diff --git a/node_modules/jwt-simple/.npmignore b/node_modules/jwt-simple/.npmignore new file mode 100644 index 0000000..10214a4 --- /dev/null +++ b/node_modules/jwt-simple/.npmignore @@ -0,0 +1,3 @@ +.vimrc* +.git* +.travis.yml diff --git a/node_modules/jwt-simple/.p/a.js b/node_modules/jwt-simple/.p/a.js new file mode 100644 index 0000000..d86b722 --- /dev/null +++ b/node_modules/jwt-simple/.p/a.js @@ -0,0 +1,8 @@ +var jwt = require('..'); +var payload = {x: 'y'}; +var token = jwt.encode(payload, 'pass', 'HS512'); +jwt.decode(token, 'pass'); +//=> + +jwt.decode(token, 'whatever') +//=> diff --git a/node_modules/jwt-simple/History.md b/node_modules/jwt-simple/History.md new file mode 100644 index 0000000..c3fe368 --- /dev/null +++ b/node_modules/jwt-simple/History.md @@ -0,0 +1,23 @@ +## 0.5.0 + +Add support for nbf and exp claims #38 @alexjab + +## 0.4.1 + +Fix version numver #32 + +## 0.4.0 + +add extra jwt header function to encode #28 + +## 0.3.1 + +* Check for lack of token #23 + +## 0.3.0 + +* Add an algorithm parameter to the decode method #16 @gregorypratt + +## 0.2.0 + +* Add the RS256 alg #7 [thedufer] diff --git a/node_modules/jwt-simple/LICENSE b/node_modules/jwt-simple/LICENSE new file mode 100644 index 0000000..c23986b --- /dev/null +++ b/node_modules/jwt-simple/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 Kazuhito Hokamura + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/jwt-simple/README.md b/node_modules/jwt-simple/README.md new file mode 100644 index 0000000..785404f --- /dev/null +++ b/node_modules/jwt-simple/README.md @@ -0,0 +1,33 @@ +# node-jwt-simple + +[JWT(JSON Web Token)](http://self-issued.info/docs/draft-jones-json-web-token.html) encode and decode module for node.js. + +## Install + + $ npm install jwt-simple + +## Usage + +```javascript +var jwt = require('jwt-simple'); +var payload = { foo: 'bar' }; +var secret = 'xxx'; + +// encode +var token = jwt.encode(payload, secret); + +// decode +var decoded = jwt.decode(token, secret); +console.log(decoded); //=> { foo: 'bar' } +``` + +### Algorithms + +By default the algorithm to encode is `HS256`. + +The supported algorithms for encoding and decoding are `HS256`, `HS384`, `HS512` and `RS256`. + +```javascript +// encode using HS512 +jwt.encode(payload, secret, 'HS512') +``` diff --git a/node_modules/jwt-simple/index.js b/node_modules/jwt-simple/index.js new file mode 100644 index 0000000..3ae0692 --- /dev/null +++ b/node_modules/jwt-simple/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/jwt'); diff --git a/node_modules/jwt-simple/lib/jwt.js b/node_modules/jwt-simple/lib/jwt.js new file mode 100644 index 0000000..532baac --- /dev/null +++ b/node_modules/jwt-simple/lib/jwt.js @@ -0,0 +1,204 @@ +/* + * jwt-simple + * + * JSON Web Token encode and decode module for node.js + * + * Copyright(c) 2011 Kazuhito Hokamura + * MIT Licensed + */ + +/** + * module dependencies + */ +var crypto = require('crypto'); + + +/** + * support algorithm mapping + */ +var algorithmMap = { + HS256: 'sha256', + HS384: 'sha384', + HS512: 'sha512', + RS256: 'RSA-SHA256' +}; + +/** + * Map algorithm to hmac or sign type, to determine which crypto function to use + */ +var typeMap = { + HS256: 'hmac', + HS384: 'hmac', + HS512: 'hmac', + RS256: 'sign' +}; + + +/** + * expose object + */ +var jwt = module.exports; + + +/** + * version + */ +jwt.version = '0.5.0'; + +/** + * Decode jwt + * + * @param {Object} token + * @param {String} key + * @param {Boolean} noVerify + * @param {String} algorithm + * @return {Object} payload + * @api public + */ +jwt.decode = function jwt_decode(token, key, noVerify, algorithm) { + // check token + if (!token) { + throw new Error('No token supplied'); + } + // check segments + var segments = token.split('.'); + if (segments.length !== 3) { + throw new Error('Not enough or too many segments'); + } + + // All segment should be base64 + var headerSeg = segments[0]; + var payloadSeg = segments[1]; + var signatureSeg = segments[2]; + + // base64 decode and parse JSON + var header = JSON.parse(base64urlDecode(headerSeg)); + var payload = JSON.parse(base64urlDecode(payloadSeg)); + + if (!noVerify) { + var signingMethod = algorithmMap[algorithm || header.alg]; + var signingType = typeMap[algorithm || header.alg]; + if (!signingMethod || !signingType) { + throw new Error('Algorithm not supported'); + } + + // Support for nbf and exp claims. + // According to the RFC, they should be in seconds. + if (payload.nbf && Date.now() < payload.nbf*1000) { + throw new Error('Token not yet active'); + } + + if (payload.exp && Date.now() > payload.exp*1000) { + throw new Error('Token expired'); + } + + // verify signature. `sign` will return base64 string. + var signingInput = [headerSeg, payloadSeg].join('.'); + if (!verify(signingInput, key, signingMethod, signingType, signatureSeg)) { + throw new Error('Signature verification failed'); + } + } + + return payload; +}; + + +/** + * Encode jwt + * + * @param {Object} payload + * @param {String} key + * @param {String} algorithm + * @param {Object} options + * @return {String} token + * @api public + */ +jwt.encode = function jwt_encode(payload, key, algorithm, options) { + // Check key + if (!key) { + throw new Error('Require key'); + } + + // Check algorithm, default is HS256 + if (!algorithm) { + algorithm = 'HS256'; + } + + var signingMethod = algorithmMap[algorithm]; + var signingType = typeMap[algorithm]; + if (!signingMethod || !signingType) { + throw new Error('Algorithm not supported'); + } + + // header, typ is fixed value. + var header = { typ: 'JWT', alg: algorithm }; + if (options && options.header) { + assignProperties(header, options.header); + } + + // create segments, all segments should be base64 string + var segments = []; + segments.push(base64urlEncode(JSON.stringify(header))); + segments.push(base64urlEncode(JSON.stringify(payload))); + segments.push(sign(segments.join('.'), key, signingMethod, signingType)); + + return segments.join('.'); +}; + +/** + * private util functions + */ + +function assignProperties(dest, source) { + for (var attr in source) { + if (source.hasOwnProperty(attr)) { + dest[attr] = source[attr]; + } + } +} + +function verify(input, key, method, type, signature) { + if(type === "hmac") { + return (signature === sign(input, key, method, type)); + } + else if(type == "sign") { + return crypto.createVerify(method) + .update(input) + .verify(key, base64urlUnescape(signature), 'base64'); + } + else { + throw new Error('Algorithm type not recognized'); + } +} + +function sign(input, key, method, type) { + var base64str; + if(type === "hmac") { + base64str = crypto.createHmac(method, key).update(input).digest('base64'); + } + else if(type == "sign") { + base64str = crypto.createSign(method).update(input).sign(key, 'base64'); + } + else { + throw new Error('Algorithm type not recognized'); + } + + return base64urlEscape(base64str); +} + +function base64urlDecode(str) { + return new Buffer(base64urlUnescape(str), 'base64').toString(); +} + +function base64urlUnescape(str) { + str += new Array(5 - str.length % 4).join('='); + return str.replace(/\-/g, '+').replace(/_/g, '/'); +} + +function base64urlEncode(str) { + return base64urlEscape(new Buffer(str).toString('base64')); +} + +function base64urlEscape(str) { + return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +} diff --git a/node_modules/jwt-simple/package.json b/node_modules/jwt-simple/package.json new file mode 100644 index 0000000..4c8b543 --- /dev/null +++ b/node_modules/jwt-simple/package.json @@ -0,0 +1,62 @@ +{ + "name": "jwt-simple", + "description": "JWT(JSON Web Token) encode and decode module", + "version": "0.5.0", + "author": { + "name": "Kazuhito Hokamura", + "email": "k.hokamura@gmail.com" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/hokaccha/node-jwt-simple.git" + }, + "devDependencies": { + "expect.js": "^0.3.1", + "istanbul": "^0.4.2", + "mocha": "^2.3.4" + }, + "scripts": { + "test": "istanbul cover _mocha test/*.js" + }, + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + }, + "keywords": [ + "jwt", + "encode", + "decode" + ], + "main": "./index", + "gitHead": "24d8d3c529fb5eee83febfdaa8bc99a85faba9f0", + "bugs": { + "url": "https://github.com/hokaccha/node-jwt-simple/issues" + }, + "homepage": "https://github.com/hokaccha/node-jwt-simple#readme", + "_id": "jwt-simple@0.5.0", + "_shasum": "06b1d5f5c2e34aca56746166f7e41e932a10e573", + "_from": "jwt-simple@latest", + "_npmVersion": "3.3.12", + "_nodeVersion": "5.5.0", + "_npmUser": { + "name": "hokaccha", + "email": "k.hokamura@gmail.com" + }, + "maintainers": [ + { + "name": "hokaccha", + "email": "k.hokamura@gmail.com" + } + ], + "dist": { + "shasum": "06b1d5f5c2e34aca56746166f7e41e932a10e573", + "tarball": "https://registry.npmjs.org/jwt-simple/-/jwt-simple-0.5.0.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/jwt-simple-0.5.0.tgz_1457707490625_0.3103703015949577" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/jwt-simple/-/jwt-simple-0.5.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/jwt-simple/test/basic.js b/node_modules/jwt-simple/test/basic.js new file mode 100644 index 0000000..99ee165 --- /dev/null +++ b/node_modules/jwt-simple/test/basic.js @@ -0,0 +1,145 @@ +var jwt = require('../index'); +var expect = require('expect.js'); +var fs = require('fs'); + +var package = require('../package.json'); + +describe('jwt', function() { + it('jwt has `version` property', function() { + expect(jwt.version).to.be.a('string'); + }); + + it('jwt has `encode` method', function() { + expect(jwt.encode).to.be.a('function'); + }); + + it('jwt has `decode` method', function() { + expect(jwt.decode).to.be.a('function'); + }); +}); + +describe('version', function() { + it('the version in the library is the same as the one in package.json', function() { + expect(jwt.version).to.equal(package.version); + }); +}); + +describe('encode', function() { + it('encode token', function() { + var token = jwt.encode({ foo: 'bar' }, 'key'); + expect(token).to.be.a('string'); + expect(token.split('.')).to.have.length(3); + }); + + it('throw an error when the key is missing', function() { + var fn = jwt.encode.bind(null, { foo: 'bar' }); + expect(fn).to.throwError(/Require key/); + }); + + it('throw an error when the specified algorithm is not supported', function() { + var fn = jwt.encode.bind(null, { foo: 'bar' }, 'some_key', 'FooBar256'); + expect(fn).to.throwError(/Algorithm not supported/); + }); +}); + +describe('decode', function() { + var key = 'key'; + var obj = { foo: 'bar' }; + var token = jwt.encode(obj, key); + + it('decode token', function() { + var obj2 = jwt.decode(token, key); + expect(obj2).to.eql(obj); + }); + + it('throw an error when no token is provided', function() { + var fn = jwt.decode.bind(null, null, key); + expect(fn).to.throwError(/No token supplied/); + }); + + it('throw an error when the token is not correctly formatted', function() { + var fn = jwt.decode.bind(null, 'foo.bar', key); + expect(fn).to.throwError(/Not enough or too many segments/); + }); + + it('throw an error when the specified algorithm is not supported', function() { + var fn = jwt.decode.bind(null, token, key, false, 'FooBar256'); + expect(fn).to.throwError(/Algorithm not supported/); + }); + + it('throw an error when the signature verification fails', function() { + var fn = jwt.decode.bind(null, token, 'invalid_key'); + expect(fn).to.throwError(/Signature verification failed/); + }); + + it('throw an error when the token is not yet active (optional nbf claim)', function() { + var nbf = (Date.now() + 1000) / 1000; + var token = jwt.encode({ foo: 'bar', nbf: nbf }, key); + var fn = jwt.decode.bind(null, token, key); + expect(fn).to.throwError(/Token not yet active/); + }); + + it('throw an error when the token has expired (optional exp claim)', function() { + var exp = (Date.now() - 1000) / 1000; + var token = jwt.encode({ foo: 'bar', exp: exp }, key); + var fn = jwt.decode.bind(null, token, key); + expect(fn).to.throwError(/Token expired/); + }); + + it('do not throw any error when verification is disabled', function() { + var obj = { foo: 'bar' }; + var key = 'key'; + var token = jwt.encode(obj, key); + var fn1 = jwt.decode.bind(null, token, 'invalid_key1'); + var fn2 = jwt.decode.bind(null, token, 'invalid_key2', true); + expect(fn1).to.throwError(/Signature verification failed/); + expect(fn2()).to.eql(obj); + }); + + it('decode token given algorithm', function() { + var obj = { foo: 'bar' }; + var key = 'key'; + var token = jwt.encode(obj, key, 'HS512'); + var obj2 = jwt.decode(token, key, false, 'HS512'); + expect(obj2).to.eql(obj); + expect(jwt.decode.bind(null, token, key, false, 'HS256')).to.throwError(/Signature verification failed/); + }); + + describe('RS256', function() { + var obj = { foo: 'bar' }; + var pem = fs.readFileSync(__dirname + '/test.pem').toString('ascii'); + var cert = fs.readFileSync(__dirname + '/test.crt').toString('ascii'); + var alg = 'RS256'; + + it('can add jwt header by options.header', function() { + var token = jwt.encode(obj, pem, alg, {header: {kid: 'keyidX'}}); + var obj2 = jwt.decode(token, cert); + expect(obj2).to.eql(obj); + + var jwtHeader = token.split('.')[0]; + expect(JSON.parse(base64urlDecode(jwtHeader))).to.eql({typ:'JWT',alg:alg,kid:'keyidX'}); + }); + + + it('decode token given RS256 algorithm', function() { + var token = jwt.encode(obj, pem, alg); + var obj2 = jwt.decode(token, cert); + expect(obj2).to.eql(obj); + }); + + it('throw an error when the key is invalid', function() { + var token = jwt.encode(obj, pem, alg); + var obj2 = jwt.decode(token, cert); + expect(jwt.decode.bind(null, token, 'invalid_key')).to.throwError(); + }); + }); +}); + +function base64urlDecode(str) { + return new Buffer(base64urlUnescape(str), 'base64').toString(); +} + +function base64urlUnescape(str) { + str += new Array(5 - str.length % 4).join('='); + return str.replace(/\-/g, '+').replace(/_/g, '/'); +} diff --git a/node_modules/jwt-simple/test/test.crt b/node_modules/jwt-simple/test/test.crt new file mode 100644 index 0000000..e933ff0 --- /dev/null +++ b/node_modules/jwt-simple/test/test.crt @@ -0,0 +1,13 @@ +-----BEGIN CERTIFICATE----- +MIICATCCAWoCCQDoLzF89AVR9jANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB +VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0 +cyBQdHkgTHRkMB4XDTE0MDMxODA5MzgzOVoXDTE1MDMxODA5MzgzOVowRTELMAkG +A1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0 +IFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAxkf+ +aQuof/FiI1ejRl/385JhGbOq9ZUD0Ma7FELpkW+Wb9k3dxFRXjIeZgbMr5kUtzGv +jMA+IJpMPmqHOLMUG731xxmXoHphlhWKV1TTR8OXduIxRB+frVhYfp0nOAZroO+5 +sXBrGwCcFFjsDBhLLf7R1d9WdkS/LQ0rBi7GvaMCAwEAATANBgkqhkiG9w0BAQUF +AAOBgQCNxfthoxLOFZidvviG6aFjFgY35eFqv3RLHWAVBWQBHfjczph/r5mlT06z +AOKO7yp23Gi2dyBYaeq1u6n7iyMp9htYee8Y+Erlp6vurvi9S+/8mNVAPBtQ1kNw +KvzMTvylD2zWjopwMb9bfSKKT5pe7pZ7CS6Y5T8lM9yZlMBhHQ== +-----END CERTIFICATE----- diff --git a/node_modules/jwt-simple/test/test.pem b/node_modules/jwt-simple/test/test.pem new file mode 100644 index 0000000..3c622ea --- /dev/null +++ b/node_modules/jwt-simple/test/test.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQDGR/5pC6h/8WIjV6NGX/fzkmEZs6r1lQPQxrsUQumRb5Zv2Td3 +EVFeMh5mBsyvmRS3Ma+MwD4gmkw+aoc4sxQbvfXHGZegemGWFYpXVNNHw5d24jFE +H5+tWFh+nSc4Bmug77mxcGsbAJwUWOwMGEst/tHV31Z2RL8tDSsGLsa9owIDAQAB +AoGAasmbWzfMKBv4ntA0P1KwV54ebZk2Gc2HoIlneCIRaSKQAu0Z0iahi/myJYDD +/E6VuZQo18UxsJ1pMrRs3zyTNunD0hzVgnqz46nMGeMFdrsFcFQIFEtTtxngEyiy +zJrO+5oUKX6CIpRZhIBGWk0hKETm9WJ5LMPf48A9PcQGvgECQQD5k7NOy72adPt9 +9CSOIsaXeovu0ADmA6sDPTtCMzyXWiq6igN9q4gwBHmEfq/272l8CSfbVHAZL1ym +WtuLb0srAkEAy2JW3NgxNHn2DdcodEz7QBnRd7qO+qddNv+MoimsbFCpM+lUOXPn +IlFVA7IZYMDONwK+qHUIR8kWB2pKqGo7aQJACjqReMNE7BWrUQg2j1TBiufM4GbK +AqNX2PQjf50V+KYLZkXNytLC7CTizhlbIOXDDwBZD9YwGfgk9fR3VwmirQJBALbm +IKdJ5DYE17lqm/66m9fxX+YD50CR8cnb1mSehWiCwSbl1dA04s6BxaolJ51Sxh/C +YCKt3FxyAVV5yNnbbsECQQCZCrGcqIqFHuEYOhLMw0JGlRxVeR2PhWCaPX5M0s+9 +coyZRyO5MAWBfXDPF552Yqah1FRk+DX2qidkc27P+1QT +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/.npmignore b/node_modules/meteor-node-stubs/.npmignore new file mode 100644 index 0000000..07e6e47 --- /dev/null +++ b/node_modules/meteor-node-stubs/.npmignore @@ -0,0 +1 @@ +/node_modules diff --git a/node_modules/meteor-node-stubs/LICENSE b/node_modules/meteor-node-stubs/LICENSE new file mode 100644 index 0000000..1b47ab5 --- /dev/null +++ b/node_modules/meteor-node-stubs/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Ben Newman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/README.md b/node_modules/meteor-node-stubs/README.md new file mode 100644 index 0000000..659a1a3 --- /dev/null +++ b/node_modules/meteor-node-stubs/README.md @@ -0,0 +1,2 @@ +# node-stubs +Stub implementations of Node built-in modules, a la Browserify diff --git a/node_modules/meteor-node-stubs/build-deps.js b/node_modules/meteor-node-stubs/build-deps.js new file mode 100644 index 0000000..2c3593c --- /dev/null +++ b/node_modules/meteor-node-stubs/build-deps.js @@ -0,0 +1,29 @@ +var fs = require("fs"); +var path = require("path"); +var depsDir = path.join(__dirname, "deps"); +var map = require("./map.json"); + +// Each file in the `deps` directory expresses the dependencies of a stub. +// For example, `deps/http.js` calls `require("http-browserify")` to +// indicate that the `http` stub depends on the `http-browserify` package. +// This makes it easy for a bundling tool like Browserify, Webpack, or +// Meteor to include the appropriate package dependencies by depending on +// `meteor-node-stubs/deps/http` rather than having to know how the `http` +// stub is implemented. Some modules in the `deps` directory are empty, +// such as `deps/fs.js`, which indicates that no dependencies need to be +// bundled. Note that these modules should not be `require`d at runtime, +// but merely scanned at bundling time. + +fs.mkdir(depsDir, function () { + require("rimraf")("deps/*.js", function (error) { + if (error) throw error; + Object.keys(map).forEach(function (id) { + fs.writeFile( + path.join(depsDir, id + ".js"), + typeof map[id] === "string" + ? "require(" + JSON.stringify(map[id]) + ");\n" + : "" + ); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/deps/_stream_duplex.js b/node_modules/meteor-node-stubs/deps/_stream_duplex.js new file mode 100644 index 0000000..4e97dce --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/_stream_duplex.js @@ -0,0 +1 @@ +require("readable-stream/duplex.js"); diff --git a/node_modules/meteor-node-stubs/deps/_stream_passthrough.js b/node_modules/meteor-node-stubs/deps/_stream_passthrough.js new file mode 100644 index 0000000..6ce74e2 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/_stream_passthrough.js @@ -0,0 +1 @@ +require("readable-stream/passthrough.js"); diff --git a/node_modules/meteor-node-stubs/deps/_stream_readable.js b/node_modules/meteor-node-stubs/deps/_stream_readable.js new file mode 100644 index 0000000..4af03c5 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/_stream_readable.js @@ -0,0 +1 @@ +require("readable-stream/readable.js"); diff --git a/node_modules/meteor-node-stubs/deps/_stream_transform.js b/node_modules/meteor-node-stubs/deps/_stream_transform.js new file mode 100644 index 0000000..e9b568c --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/_stream_transform.js @@ -0,0 +1 @@ +require("readable-stream/transform.js"); diff --git a/node_modules/meteor-node-stubs/deps/_stream_writable.js b/node_modules/meteor-node-stubs/deps/_stream_writable.js new file mode 100644 index 0000000..201badf --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/_stream_writable.js @@ -0,0 +1 @@ +require("readable-stream/writable.js"); diff --git a/node_modules/meteor-node-stubs/deps/assert.js b/node_modules/meteor-node-stubs/deps/assert.js new file mode 100644 index 0000000..42b0210 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/assert.js @@ -0,0 +1 @@ +require("assert/"); diff --git a/node_modules/meteor-node-stubs/deps/buffer.js b/node_modules/meteor-node-stubs/deps/buffer.js new file mode 100644 index 0000000..13d7e91 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/buffer.js @@ -0,0 +1 @@ +require("buffer/"); diff --git a/node_modules/meteor-node-stubs/deps/child_process.js b/node_modules/meteor-node-stubs/deps/child_process.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/cluster.js b/node_modules/meteor-node-stubs/deps/cluster.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/console.js b/node_modules/meteor-node-stubs/deps/console.js new file mode 100644 index 0000000..b59a074 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/console.js @@ -0,0 +1 @@ +require("console-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/constants.js b/node_modules/meteor-node-stubs/deps/constants.js new file mode 100644 index 0000000..5f6960e --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/constants.js @@ -0,0 +1 @@ +require("constants-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/crypto.js b/node_modules/meteor-node-stubs/deps/crypto.js new file mode 100644 index 0000000..5c05ba2 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/crypto.js @@ -0,0 +1 @@ +require("crypto-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/dgram.js b/node_modules/meteor-node-stubs/deps/dgram.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/dns.js b/node_modules/meteor-node-stubs/deps/dns.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/domain.js b/node_modules/meteor-node-stubs/deps/domain.js new file mode 100644 index 0000000..bbd49dc --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/domain.js @@ -0,0 +1 @@ +require("domain-browser"); diff --git a/node_modules/meteor-node-stubs/deps/events.js b/node_modules/meteor-node-stubs/deps/events.js new file mode 100644 index 0000000..21c061a --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/events.js @@ -0,0 +1 @@ +require("events/"); diff --git a/node_modules/meteor-node-stubs/deps/fs.js b/node_modules/meteor-node-stubs/deps/fs.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/http.js b/node_modules/meteor-node-stubs/deps/http.js new file mode 100644 index 0000000..a2c6ea8 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/http.js @@ -0,0 +1 @@ +require("http-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/https.js b/node_modules/meteor-node-stubs/deps/https.js new file mode 100644 index 0000000..4be36ca --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/https.js @@ -0,0 +1 @@ +require("https-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/module.js b/node_modules/meteor-node-stubs/deps/module.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/net.js b/node_modules/meteor-node-stubs/deps/net.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/os.js b/node_modules/meteor-node-stubs/deps/os.js new file mode 100644 index 0000000..9b8ce2b --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/os.js @@ -0,0 +1 @@ +require("os-browserify/browser.js"); diff --git a/node_modules/meteor-node-stubs/deps/path.js b/node_modules/meteor-node-stubs/deps/path.js new file mode 100644 index 0000000..10f43ec --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/path.js @@ -0,0 +1 @@ +require("path-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/process.js b/node_modules/meteor-node-stubs/deps/process.js new file mode 100644 index 0000000..67389c2 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/process.js @@ -0,0 +1 @@ +require("process/browser.js"); diff --git a/node_modules/meteor-node-stubs/deps/punycode.js b/node_modules/meteor-node-stubs/deps/punycode.js new file mode 100644 index 0000000..ee5240d --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/punycode.js @@ -0,0 +1 @@ +require("punycode/"); diff --git a/node_modules/meteor-node-stubs/deps/querystring.js b/node_modules/meteor-node-stubs/deps/querystring.js new file mode 100644 index 0000000..f42c175 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/querystring.js @@ -0,0 +1 @@ +require("querystring-es3/"); diff --git a/node_modules/meteor-node-stubs/deps/readline.js b/node_modules/meteor-node-stubs/deps/readline.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/repl.js b/node_modules/meteor-node-stubs/deps/repl.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/stream.js b/node_modules/meteor-node-stubs/deps/stream.js new file mode 100644 index 0000000..f2fe842 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/stream.js @@ -0,0 +1 @@ +require("stream-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/string_decoder.js b/node_modules/meteor-node-stubs/deps/string_decoder.js new file mode 100644 index 0000000..77044e5 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/string_decoder.js @@ -0,0 +1 @@ +require("string_decoder/"); diff --git a/node_modules/meteor-node-stubs/deps/sys.js b/node_modules/meteor-node-stubs/deps/sys.js new file mode 100644 index 0000000..0d21934 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/sys.js @@ -0,0 +1 @@ +require("util/util.js"); diff --git a/node_modules/meteor-node-stubs/deps/timers.js b/node_modules/meteor-node-stubs/deps/timers.js new file mode 100644 index 0000000..713c170 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/timers.js @@ -0,0 +1 @@ +require("timers-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/tls.js b/node_modules/meteor-node-stubs/deps/tls.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/meteor-node-stubs/deps/tty.js b/node_modules/meteor-node-stubs/deps/tty.js new file mode 100644 index 0000000..4fff352 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/tty.js @@ -0,0 +1 @@ +require("tty-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/url.js b/node_modules/meteor-node-stubs/deps/url.js new file mode 100644 index 0000000..a6c1d89 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/url.js @@ -0,0 +1 @@ +require("url/"); diff --git a/node_modules/meteor-node-stubs/deps/util.js b/node_modules/meteor-node-stubs/deps/util.js new file mode 100644 index 0000000..0d21934 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/util.js @@ -0,0 +1 @@ +require("util/util.js"); diff --git a/node_modules/meteor-node-stubs/deps/vm.js b/node_modules/meteor-node-stubs/deps/vm.js new file mode 100644 index 0000000..fc311e4 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/vm.js @@ -0,0 +1 @@ +require("vm-browserify"); diff --git a/node_modules/meteor-node-stubs/deps/zlib.js b/node_modules/meteor-node-stubs/deps/zlib.js new file mode 100644 index 0000000..71949d0 --- /dev/null +++ b/node_modules/meteor-node-stubs/deps/zlib.js @@ -0,0 +1 @@ +require("browserify-zlib"); diff --git a/node_modules/meteor-node-stubs/index.js b/node_modules/meteor-node-stubs/index.js new file mode 100644 index 0000000..15cd191 --- /dev/null +++ b/node_modules/meteor-node-stubs/index.js @@ -0,0 +1,28 @@ +var map = require("./map.json"); +var meteorAliases = {}; + +Object.keys(map).forEach(function (id) { + if (typeof map[id] === "string") { + try { + exports[id] = meteorAliases[id + ".js"] = + require.resolve(map[id]); + } catch (e) { + // Resolution can fail at runtime if the stub was not included in the + // bundle because nothing depended on it. + } + } else { + exports[id] = map[id]; + meteorAliases[id + ".js"] = function(){}; + } +}); + +if (typeof meteorInstall === "function") { + meteorInstall({ + // Install the aliases into a node_modules directory one level up from + // the root directory, so that they do not clutter the namespace + // available to apps and packages. + "..": { + node_modules: meteorAliases + } + }); +} diff --git a/node_modules/meteor-node-stubs/map.json b/node_modules/meteor-node-stubs/map.json new file mode 100644 index 0000000..438c0d8 --- /dev/null +++ b/node_modules/meteor-node-stubs/map.json @@ -0,0 +1,40 @@ +{ + "assert": "assert/", + "buffer": "buffer/", + "child_process": null, + "cluster": null, + "console": "console-browserify", + "constants": "constants-browserify", + "crypto": "crypto-browserify", + "dgram": null, + "dns": null, + "domain": "domain-browser", + "events": "events/", + "fs": null, + "http": "http-browserify", + "https": "https-browserify", + "module": null, + "net": null, + "os": "os-browserify/browser.js", + "path": "path-browserify", + "process": "process/browser.js", + "punycode": "punycode/", + "querystring": "querystring-es3/", + "readline": null, + "repl": null, + "stream": "stream-browserify", + "_stream_duplex": "readable-stream/duplex.js", + "_stream_passthrough": "readable-stream/passthrough.js", + "_stream_readable": "readable-stream/readable.js", + "_stream_transform": "readable-stream/transform.js", + "_stream_writable": "readable-stream/writable.js", + "string_decoder": "string_decoder/", + "sys": "util/util.js", + "timers": "timers-browserify", + "tls": null, + "tty": "tty-browserify", + "url": "url/", + "util": "util/util.js", + "vm": "vm-browserify", + "zlib": "browserify-zlib" +} diff --git a/node_modules/meteor-node-stubs/node_modules/assert/.npmignore b/node_modules/meteor-node-stubs/node_modules/assert/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/assert/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/assert/.travis.yml b/node_modules/meteor-node-stubs/node_modules/assert/.travis.yml new file mode 100644 index 0000000..b5f7f83 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/assert/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: +- '0.10' +env: + global: + - secure: qThuKBZQtkooAvzaYldECGNqvKGPRTnXx62IVyhSbFlsCY1VCmjhLldhyPDiZQ3JqL1XvSkK8OMDupiHqZnNE0nGijoO4M/kaEdjBB+jpjg3f8I6te2SNU935SbkfY9KHAaFXMZwdcq7Fk932AxWEu+FMSDM+080wNKpEATXDe4= + - secure: O/scKjHLRcPN5ILV5qsSkksQ7qcZQdHWEUUPItmj/4+vmCc28bHpicoUxXG5A96iHvkBbdmky/nGCg464ZaNLk68m6hfEMDAR3J6mhM2Pf5C4QI/LlFlR1fob9sQ8lztwSGOItwdK8Rfrgb30RRVV71f6FxnaJ6PKMuMNT5S1AQ= diff --git a/node_modules/meteor-node-stubs/node_modules/assert/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/assert/.zuul.yml new file mode 100644 index 0000000..eeb1386 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/assert/.zuul.yml @@ -0,0 +1,10 @@ +ui: mocha-qunit +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: latest + - name: ie + version: 9..latest diff --git a/node_modules/meteor-node-stubs/node_modules/assert/LICENSE b/node_modules/meteor-node-stubs/node_modules/assert/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/assert/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/assert/README.md b/node_modules/meteor-node-stubs/node_modules/assert/README.md new file mode 100644 index 0000000..6d252ab --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/assert/README.md @@ -0,0 +1,64 @@ +# assert + +[![Build Status](https://travis-ci.org/defunctzombie/commonjs-assert.svg?branch=master)](https://travis-ci.org/defunctzombie/commonjs-assert) + +This module is used for writing unit tests for your applications, you can access it with require('assert'). + +The API is derived from the [commonjs 1.0 unit testing](http://wiki.commonjs.org/wiki/Unit_Testing/1.0) spec and the [node.js assert module](http://nodejs.org/api/assert.html) + +## assert.fail(actual, expected, message, operator) +Throws an exception that displays the values for actual and expected separated by the provided operator. + +## assert(value, message), assert.ok(value, [message]) +Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message); + +## assert.equal(actual, expected, [message]) +Tests shallow, coercive equality with the equal comparison operator ( == ). + +## assert.notEqual(actual, expected, [message]) +Tests shallow, coercive non-equality with the not equal comparison operator ( != ). + +## assert.deepEqual(actual, expected, [message]) +Tests for deep equality. + +## assert.notDeepEqual(actual, expected, [message]) +Tests for any deep inequality. + +## assert.strictEqual(actual, expected, [message]) +Tests strict equality, as determined by the strict equality operator ( === ) + +## assert.notStrictEqual(actual, expected, [message]) +Tests strict non-equality, as determined by the strict not equal operator ( !== ) + +## assert.throws(block, [error], [message]) +Expects block to throw an error. error can be constructor, regexp or validation function. + +Validate instanceof using constructor: + +```javascript +assert.throws(function() { throw new Error("Wrong value"); }, Error); +``` + +Validate error message using RegExp: + +```javascript +assert.throws(function() { throw new Error("Wrong value"); }, /value/); +``` + +Custom error validation: + +```javascript +assert.throws(function() { + throw new Error("Wrong value"); +}, function(err) { + if ( (err instanceof Error) && /value/.test(err) ) { + return true; + } +}, "unexpected error"); +``` + +## assert.doesNotThrow(block, [message]) +Expects block not to throw an error, see assert.throws for details. + +## assert.ifError(value) +Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks. diff --git a/node_modules/meteor-node-stubs/node_modules/assert/assert.js b/node_modules/meteor-node-stubs/node_modules/assert/assert.js new file mode 100644 index 0000000..59d8985 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/assert/assert.js @@ -0,0 +1,359 @@ +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// when used in node, this will actually load the util module we depend on +// versus loading the builtin util module as happens otherwise +// this is a bug in node module loading as far as I am concerned +var util = require('util/'); + +var pSlice = Array.prototype.slice; +var hasOwn = Object.prototype.hasOwnProperty; + +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } + else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = stackStartFunction.name; + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && !isFinite(value)) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); + } + return value; +} + +function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} + +function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +function _deepEqual(actual, expected) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; + + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } + + return true; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) { + return a === b; + } + var aIsArgs = isArguments(a), + bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b); + } + var ka = objectKeys(a), + kb = objectKeys(b), + key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key])) return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (util.isString(expected)) { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws.apply(this, [true].concat(pSlice.call(arguments))); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); +}; + +assert.ifError = function(err) { if (err) {throw err;}}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/assert/package.json b/node_modules/meteor-node-stubs/node_modules/assert/package.json new file mode 100644 index 0000000..5935862 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/assert/package.json @@ -0,0 +1,34 @@ +{ + "name": "assert", + "description": "commonjs assert - node.js api compatible", + "keywords": [ + "assert" + ], + "version": "1.3.0", + "homepage": "https://github.com/defunctzombie/commonjs-assert", + "repository": { + "type": "git", + "url": "git://github.com/defunctzombie/commonjs-assert.git" + }, + "main": "./assert.js", + "dependencies": { + "util": "0.10.3" + }, + "devDependencies": { + "zuul": "~1.10.2", + "mocha": "~1.21.4" + }, + "license": "MIT", + "scripts": { + "test": "mocha --ui qunit test.js && zuul -- test.js" + }, + "readme": "# assert\n\n[![Build Status](https://travis-ci.org/defunctzombie/commonjs-assert.svg?branch=master)](https://travis-ci.org/defunctzombie/commonjs-assert)\n\nThis module is used for writing unit tests for your applications, you can access it with require('assert').\n\nThe API is derived from the [commonjs 1.0 unit testing](http://wiki.commonjs.org/wiki/Unit_Testing/1.0) spec and the [node.js assert module](http://nodejs.org/api/assert.html)\n\n## assert.fail(actual, expected, message, operator)\nThrows an exception that displays the values for actual and expected separated by the provided operator.\n\n## assert(value, message), assert.ok(value, [message])\nTests if value is truthy, it is equivalent to assert.equal(true, !!value, message);\n\n## assert.equal(actual, expected, [message])\nTests shallow, coercive equality with the equal comparison operator ( == ).\n\n## assert.notEqual(actual, expected, [message])\nTests shallow, coercive non-equality with the not equal comparison operator ( != ).\n\n## assert.deepEqual(actual, expected, [message])\nTests for deep equality.\n\n## assert.notDeepEqual(actual, expected, [message])\nTests for any deep inequality.\n\n## assert.strictEqual(actual, expected, [message])\nTests strict equality, as determined by the strict equality operator ( === )\n\n## assert.notStrictEqual(actual, expected, [message])\nTests strict non-equality, as determined by the strict not equal operator ( !== )\n\n## assert.throws(block, [error], [message])\nExpects block to throw an error. error can be constructor, regexp or validation function.\n\nValidate instanceof using constructor:\n\n```javascript\nassert.throws(function() { throw new Error(\"Wrong value\"); }, Error);\n```\n\nValidate error message using RegExp:\n\n```javascript\nassert.throws(function() { throw new Error(\"Wrong value\"); }, /value/);\n```\n\nCustom error validation:\n\n```javascript\nassert.throws(function() {\n throw new Error(\"Wrong value\");\n}, function(err) {\n if ( (err instanceof Error) && /value/.test(err) ) {\n return true;\n }\n}, \"unexpected error\");\n```\n\n## assert.doesNotThrow(block, [message])\nExpects block not to throw an error, see assert.throws for details.\n\n## assert.ifError(value)\nTests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/defunctzombie/commonjs-assert/issues" + }, + "_id": "assert@1.3.0", + "_shasum": "03939a622582a812cc202320a0b9a56c9b815849", + "_resolved": "https://registry.npmjs.org/assert/-/assert-1.3.0.tgz", + "_from": "https://registry.npmjs.org/assert/-/assert-1.3.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/assert/test.js b/node_modules/meteor-node-stubs/node_modules/assert/test.js new file mode 100644 index 0000000..981e7a8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/assert/test.js @@ -0,0 +1,343 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('./'); + +var keys = Object.keys; + +function makeBlock(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function() { + return f.apply(this, args); + }; +} + +test('assert.ok', function () { + assert.throws(makeBlock(assert, false), assert.AssertionError, 'ok(false)'); + + assert.doesNotThrow(makeBlock(assert, true), assert.AssertionError, 'ok(true)'); + + assert.doesNotThrow(makeBlock(assert, 'test', 'ok(\'test\')')); + + assert.throws(makeBlock(assert.ok, false), + assert.AssertionError, 'ok(false)'); + + assert.doesNotThrow(makeBlock(assert.ok, true), + assert.AssertionError, 'ok(true)'); + + assert.doesNotThrow(makeBlock(assert.ok, 'test'), 'ok(\'test\')'); +}); + +test('assert.equal', function () { + assert.throws(makeBlock(assert.equal, true, false), assert.AssertionError, 'equal'); + + assert.doesNotThrow(makeBlock(assert.equal, null, null), 'equal'); + + assert.doesNotThrow(makeBlock(assert.equal, undefined, undefined), 'equal'); + + assert.doesNotThrow(makeBlock(assert.equal, null, undefined), 'equal'); + + assert.doesNotThrow(makeBlock(assert.equal, true, true), 'equal'); + + assert.doesNotThrow(makeBlock(assert.equal, 2, '2'), 'equal'); + + assert.doesNotThrow(makeBlock(assert.notEqual, true, false), 'notEqual'); + + assert.throws(makeBlock(assert.notEqual, true, true), + assert.AssertionError, 'notEqual'); +}); + +test('assert.strictEqual', function () { + assert.throws(makeBlock(assert.strictEqual, 2, '2'), + assert.AssertionError, 'strictEqual'); + + assert.throws(makeBlock(assert.strictEqual, null, undefined), + assert.AssertionError, 'strictEqual'); + + assert.doesNotThrow(makeBlock(assert.notStrictEqual, 2, '2'), 'notStrictEqual'); +}); + +test('assert.deepEqual - 7.2', function () { + assert.doesNotThrow(makeBlock(assert.deepEqual, new Date(2000, 3, 14), + new Date(2000, 3, 14)), 'deepEqual date'); + + assert.throws(makeBlock(assert.deepEqual, new Date(), new Date(2000, 3, 14)), + assert.AssertionError, + 'deepEqual date'); +}); + +test('assert.deepEqual - 7.3', function () { + assert.doesNotThrow(makeBlock(assert.deepEqual, /a/, /a/)); + assert.doesNotThrow(makeBlock(assert.deepEqual, /a/g, /a/g)); + assert.doesNotThrow(makeBlock(assert.deepEqual, /a/i, /a/i)); + assert.doesNotThrow(makeBlock(assert.deepEqual, /a/m, /a/m)); + assert.doesNotThrow(makeBlock(assert.deepEqual, /a/igm, /a/igm)); + assert.throws(makeBlock(assert.deepEqual, /ab/, /a/)); + assert.throws(makeBlock(assert.deepEqual, /a/g, /a/)); + assert.throws(makeBlock(assert.deepEqual, /a/i, /a/)); + assert.throws(makeBlock(assert.deepEqual, /a/m, /a/)); + assert.throws(makeBlock(assert.deepEqual, /a/igm, /a/im)); + + var re1 = /a/; + re1.lastIndex = 3; + assert.throws(makeBlock(assert.deepEqual, re1, /a/)); +}); + +test('assert.deepEqual - 7.4', function () { + assert.doesNotThrow(makeBlock(assert.deepEqual, 4, '4'), 'deepEqual == check'); + assert.doesNotThrow(makeBlock(assert.deepEqual, true, 1), 'deepEqual == check'); + assert.throws(makeBlock(assert.deepEqual, 4, '5'), + assert.AssertionError, + 'deepEqual == check'); +}); + +test('assert.deepEqual - 7.5', function () { + // having the same number of owned properties && the same set of keys + assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4}, {a: 4})); + assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'})); + assert.doesNotThrow(makeBlock(assert.deepEqual, [4], ['4'])); + assert.throws(makeBlock(assert.deepEqual, {a: 4}, {a: 4, b: true}), + assert.AssertionError); + assert.doesNotThrow(makeBlock(assert.deepEqual, ['a'], {0: 'a'})); + //(although not necessarily the same order), + assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4})); + var a1 = [1, 2, 3]; + var a2 = [1, 2, 3]; + a1.a = 'test'; + a1.b = true; + a2.b = true; + a2.a = 'test'; + assert.throws(makeBlock(assert.deepEqual, keys(a1), keys(a2)), + assert.AssertionError); + assert.doesNotThrow(makeBlock(assert.deepEqual, a1, a2)); +}); + +test('assert.deepEqual - instances', function () { + // having an identical prototype property + var nbRoot = { + toString: function() { return this.first + ' ' + this.last; } + }; + + function nameBuilder(first, last) { + this.first = first; + this.last = last; + return this; + } + nameBuilder.prototype = nbRoot; + + function nameBuilder2(first, last) { + this.first = first; + this.last = last; + return this; + } + nameBuilder2.prototype = nbRoot; + + var nb1 = new nameBuilder('Ryan', 'Dahl'); + var nb2 = new nameBuilder2('Ryan', 'Dahl'); + + assert.doesNotThrow(makeBlock(assert.deepEqual, nb1, nb2)); + + nameBuilder2.prototype = Object; + nb2 = new nameBuilder2('Ryan', 'Dahl'); + assert.throws(makeBlock(assert.deepEqual, nb1, nb2), assert.AssertionError); +}); + +test('assert.deepEqual - ES6 primitives', function () { + assert.throws(makeBlock(assert.deepEqual, null, {}), assert.AssertionError); + assert.throws(makeBlock(assert.deepEqual, undefined, {}), assert.AssertionError); + assert.throws(makeBlock(assert.deepEqual, 'a', ['a']), assert.AssertionError); + assert.throws(makeBlock(assert.deepEqual, 'a', {0: 'a'}), assert.AssertionError); + assert.throws(makeBlock(assert.deepEqual, 1, {}), assert.AssertionError); + assert.throws(makeBlock(assert.deepEqual, true, {}), assert.AssertionError); + if (typeof Symbol === 'symbol') { + assert.throws(makeBlock(assert.deepEqual, Symbol(), {}), assert.AssertionError); + } +}); + +test('assert.deepEqual - object wrappers', function () { + assert.doesNotThrow(makeBlock(assert.deepEqual, new String('a'), ['a'])); + assert.doesNotThrow(makeBlock(assert.deepEqual, new String('a'), {0: 'a'})); + assert.doesNotThrow(makeBlock(assert.deepEqual, new Number(1), {})); + assert.doesNotThrow(makeBlock(assert.deepEqual, new Boolean(true), {})); +}); + +function thrower(errorConstructor) { + throw new errorConstructor('test'); +} + +test('assert - Testing the throwing', function () { + var aethrow = makeBlock(thrower, assert.AssertionError); + aethrow = makeBlock(thrower, assert.AssertionError); + + // the basic calls work + assert.throws(makeBlock(thrower, assert.AssertionError), + assert.AssertionError, 'message'); + assert.throws(makeBlock(thrower, assert.AssertionError), assert.AssertionError); + assert.throws(makeBlock(thrower, assert.AssertionError)); + + // if not passing an error, catch all. + assert.throws(makeBlock(thrower, TypeError)); + + // when passing a type, only catch errors of the appropriate type + var threw = false; + try { + assert.throws(makeBlock(thrower, TypeError), assert.AssertionError); + } catch (e) { + threw = true; + assert.ok(e instanceof TypeError, 'type'); + } + assert.equal(true, threw, + 'a.throws with an explicit error is eating extra errors', + assert.AssertionError); + threw = false; + + // doesNotThrow should pass through all errors + try { + assert.doesNotThrow(makeBlock(thrower, TypeError), assert.AssertionError); + } catch (e) { + threw = true; + assert.ok(e instanceof TypeError); + } + assert.equal(true, threw, + 'a.doesNotThrow with an explicit error is eating extra errors'); + + // key difference is that throwing our correct error makes an assertion error + try { + assert.doesNotThrow(makeBlock(thrower, TypeError), TypeError); + } catch (e) { + threw = true; + assert.ok(e instanceof assert.AssertionError); + } + assert.equal(true, threw, + 'a.doesNotThrow is not catching type matching errors'); +}); + +test('assert.ifError', function () { + assert.throws(function() {assert.ifError(new Error('test error'))}); + assert.doesNotThrow(function() {assert.ifError(null)}); + assert.doesNotThrow(function() {assert.ifError()}); +}); + +test('assert - make sure that validating using constructor really works', function () { + var threw = false; + try { + assert.throws( + function() { + throw ({}); + }, + Array + ); + } catch (e) { + threw = true; + } + assert.ok(threw, 'wrong constructor validation'); +}); + +test('assert - use a RegExp to validate error message', function () { + assert.throws(makeBlock(thrower, TypeError), /test/); +}); + +test('assert - se a fn to validate error object', function () { + assert.throws(makeBlock(thrower, TypeError), function(err) { + if ((err instanceof TypeError) && /test/.test(err)) { + return true; + } + }); +}); + +test('assert - Make sure deepEqual doesn\'t loop forever on circular refs', function () { + var b = {}; + b.b = b; + + var c = {}; + c.b = c; + + var gotError = false; + try { + assert.deepEqual(b, c); + } catch (e) { + gotError = true; + } + + assert.ok(gotError); +}); + +test('assert - Ensure reflexivity of deepEqual with `arguments` objects', function() { + var args = (function() { return arguments; })(); + assert.throws(makeBlock(assert.deepEqual, [], args), assert.AssertionError); + assert.throws(makeBlock(assert.deepEqual, args, []), assert.AssertionError); +}); + +test('assert - test assertion message', function () { + function testAssertionMessage(actual, expected) { + try { + assert.equal(actual, ''); + } catch (e) { + assert.equal(e.toString(), + ['AssertionError:', expected, '==', '""'].join(' ')); + } + } + testAssertionMessage(undefined, '"undefined"'); + testAssertionMessage(null, 'null'); + testAssertionMessage(true, 'true'); + testAssertionMessage(false, 'false'); + testAssertionMessage(0, '0'); + testAssertionMessage(100, '100'); + testAssertionMessage(NaN, '"NaN"'); + testAssertionMessage(Infinity, '"Infinity"'); + testAssertionMessage(-Infinity, '"-Infinity"'); + testAssertionMessage('', '""'); + testAssertionMessage('foo', '"foo"'); + testAssertionMessage([], '[]'); + testAssertionMessage([1, 2, 3], '[1,2,3]'); + testAssertionMessage(/a/, '"/a/"'); + testAssertionMessage(function f() {}, '"function f() {}"'); + testAssertionMessage({}, '{}'); + testAssertionMessage({a: undefined, b: null}, '{"a":"undefined","b":null}'); + testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, + '{"a":"NaN","b":"Infinity","c":"-Infinity"}'); +}); + +test('assert - regressions from node.js testcase', function () { + var threw = false; + + try { + assert.throws(function () { + assert.ifError(null); + }); + } catch (e) { + threw = true; + assert.equal(e.message, 'Missing expected exception..'); + } + assert.ok(threw); + + try { + assert.equal(1, 2); + } catch (e) { + assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2'); + } + + try { + assert.equal(1, 2, 'oh no'); + } catch (e) { + assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no'); + } +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/.npmignore b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/.npmignore new file mode 100644 index 0000000..2752eb9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +.DS_Store diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/.travis.yml b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/.travis.yml new file mode 100644 index 0000000..87f8cd9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/README.md b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/README.md new file mode 100644 index 0000000..61f323a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/README.md @@ -0,0 +1,22 @@ +# browserify-zlib + +Emulates Node's [zlib](http://nodejs.org/api/zlib.html) module for [Browserify](http://browserify.org) +using [pako](https://github.com/nodeca/pako). It uses the actual Node source code and passes the Node zlib tests +by emulating the C++ binding that actually calls zlib. + +[![browser support](https://ci.testling.com/devongovett/browserify-zlib.png) +](https://ci.testling.com/devongovett/browserify-zlib) + +[![node tests](https://travis-ci.org/devongovett/browserify-zlib.svg) +](https://travis-ci.org/devongovett/browserify-zlib) + +## Not implemented + +The following options/methods are not supported because pako does not support them yet. + +* The `params` method +* The `dictionary` option + +## License + +MIT diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/Gruntfile.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/Gruntfile.js new file mode 100644 index 0000000..3e4c95a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/Gruntfile.js @@ -0,0 +1,82 @@ +'use strict'; + + +module.exports = function(grunt) { + var browsers = [{ + browserName: 'iphone', + platform: 'OS X 10.8', + version: '8.1' + }, { + browserName: 'android', + platform: 'Linux', + version: '5.0' + }, { + browserName: 'firefox', + platform: 'XP', + version: '35' + }, { + browserName: 'chrome', + platform: 'XP', + version: '41' + }, { + browserName: 'internet explorer', + platform: 'WIN7', + version: '11' + }, { + browserName: 'internet explorer', + platform: 'WIN7', + version: '10' + }, { + browserName: 'internet explorer', + platform: 'WIN7', + version: '9' + }, { + browserName: 'internet explorer', + platform: 'WIN7', + version: '8' + }, { + browserName: 'internet explorer', + platform: 'XP', + version: '7' + }, { + browserName: 'internet explorer', + platform: 'XP', + version: '6' + }, { + browserName: 'safari', + platform: 'OS X 10.8', + version: '6' + }]; + + + grunt.initConfig({ + connect: { + server: { + options: { + base: '', + port: 9999 + } + } + }, + 'saucelabs-mocha': { + all: { + options: { + urls: ['http://127.0.0.1:9999/test/browser/test.html'], + build: process.env.TRAVIS_JOB_NUMBER || ('local' + ~~(Math.random()*1000)), + browsers: browsers, + throttled: 3, + testname: process.env.SAUCE_PROJ || 'mocha tests' + } + } + }, + watch: {} + }); + + // Loading dependencies + for (var key in grunt.file.readJSON('package.json').devDependencies) { + if (key !== 'grunt' && key.indexOf('grunt') === 0) { grunt.loadNpmTasks(key); } + } + + //grunt.registerTask('dev', ['connect', 'watch']); + grunt.registerTask('test', ['connect', 'saucelabs-mocha']); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/HISTORY.md b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/HISTORY.md new file mode 100644 index 0000000..9ca3c2d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/HISTORY.md @@ -0,0 +1,69 @@ +0.2.8 / 2015-09-14 +------------------ + +- Fixed regression after 0.2.4 for edge conditions in inflate wrapper (#65). + Added more tests to cover possible cases. + + +0.2.7 / 2015-06-09 +------------------ + +- Added Z_SYNC_FLUSH support. Thanks to @TinoLange. + + +0.2.6 / 2015-03-24 +------------------ + +- Allow ArrayBuffer input. + + +0.2.5 / 2014-07-19 +------------------ + +- Workaround for Chrome 38.0.2096.0 script parser bug, #30. + + +0.2.4 / 2014-07-07 +------------------ + +- Fixed bug in inflate wrapper, #29 + + +0.2.3 / 2014-06-09 +------------------ + +- Maintenance release, dependencies update. + + +0.2.2 / 2014-06-04 +------------------ + +- Fixed iOS 5.1 Safary issue with `apply(typed_array)`, #26. + + +0.2.1 / 2014-05-01 +------------------ + +- Fixed collision on switch dynamic/fixed tables. + + +0.2.0 / 2014-04-18 +------------------ + +- Added custom gzip headers support. +- Added strings support. +- Improved memory allocations for small chunks. +- ZStream properties rename/cleanup. +- More coverage tests. + + +0.1.1 / 2014-03-20 +------------------ + +- Bugfixes for inflate/deflate. + + +0.1.0 / 2014-03-15 +------------------ + +- First release. diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/LICENSE b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/LICENSE new file mode 100644 index 0000000..102ad09 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2014-2015 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/README.md b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/README.md new file mode 100644 index 0000000..e824e05 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/README.md @@ -0,0 +1,175 @@ +pako - zlib port to javascript, very fast! +========================================== + +[![Build Status](https://travis-ci.org/nodeca/pako.svg?branch=master)](https://travis-ci.org/nodeca/pako) +[![NPM version](https://img.shields.io/npm/v/pako.svg)](https://www.npmjs.org/package/pako) + +__Why pako is cool:__ + +- Almost as fast in modern JS engines as C implementation (see benchmarks). +- Works in browsers, you can browserify any separate component. +- Chunking support for big blobs. +- Results are binary equal to well known [zlib](http://www.zlib.net/) (now v1.2.8 ported). + +This project was done to understand how fast JS can be and is it necessary to +develop native C modules for CPU-intensive tasks. Enjoy the result! + + +__Famous projects, using pako:__ + +- [browserify](http://browserify.org/) (via [browserify-zlib](https://github.com/devongovett/browserify-zlib)) +- [JSZip](http://stuk.github.io/jszip/) +- [mincer](https://github.com/nodeca/mincer) +- [JS-Git](https://github.com/creationix/js-git) and + [Tedit](https://chrome.google.com/webstore/detail/tedit-development-environ/ooekdijbnbbjdfjocaiflnjgoohnblgf) + by [@creatronix](https://github.com/creationix) + + +__Benchmarks:__ + +``` +node v0.10.26, 1mb sample: + + deflate-dankogai x 4.73 ops/sec ±0.82% (15 runs sampled) + deflate-gildas x 4.58 ops/sec ±2.33% (15 runs sampled) + deflate-imaya x 3.22 ops/sec ±3.95% (12 runs sampled) + ! deflate-pako x 6.99 ops/sec ±0.51% (21 runs sampled) + deflate-pako-string x 5.89 ops/sec ±0.77% (18 runs sampled) + deflate-pako-untyped x 4.39 ops/sec ±1.58% (14 runs sampled) + * deflate-zlib x 14.71 ops/sec ±4.23% (59 runs sampled) + inflate-dankogai x 32.16 ops/sec ±0.13% (56 runs sampled) + inflate-imaya x 30.35 ops/sec ±0.92% (53 runs sampled) + ! inflate-pako x 69.89 ops/sec ±1.46% (71 runs sampled) + inflate-pako-string x 19.22 ops/sec ±1.86% (49 runs sampled) + inflate-pako-untyped x 17.19 ops/sec ±0.85% (32 runs sampled) + * inflate-zlib x 70.03 ops/sec ±1.64% (81 runs sampled) + +node v0.11.12, 1mb sample: + + deflate-dankogai x 5.60 ops/sec ±0.49% (17 runs sampled) + deflate-gildas x 5.06 ops/sec ±6.00% (16 runs sampled) + deflate-imaya x 3.52 ops/sec ±3.71% (13 runs sampled) + ! deflate-pako x 11.52 ops/sec ±0.22% (32 runs sampled) + deflate-pako-string x 9.53 ops/sec ±1.12% (27 runs sampled) + deflate-pako-untyped x 5.44 ops/sec ±0.72% (17 runs sampled) + * deflate-zlib x 14.05 ops/sec ±3.34% (63 runs sampled) + inflate-dankogai x 42.19 ops/sec ±0.09% (56 runs sampled) + inflate-imaya x 79.68 ops/sec ±1.07% (68 runs sampled) + ! inflate-pako x 97.52 ops/sec ±0.83% (80 runs sampled) + inflate-pako-string x 45.19 ops/sec ±1.69% (57 runs sampled) + inflate-pako-untyped x 24.35 ops/sec ±2.59% (40 runs sampled) + * inflate-zlib x 60.32 ops/sec ±1.36% (69 runs sampled) +``` + +zlib's test is partialy afferted by marshling (that make sense for inflate only). +You can change deflate level to 0 in benchmark source, to investigate details. +For deflate level 6 results can be considered as correct. + +__Install:__ + +node.js: + +``` +npm install pako +``` + +browser: + +``` +bower install pako +``` + + +Example & API +------------- + +Full docs - http://nodeca.github.io/pako/ + +```javascript +var pako = require('pako'); + +// Deflate +// +var input = new Uint8Array(); +//... fill input data here +var output = pako.deflate(input); + +// Inflate (simple wrapper can throw exception on broken stream) +// +var compressed = new Uint8Array(); +//... fill data to uncompress here +try { + var result = pako.inflate(compressed); +} catch (err) { + console.log(err); +} + +// +// Alternate interface for chunking & without exceptions +// + +var inflator = new pako.Inflate(); + +inflator.push(chunk1, false); +inflator.push(chunk2, false); +... +inflator.push(chunkN, true); // true -> last chunk + +if (inflator.err) { + console.log(inflator.msg); +} + +var output = inflator.result; + +``` + +Sometime you can wish to work with strings. For example, to send +big objects as json to server. Pako detects input data type. You can +force output to be string with option `{ to: 'string' }`. + +```javascript +var pako = require('pako'); + +var test = { my: 'super', puper: [456, 567], awesome: 'pako' }; + +var binaryString = pako.deflate(JSON.stringify(test), { to: 'string' }); + +// +// Here you can do base64 encode, make xhr requests and so on. +// + +var restored = JSON.parse(pako.inflate(binaryString, { to: 'string' })); +``` + + +Notes +----- + +Pako does not contain some specific zlib functions: + +- __deflate__ - methods `deflateCopy`, `deflateBound`, `deflateParams`, + `deflatePending`, `deflatePrime`, `deflateSetDictionary`, `deflateTune`. +- __inflate__ - `inflateGetDictionary`, `inflateCopy`, `inflateMark`, + `inflatePrime`, `inflateSetDictionary`, `inflateSync`, `inflateSyncPoint`, + `inflateUndermine`. + + +Authors +------- + +- Andrey Tupitsin [@anrd83](https://github.com/andr83) +- Vitaly Puzrin [@puzrin](https://github.com/puzrin) + +Personal thanks to: + +- Vyacheslav Egorov ([@mraleph](https://github.com/mraleph)) for his awesome + tutoruals about optimising JS code for v8, [IRHydra](http://mrale.ph/irhydra/) + tool and his advices. +- David Duponchel ([@dduponchel](https://github.com/dduponchel)) for help with + testing. + + +License +------- + +MIT diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/bower.json b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/bower.json new file mode 100644 index 0000000..f078747 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/bower.json @@ -0,0 +1,23 @@ +{ + "name": "pako", + "main": "dist/pako.js", + "homepage": "https://github.com/nodeca/pako", + "authors": [ + "Andrei Tuputcyn ", + "Vitaly Puzrin " + ], + "description": "deflate / inflate / gzip for bworser - very fast zlib port", + "keywords": ["zlib", "deflate", "inflate", "gzip"], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "Makefile", + "index*", + "lib", + "benchmark", + "coverage" + ] +} diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako.js new file mode 100644 index 0000000..6ac5571 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako.js @@ -0,0 +1,6433 @@ +/* pako 0.2.8 nodeca/pako */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o Array + * + * Chunks of output data, if [[Deflate#onData]] not overriden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +var Deflate = function(options) { + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } +}; + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): ouput data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function(status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate alrorythm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; + +},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate.js":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(require,module,exports){ +'use strict'; + + +var zlib_inflate = require('./zlib/inflate.js'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var c = require('./zlib/constants'); +var msg = require('./zlib/messages'); +var zstream = require('./zlib/zstream'); +var gzheader = require('./zlib/gzheader'); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overriden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +var Inflate = function(options) { + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new gzheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); +}; + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): ouput data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function(status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 alligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; + +},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate.js":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(require,module,exports){ +'use strict'; + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (source.hasOwnProperty(p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs+len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i=0; i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254]=_utf8len[254]=1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { + c2 = str.charCodeAt(m_pos+1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i=0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { + c2 = str.charCodeAt(m_pos+1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // use fallback for big arrays to avoid stack overflow + if (len < 65537) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i=0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i=0, len=buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len*2); + + for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function(buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max-1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Fuckup - very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means vuffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +},{"./common":3}],5:[function(require,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It doesn't worth to make additional optimizationa as in original. +// Small size is preferable. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],6:[function(require,module,exports){ +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + +},{}],7:[function(require,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n =0; n < 256; n++) { + c = n; + for (var k =0; k < 8; k++) { + c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc = crc ^ (-1); + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],8:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2*L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only (s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH-1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length-1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH-1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +var Config = function (good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +}; + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); + this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS+1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + s.d_buf = s.lit_bufsize >> 1; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state + */ +//function deflateCopy(dest, source) { +// +//} + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +},{"../utils/common":3,"./adler32":5,"./crc32":7,"./messages":13,"./trees":14}],9:[function(require,module,exports){ +'use strict'; + + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; + +},{}],10:[function(require,module,exports){ +'use strict'; + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +},{}],11:[function(require,module,exports){ +'use strict'; + + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function ZSWAP32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window,src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window,src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more conveniend processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = ZSWAP32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = {bits: state.lenbits}; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = {bits: state.lenbits}; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = {bits: state.distbits}; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' insdead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too + if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +},{"../utils/common":3,"./adler32":5,"./crc32":7,"./inffast":10,"./inftrees":12}],12:[function(require,module,exports){ +'use strict'; + + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + var i=0; + /* process all codes and make table entries */ + for (;;) { + i++; + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +},{"../utils/common":3}],13:[function(require,module,exports){ +'use strict'; + +module.exports = { + '2': 'need dictionary', /* Z_NEED_DICT 2 */ + '1': 'stream end', /* Z_STREAM_END 1 */ + '0': '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],14:[function(require,module,exports){ +'use strict'; + + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2*L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES+2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +}; + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +var TreeDesc = function(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +}; + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short (s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max+1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n*2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n-base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m*2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; + tree[m*2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n*2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n*2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n*2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n*2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n*2 + 1]/*.Len*/ = 5; + static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n*2; + var _m2 = m*2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n*2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node*2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n+1)*2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6*2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10*2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138*2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n+1)*2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count-11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3*(max_blindex+1) + 5+5+4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len+3+7) >>> 3; + static_lenb = (s.static_len+3+7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc*2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + +},{"../utils/common":3}],15:[function(require,module,exports){ +'use strict'; + + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],"/":[function(require,module,exports){ +// Top level file is just a mixin of submodules & constants +'use strict'; + +var assign = require('./lib/utils/common').assign; + +var deflate = require('./lib/deflate'); +var inflate = require('./lib/inflate'); +var constants = require('./lib/zlib/constants'); + +var pako = {}; + +assign(pako, deflate, inflate, constants); + +module.exports = pako; + +},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/") +}); \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako.min.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako.min.js new file mode 100644 index 0000000..906dd71 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako.min.js @@ -0,0 +1,3 @@ +/* pako 0.2.8 nodeca/pako */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.pako=t()}}(function(){return function t(e,a,i){function n(s,o){if(!a[s]){if(!e[s]){var l="function"==typeof require&&require;if(!o&&l)return l(s,!0);if(r)return r(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var d=a[s]={exports:{}};e[s][0].call(d.exports,function(t){var a=e[s][1][t];return n(a?a:t)},d,d.exports,t,e,a,i)}return a[s].exports}for(var r="function"==typeof require&&require,s=0;s0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var a=s.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==c)throw new Error(h[a]);e.header&&s.deflateSetHeader(this.strm,e.header)};v.prototype.push=function(t,e){var a,i,n=this.strm,r=this.options.chunkSize;if(this.ended)return!1;i=e===~~e?e:e===!0?u:_,"string"==typeof t?n.input=l.string2buf(t):"[object ArrayBuffer]"===f.call(t)?n.input=new Uint8Array(t):n.input=t,n.next_in=0,n.avail_in=n.input.length;do{if(0===n.avail_out&&(n.output=new o.Buf8(r),n.next_out=0,n.avail_out=r),a=s.deflate(n,i),a!==b&&a!==c)return this.onEnd(a),this.ended=!0,!1;(0===n.avail_out||0===n.avail_in&&(i===u||i===g))&&this.onData("string"===this.options.to?l.buf2binstring(o.shrinkBuf(n.output,n.next_out)):o.shrinkBuf(n.output,n.next_out))}while((n.avail_in>0||0===n.avail_out)&&a!==b);return i===u?(a=s.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===c):i===g?(this.onEnd(c),n.avail_out=0,!0):!0},v.prototype.onData=function(t){this.chunks.push(t)},v.prototype.onEnd=function(t){t===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},a.Deflate=v,a.deflate=i,a.deflateRaw=n,a.gzip=r},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate.js":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(t,e,a){"use strict";function i(t,e){var a=new u(e);if(a.push(t,!0),a.err)throw a.msg;return a.result}function n(t,e){return e=e||{},e.raw=!0,i(t,e)}var r=t("./zlib/inflate.js"),s=t("./utils/common"),o=t("./utils/strings"),l=t("./zlib/constants"),h=t("./zlib/messages"),d=t("./zlib/zstream"),f=t("./zlib/gzheader"),_=Object.prototype.toString,u=function(t){this.options=s.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0===(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var a=r.inflateInit2(this.strm,e.windowBits);if(a!==l.Z_OK)throw new Error(h[a]);this.header=new f,r.inflateGetHeader(this.strm,this.header)};u.prototype.push=function(t,e){var a,i,n,h,d,f=this.strm,u=this.options.chunkSize,c=!1;if(this.ended)return!1;i=e===~~e?e:e===!0?l.Z_FINISH:l.Z_NO_FLUSH,"string"==typeof t?f.input=o.binstring2buf(t):"[object ArrayBuffer]"===_.call(t)?f.input=new Uint8Array(t):f.input=t,f.next_in=0,f.avail_in=f.input.length;do{if(0===f.avail_out&&(f.output=new s.Buf8(u),f.next_out=0,f.avail_out=u),a=r.inflate(f,l.Z_NO_FLUSH),a===l.Z_BUF_ERROR&&c===!0&&(a=l.Z_OK,c=!1),a!==l.Z_STREAM_END&&a!==l.Z_OK)return this.onEnd(a),this.ended=!0,!1;f.next_out&&(0===f.avail_out||a===l.Z_STREAM_END||0===f.avail_in&&(i===l.Z_FINISH||i===l.Z_SYNC_FLUSH))&&("string"===this.options.to?(n=o.utf8border(f.output,f.next_out),h=f.next_out-n,d=o.buf2string(f.output,n),f.next_out=h,f.avail_out=u-h,h&&s.arraySet(f.output,f.output,n,h,0),this.onData(d)):this.onData(s.shrinkBuf(f.output,f.next_out))),0===f.avail_in&&0===f.avail_out&&(c=!0)}while((f.avail_in>0||0===f.avail_out)&&a!==l.Z_STREAM_END);return a===l.Z_STREAM_END&&(i=l.Z_FINISH),i===l.Z_FINISH?(a=r.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===l.Z_OK):i===l.Z_SYNC_FLUSH?(this.onEnd(l.Z_OK),f.avail_out=0,!0):!0},u.prototype.onData=function(t){this.chunks.push(t)},u.prototype.onEnd=function(t){t===l.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},a.Inflate=u,a.inflate=i,a.inflateRaw=n,a.ungzip=i},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate.js":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(t,e,a){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;a.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(var i in a)a.hasOwnProperty(i)&&(t[i]=a[i])}}return t},a.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,a,i,n){if(e.subarray&&t.subarray)return void t.set(e.subarray(a,a+i),n);for(var r=0;i>r;r++)t[n+r]=e[a+r]},flattenChunks:function(t){var e,a,i,n,r,s;for(i=0,e=0,a=t.length;a>e;e++)i+=t[e].length;for(s=new Uint8Array(i),n=0,e=0,a=t.length;a>e;e++)r=t[e],s.set(r,n),n+=r.length;return s}},r={arraySet:function(t,e,a,i,n){for(var r=0;i>r;r++)t[n+r]=e[a+r]},flattenChunks:function(t){return[].concat.apply([],t)}};a.setTyped=function(t){t?(a.Buf8=Uint8Array,a.Buf16=Uint16Array,a.Buf32=Int32Array,a.assign(a,n)):(a.Buf8=Array,a.Buf16=Array,a.Buf32=Array,a.assign(a,r))},a.setTyped(i)},{}],4:[function(t,e,a){"use strict";function i(t,e){if(65537>e&&(t.subarray&&s||!t.subarray&&r))return String.fromCharCode.apply(null,n.shrinkBuf(t,e));for(var a="",i=0;e>i;i++)a+=String.fromCharCode(t[i]);return a}var n=t("./common"),r=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch(o){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(o){s=!1}for(var l=new n.Buf8(256),h=0;256>h;h++)l[h]=h>=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;l[254]=l[254]=1,a.string2buf=function(t){var e,a,i,r,s,o=t.length,l=0;for(r=0;o>r;r++)a=t.charCodeAt(r),55296===(64512&a)&&o>r+1&&(i=t.charCodeAt(r+1),56320===(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),r++)),l+=128>a?1:2048>a?2:65536>a?3:4;for(e=new n.Buf8(l),s=0,r=0;l>s;r++)a=t.charCodeAt(r),55296===(64512&a)&&o>r+1&&(i=t.charCodeAt(r+1),56320===(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),r++)),128>a?e[s++]=a:2048>a?(e[s++]=192|a>>>6,e[s++]=128|63&a):65536>a?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},a.buf2binstring=function(t){return i(t,t.length)},a.binstring2buf=function(t){for(var e=new n.Buf8(t.length),a=0,i=e.length;i>a;a++)e[a]=t.charCodeAt(a);return e},a.buf2string=function(t,e){var a,n,r,s,o=e||t.length,h=new Array(2*o);for(n=0,a=0;o>a;)if(r=t[a++],128>r)h[n++]=r;else if(s=l[r],s>4)h[n++]=65533,a+=s-1;else{for(r&=2===s?31:3===s?15:7;s>1&&o>a;)r=r<<6|63&t[a++],s--;s>1?h[n++]=65533:65536>r?h[n++]=r:(r-=65536,h[n++]=55296|r>>10&1023,h[n++]=56320|1023&r)}return i(h,n)},a.utf8border=function(t,e){var a;for(e=e||t.length,e>t.length&&(e=t.length),a=e-1;a>=0&&128===(192&t[a]);)a--;return 0>a?e:0===a?e:a+l[t[a]]>e?a:e}},{"./common":3}],5:[function(t,e,a){"use strict";function i(t,e,a,i){for(var n=65535&t|0,r=t>>>16&65535|0,s=0;0!==a;){s=a>2e3?2e3:a,a-=s;do n=n+e[i++]|0,r=r+n|0;while(--s);n%=65521,r%=65521}return n|r<<16|0}e.exports=i},{}],6:[function(t,e,a){e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],7:[function(t,e,a){"use strict";function i(){for(var t,e=[],a=0;256>a;a++){t=a;for(var i=0;8>i;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e}function n(t,e,a,i){var n=r,s=i+a;t=-1^t;for(var o=i;s>o;o++)t=t>>>8^n[255&(t^e[o])];return-1^t}var r=i();e.exports=n},{}],8:[function(t,e,a){"use strict";function i(t,e){return t.msg=N[e],e}function n(t){return(t<<1)-(t>4?9:0)}function r(t){for(var e=t.length;--e>=0;)t[e]=0}function s(t){var e=t.state,a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(A.arraySet(t.output,e.pending_buf,e.pending_out,a,t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))}function o(t,e){Z._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,s(t.strm)}function l(t,e){t.pending_buf[t.pending++]=e}function h(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function d(t,e,a,i){var n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,A.arraySet(e,t.input,t.next_in,n,a),1===t.state.wrap?t.adler=R(t.adler,e,n,a):2===t.state.wrap&&(t.adler=C(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)}function f(t,e){var a,i,n=t.max_chain_length,r=t.strstart,s=t.prev_length,o=t.nice_match,l=t.strstart>t.w_size-ht?t.strstart-(t.w_size-ht):0,h=t.window,d=t.w_mask,f=t.prev,_=t.strstart+lt,u=h[r+s-1],c=h[r+s];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do if(a=e,h[a+s]===c&&h[a+s-1]===u&&h[a]===h[r]&&h[++a]===h[r+1]){r+=2,a++;do;while(h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&_>r);if(i=lt-(_-r),r=_-lt,i>s){if(t.match_start=e,s=i,i>=o)break;u=h[r+s-1],c=h[r+s]}}while((e=f[e&d])>l&&0!==--n);return s<=t.lookahead?s:t.lookahead}function _(t){var e,a,i,n,r,s=t.w_size;do{if(n=t.window_size-t.lookahead-t.strstart,t.strstart>=s+(s-ht)){A.arraySet(t.window,t.window,s,s,0),t.match_start-=s,t.strstart-=s,t.block_start-=s,a=t.hash_size,e=a;do i=t.head[--e],t.head[e]=i>=s?i-s:0;while(--a);a=s,e=a;do i=t.prev[--e],t.prev[e]=i>=s?i-s:0;while(--a);n+=s}if(0===t.strm.avail_in)break;if(a=d(t.strm,t.window,t.strstart+t.lookahead,n),t.lookahead+=a,t.lookahead+t.insert>=ot)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(_(t),0===t.lookahead&&e===O)return wt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+a;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,o(t,!1),0===t.strm.avail_out))return wt;if(t.strstart-t.block_start>=t.w_size-ht&&(o(t,!1),0===t.strm.avail_out))return wt}return t.insert=0,e===F?(o(t,!0),0===t.strm.avail_out?vt:kt):t.strstart>t.block_start&&(o(t,!1),0===t.strm.avail_out)?wt:wt}function c(t,e){for(var a,i;;){if(t.lookahead=ot&&(t.ins_h=(t.ins_h<=ot)if(i=Z._tr_tally(t,t.strstart-t.match_start,t.match_length-ot),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ot){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=ot&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=ot-1)),t.prev_length>=ot&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-ot,i=Z._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ot),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=n&&(t.ins_h=(t.ins_h<=ot&&t.strstart>0&&(n=t.strstart-1,i=s[n],i===s[++n]&&i===s[++n]&&i===s[++n])){r=t.strstart+lt;do;while(i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&i===s[++n]&&r>n);t.match_length=lt-(r-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ot?(a=Z._tr_tally(t,1,t.match_length-ot),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=Z._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(o(t,!1),0===t.strm.avail_out))return wt}return t.insert=0,e===F?(o(t,!0),0===t.strm.avail_out?vt:kt):t.last_lit&&(o(t,!1),0===t.strm.avail_out)?wt:pt}function m(t,e){for(var a;;){if(0===t.lookahead&&(_(t),0===t.lookahead)){if(e===O)return wt;break}if(t.match_length=0,a=Z._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(o(t,!1),0===t.strm.avail_out))return wt}return t.insert=0,e===F?(o(t,!0),0===t.strm.avail_out?vt:kt):t.last_lit&&(o(t,!1),0===t.strm.avail_out)?wt:pt}function w(t){t.window_size=2*t.w_size,r(t.head),t.max_lazy_match=E[t.level].max_lazy,t.good_match=E[t.level].good_length,t.nice_match=E[t.level].nice_length,t.max_chain_length=E[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ot-1,t.match_available=0,t.ins_h=0}function p(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=J,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new A.Buf16(2*rt),this.dyn_dtree=new A.Buf16(2*(2*it+1)),this.bl_tree=new A.Buf16(2*(2*nt+1)),r(this.dyn_ltree),r(this.dyn_dtree),r(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new A.Buf16(st+1),this.heap=new A.Buf16(2*at+1),r(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new A.Buf16(2*at+1),r(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=W,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?ft:gt,t.adler=2===e.wrap?0:1,e.last_flush=O,Z._tr_init(e),D):i(t,H)}function k(t){var e=v(t);return e===D&&w(t.state),e}function x(t,e){return t&&t.state?2!==t.state.wrap?H:(t.state.gzhead=e,D):H}function y(t,e,a,n,r,s){if(!t)return H;var o=1;if(e===M&&(e=6),0>n?(o=0,n=-n):n>15&&(o=2,n-=16),1>r||r>Q||a!==J||8>n||n>15||0>e||e>9||0>s||s>G)return i(t,H);8===n&&(n=9);var l=new p;return t.state=l,l.strm=t,l.wrap=o,l.gzhead=null,l.w_bits=n,l.w_size=1<>1,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=s,l.method=a,k(t)}function z(t,e){return y(t,e,J,V,$,X)}function B(t,e){var a,o,d,f;if(!t||!t.state||e>T||0>e)return t?i(t,H):H;if(o=t.state,!t.output||!t.input&&0!==t.avail_in||o.status===mt&&e!==F)return i(t,0===t.avail_out?K:H);if(o.strm=t,a=o.last_flush,o.last_flush=e,o.status===ft)if(2===o.wrap)t.adler=0,l(o,31),l(o,139),l(o,8),o.gzhead?(l(o,(o.gzhead.text?1:0)+(o.gzhead.hcrc?2:0)+(o.gzhead.extra?4:0)+(o.gzhead.name?8:0)+(o.gzhead.comment?16:0)),l(o,255&o.gzhead.time),l(o,o.gzhead.time>>8&255),l(o,o.gzhead.time>>16&255),l(o,o.gzhead.time>>24&255),l(o,9===o.level?2:o.strategy>=Y||o.level<2?4:0),l(o,255&o.gzhead.os),o.gzhead.extra&&o.gzhead.extra.length&&(l(o,255&o.gzhead.extra.length),l(o,o.gzhead.extra.length>>8&255)),o.gzhead.hcrc&&(t.adler=C(t.adler,o.pending_buf,o.pending,0)),o.gzindex=0,o.status=_t):(l(o,0),l(o,0),l(o,0),l(o,0),l(o,0),l(o,9===o.level?2:o.strategy>=Y||o.level<2?4:0),l(o,xt),o.status=gt);else{var _=J+(o.w_bits-8<<4)<<8,u=-1;u=o.strategy>=Y||o.level<2?0:o.level<6?1:6===o.level?2:3,_|=u<<6,0!==o.strstart&&(_|=dt),_+=31-_%31,o.status=gt,h(o,_),0!==o.strstart&&(h(o,t.adler>>>16),h(o,65535&t.adler)),t.adler=1}if(o.status===_t)if(o.gzhead.extra){for(d=o.pending;o.gzindex<(65535&o.gzhead.extra.length)&&(o.pending!==o.pending_buf_size||(o.gzhead.hcrc&&o.pending>d&&(t.adler=C(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending!==o.pending_buf_size));)l(o,255&o.gzhead.extra[o.gzindex]),o.gzindex++;o.gzhead.hcrc&&o.pending>d&&(t.adler=C(t.adler,o.pending_buf,o.pending-d,d)),o.gzindex===o.gzhead.extra.length&&(o.gzindex=0,o.status=ut)}else o.status=ut;if(o.status===ut)if(o.gzhead.name){d=o.pending;do{if(o.pending===o.pending_buf_size&&(o.gzhead.hcrc&&o.pending>d&&(t.adler=C(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending===o.pending_buf_size)){f=1;break}f=o.gzindexd&&(t.adler=C(t.adler,o.pending_buf,o.pending-d,d)),0===f&&(o.gzindex=0,o.status=ct)}else o.status=ct;if(o.status===ct)if(o.gzhead.comment){d=o.pending;do{if(o.pending===o.pending_buf_size&&(o.gzhead.hcrc&&o.pending>d&&(t.adler=C(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending===o.pending_buf_size)){f=1;break}f=o.gzindexd&&(t.adler=C(t.adler,o.pending_buf,o.pending-d,d)),0===f&&(o.status=bt)}else o.status=bt;if(o.status===bt&&(o.gzhead.hcrc?(o.pending+2>o.pending_buf_size&&s(t),o.pending+2<=o.pending_buf_size&&(l(o,255&t.adler),l(o,t.adler>>8&255),t.adler=0,o.status=gt)):o.status=gt),0!==o.pending){if(s(t),0===t.avail_out)return o.last_flush=-1,D}else if(0===t.avail_in&&n(e)<=n(a)&&e!==F)return i(t,K);if(o.status===mt&&0!==t.avail_in)return i(t,K);if(0!==t.avail_in||0!==o.lookahead||e!==O&&o.status!==mt){var c=o.strategy===Y?m(o,e):o.strategy===q?g(o,e):E[o.level].func(o,e);if((c===vt||c===kt)&&(o.status=mt),c===wt||c===vt)return 0===t.avail_out&&(o.last_flush=-1),D;if(c===pt&&(e===I?Z._tr_align(o):e!==T&&(Z._tr_stored_block(o,0,0,!1),e===U&&(r(o.head),0===o.lookahead&&(o.strstart=0,o.block_start=0,o.insert=0))),s(t),0===t.avail_out))return o.last_flush=-1,D}return e!==F?D:o.wrap<=0?L:(2===o.wrap?(l(o,255&t.adler),l(o,t.adler>>8&255),l(o,t.adler>>16&255),l(o,t.adler>>24&255),l(o,255&t.total_in),l(o,t.total_in>>8&255),l(o,t.total_in>>16&255),l(o,t.total_in>>24&255)):(h(o,t.adler>>>16),h(o,65535&t.adler)),s(t),o.wrap>0&&(o.wrap=-o.wrap),0!==o.pending?D:L)}function S(t){var e;return t&&t.state?(e=t.state.status,e!==ft&&e!==_t&&e!==ut&&e!==ct&&e!==bt&&e!==gt&&e!==mt?i(t,H):(t.state=null,e===gt?i(t,j):D)):H}var E,A=t("../utils/common"),Z=t("./trees"),R=t("./adler32"),C=t("./crc32"),N=t("./messages"),O=0,I=1,U=3,F=4,T=5,D=0,L=1,H=-2,j=-3,K=-5,M=-1,P=1,Y=2,q=3,G=4,X=0,W=2,J=8,Q=9,V=15,$=8,tt=29,et=256,at=et+1+tt,it=30,nt=19,rt=2*at+1,st=15,ot=3,lt=258,ht=lt+ot+1,dt=32,ft=42,_t=69,ut=73,ct=91,bt=103,gt=113,mt=666,wt=1,pt=2,vt=3,kt=4,xt=3,yt=function(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n};E=[new yt(0,0,0,0,u),new yt(4,4,8,4,c),new yt(4,5,16,8,c),new yt(4,6,32,32,c),new yt(4,4,16,16,b),new yt(8,16,32,32,b),new yt(8,16,128,128,b),new yt(8,32,128,256,b),new yt(32,128,258,1024,b),new yt(32,258,258,4096,b)],a.deflateInit=z,a.deflateInit2=y,a.deflateReset=k,a.deflateResetKeep=v,a.deflateSetHeader=x,a.deflate=B,a.deflateEnd=S,a.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":3,"./adler32":5,"./crc32":7,"./messages":13,"./trees":14}],9:[function(t,e,a){"use strict";function i(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}e.exports=i},{}],10:[function(t,e,a){"use strict";var i=30,n=12;e.exports=function(t,e){var a,r,s,o,l,h,d,f,_,u,c,b,g,m,w,p,v,k,x,y,z,B,S,E,A;a=t.state,r=t.next_in,E=t.input,s=r+(t.avail_in-5),o=t.next_out,A=t.output,l=o-(e-t.avail_out),h=o+(t.avail_out-257),d=a.dmax,f=a.wsize,_=a.whave,u=a.wnext,c=a.window,b=a.hold,g=a.bits,m=a.lencode,w=a.distcode,p=(1<g&&(b+=E[r++]<>>24,b>>>=x,g-=x,x=k>>>16&255,0===x)A[o++]=65535&k;else{if(!(16&x)){if(0===(64&x)){k=m[(65535&k)+(b&(1<g&&(b+=E[r++]<>>=x,g-=x),15>g&&(b+=E[r++]<>>24,b>>>=x,g-=x,x=k>>>16&255,!(16&x)){if(0===(64&x)){k=w[(65535&k)+(b&(1<g&&(b+=E[r++]<g&&(b+=E[r++]<d){t.msg="invalid distance too far back",a.mode=i;break t}if(b>>>=x,g-=x,x=o-l,z>x){if(x=z-x,x>_&&a.sane){t.msg="invalid distance too far back",a.mode=i;break t}if(B=0,S=c,0===u){if(B+=f-x,y>x){y-=x;do A[o++]=c[B++];while(--x);B=o-z,S=A}}else if(x>u){if(B+=f+u-x,x-=u,y>x){y-=x;do A[o++]=c[B++];while(--x);if(B=0,y>u){x=u,y-=x;do A[o++]=c[B++];while(--x);B=o-z,S=A}}}else if(B+=u-x,y>x){y-=x;do A[o++]=c[B++];while(--x);B=o-z,S=A}for(;y>2;)A[o++]=S[B++],A[o++]=S[B++],A[o++]=S[B++],y-=3;y&&(A[o++]=S[B++],y>1&&(A[o++]=S[B++]))}else{B=o-z;do A[o++]=A[B++],A[o++]=A[B++],A[o++]=A[B++],y-=3;while(y>2);y&&(A[o++]=A[B++],y>1&&(A[o++]=A[B++]))}break}}break}}while(s>r&&h>o);y=g>>3,r-=y,g-=y<<3,b&=(1<r?5+(s-r):5-(r-s),t.avail_out=h>o?257+(h-o):257-(o-h),a.hold=b,a.bits=g}},{}],11:[function(t,e,a){"use strict";function i(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new m.Buf16(320),this.work=new m.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function r(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=F,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new m.Buf32(ct),e.distcode=e.distdyn=new m.Buf32(bt),e.sane=1,e.back=-1,A):C}function s(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,r(t)):C}function o(t,e){var a,i;return t&&t.state?(i=t.state,0>e?(a=0,e=-e):(a=(e>>4)+1,48>e&&(e&=15)),e&&(8>e||e>15)?C:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,s(t))):C}function l(t,e){var a,i;return t?(i=new n,t.state=i,i.window=null,a=o(t,e),a!==A&&(t.state=null),a):C}function h(t){return l(t,mt)}function d(t){if(wt){var e;for(b=new m.Buf32(512),g=new m.Buf32(32),e=0;144>e;)t.lens[e++]=8;for(;256>e;)t.lens[e++]=9;for(;280>e;)t.lens[e++]=7;for(;288>e;)t.lens[e++]=8;for(k(y,t.lens,0,288,b,0,t.work,{bits:9}),e=0;32>e;)t.lens[e++]=5;k(z,t.lens,0,32,g,0,t.work,{bits:5}),wt=!1}t.lencode=b,t.lenbits=9,t.distcode=g,t.distbits=5}function f(t,e,a,i){var n,r=t.state;return null===r.window&&(r.wsize=1<=r.wsize?(m.arraySet(r.window,e,a-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(n=r.wsize-r.wnext,n>i&&(n=i),m.arraySet(r.window,e,a-i,n,r.wnext),i-=n,i?(m.arraySet(r.window,e,a-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=n,r.wnext===r.wsize&&(r.wnext=0),r.whaveu;){if(0===l)break t;l--,_+=n[s++]<>>8&255,a.check=p(a.check,Et,2,0),_=0,u=0,a.mode=T;break}if(a.flags=0,a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&_)<<8)+(_>>8))%31){t.msg="incorrect header check",a.mode=ft;break}if((15&_)!==U){t.msg="unknown compression method",a.mode=ft;break}if(_>>>=4,u-=4,xt=(15&_)+8,0===a.wbits)a.wbits=xt;else if(xt>a.wbits){t.msg="invalid window size",a.mode=ft;break}a.dmax=1<u;){if(0===l)break t;l--,_+=n[s++]<>8&1),512&a.flags&&(Et[0]=255&_,Et[1]=_>>>8&255,a.check=p(a.check,Et,2,0)),_=0,u=0,a.mode=D;case D:for(;32>u;){if(0===l)break t;l--,_+=n[s++]<>>8&255,Et[2]=_>>>16&255,Et[3]=_>>>24&255,a.check=p(a.check,Et,4,0)),_=0,u=0,a.mode=L;case L:for(;16>u;){if(0===l)break t;l--,_+=n[s++]<>8),512&a.flags&&(Et[0]=255&_,Et[1]=_>>>8&255,a.check=p(a.check,Et,2,0)),_=0,u=0,a.mode=H;case H:if(1024&a.flags){for(;16>u;){if(0===l)break t;l--,_+=n[s++]<>>8&255,a.check=p(a.check,Et,2,0)),_=0,u=0}else a.head&&(a.head.extra=null);a.mode=j;case j:if(1024&a.flags&&(g=a.length,g>l&&(g=l),g&&(a.head&&(xt=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Array(a.head.extra_len)),m.arraySet(a.head.extra,n,s,g,xt)),512&a.flags&&(a.check=p(a.check,n,g,s)),l-=g,s+=g,a.length-=g),a.length))break t;a.length=0,a.mode=K;case K:if(2048&a.flags){if(0===l)break t;g=0;do xt=n[s+g++],a.head&&xt&&a.length<65536&&(a.head.name+=String.fromCharCode(xt));while(xt&&l>g);if(512&a.flags&&(a.check=p(a.check,n,g,s)),l-=g,s+=g,xt)break t}else a.head&&(a.head.name=null);a.length=0,a.mode=M;case M:if(4096&a.flags){if(0===l)break t;g=0;do xt=n[s+g++],a.head&&xt&&a.length<65536&&(a.head.comment+=String.fromCharCode(xt));while(xt&&l>g);if(512&a.flags&&(a.check=p(a.check,n,g,s)),l-=g,s+=g,xt)break t}else a.head&&(a.head.comment=null);a.mode=P;case P:if(512&a.flags){for(;16>u;){if(0===l)break t;l--,_+=n[s++]<>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=G;break;case Y:for(;32>u;){if(0===l)break t;l--,_+=n[s++]<>>=7&u,u-=7&u,a.mode=lt;break}for(;3>u;){if(0===l)break t;l--,_+=n[s++]<>>=1,u-=1,3&_){case 0:a.mode=W;break;case 1:if(d(a),a.mode=et,e===E){_>>>=2,u-=2;break t}break;case 2:a.mode=V;break;case 3:t.msg="invalid block type",a.mode=ft}_>>>=2,u-=2;break;case W:for(_>>>=7&u,u-=7&u;32>u;){if(0===l)break t;l--,_+=n[s++]<>>16^65535)){t.msg="invalid stored block lengths",a.mode=ft;break}if(a.length=65535&_,_=0,u=0,a.mode=J,e===E)break t;case J:a.mode=Q;case Q:if(g=a.length){if(g>l&&(g=l),g>h&&(g=h),0===g)break t;m.arraySet(r,n,s,g,o),l-=g,s+=g,h-=g,o+=g,a.length-=g;break}a.mode=G;break;case V:for(;14>u;){if(0===l)break t;l--,_+=n[s++]<>>=5,u-=5,a.ndist=(31&_)+1,_>>>=5,u-=5,a.ncode=(15&_)+4,_>>>=4,u-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=ft;break}a.have=0,a.mode=$;case $:for(;a.haveu;){if(0===l)break t;l--,_+=n[s++]<>>=3,u-=3}for(;a.have<19;)a.lens[At[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,zt={bits:a.lenbits},yt=k(x,a.lens,0,19,a.lencode,0,a.work,zt),a.lenbits=zt.bits,yt){t.msg="invalid code lengths set",a.mode=ft;break}a.have=0,a.mode=tt;case tt:for(;a.have>>24,mt=St>>>16&255,wt=65535&St,!(u>=gt);){if(0===l)break t;l--,_+=n[s++]<wt)_>>>=gt,u-=gt,a.lens[a.have++]=wt;else{if(16===wt){for(Bt=gt+2;Bt>u;){if(0===l)break t;l--,_+=n[s++]<>>=gt,u-=gt,0===a.have){t.msg="invalid bit length repeat",a.mode=ft;break}xt=a.lens[a.have-1],g=3+(3&_),_>>>=2,u-=2}else if(17===wt){for(Bt=gt+3;Bt>u;){if(0===l)break t;l--,_+=n[s++]<>>=gt,u-=gt,xt=0,g=3+(7&_),_>>>=3,u-=3}else{for(Bt=gt+7;Bt>u;){if(0===l)break t;l--,_+=n[s++]<>>=gt,u-=gt,xt=0,g=11+(127&_),_>>>=7,u-=7}if(a.have+g>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=ft;break}for(;g--;)a.lens[a.have++]=xt}}if(a.mode===ft)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block", +a.mode=ft;break}if(a.lenbits=9,zt={bits:a.lenbits},yt=k(y,a.lens,0,a.nlen,a.lencode,0,a.work,zt),a.lenbits=zt.bits,yt){t.msg="invalid literal/lengths set",a.mode=ft;break}if(a.distbits=6,a.distcode=a.distdyn,zt={bits:a.distbits},yt=k(z,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,zt),a.distbits=zt.bits,yt){t.msg="invalid distances set",a.mode=ft;break}if(a.mode=et,e===E)break t;case et:a.mode=at;case at:if(l>=6&&h>=258){t.next_out=o,t.avail_out=h,t.next_in=s,t.avail_in=l,a.hold=_,a.bits=u,v(t,b),o=t.next_out,r=t.output,h=t.avail_out,s=t.next_in,n=t.input,l=t.avail_in,_=a.hold,u=a.bits,a.mode===G&&(a.back=-1);break}for(a.back=0;St=a.lencode[_&(1<>>24,mt=St>>>16&255,wt=65535&St,!(u>=gt);){if(0===l)break t;l--,_+=n[s++]<>pt)],gt=St>>>24,mt=St>>>16&255,wt=65535&St,!(u>=pt+gt);){if(0===l)break t;l--,_+=n[s++]<>>=pt,u-=pt,a.back+=pt}if(_>>>=gt,u-=gt,a.back+=gt,a.length=wt,0===mt){a.mode=ot;break}if(32&mt){a.back=-1,a.mode=G;break}if(64&mt){t.msg="invalid literal/length code",a.mode=ft;break}a.extra=15&mt,a.mode=it;case it:if(a.extra){for(Bt=a.extra;Bt>u;){if(0===l)break t;l--,_+=n[s++]<>>=a.extra,u-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=nt;case nt:for(;St=a.distcode[_&(1<>>24,mt=St>>>16&255,wt=65535&St,!(u>=gt);){if(0===l)break t;l--,_+=n[s++]<>pt)],gt=St>>>24,mt=St>>>16&255,wt=65535&St,!(u>=pt+gt);){if(0===l)break t;l--,_+=n[s++]<>>=pt,u-=pt,a.back+=pt}if(_>>>=gt,u-=gt,a.back+=gt,64&mt){t.msg="invalid distance code",a.mode=ft;break}a.offset=wt,a.extra=15&mt,a.mode=rt;case rt:if(a.extra){for(Bt=a.extra;Bt>u;){if(0===l)break t;l--,_+=n[s++]<>>=a.extra,u-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=ft;break}a.mode=st;case st:if(0===h)break t;if(g=b-h,a.offset>g){if(g=a.offset-g,g>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=ft;break}g>a.wnext?(g-=a.wnext,ct=a.wsize-g):ct=a.wnext-g,g>a.length&&(g=a.length),bt=a.window}else bt=r,ct=o-a.offset,g=a.length;g>h&&(g=h),h-=g,a.length-=g;do r[o++]=bt[ct++];while(--g);0===a.length&&(a.mode=at);break;case ot:if(0===h)break t;r[o++]=a.length,h--,a.mode=at;break;case lt:if(a.wrap){for(;32>u;){if(0===l)break t;l--,_|=n[s++]<u;){if(0===l)break t;l--,_+=n[s++]<=Z;Z++)j[Z]=0;for(R=0;c>R;R++)j[e[a+R]]++;for(O=A,N=n;N>=1&&0===j[N];N--);if(O>N&&(O=N),0===N)return b[g++]=20971520,b[g++]=20971520,w.bits=1,0;for(C=1;N>C&&0===j[C];C++);for(C>O&&(O=C),F=1,Z=1;n>=Z;Z++)if(F<<=1,F-=j[Z],0>F)return-1;if(F>0&&(t===o||1!==N))return-1;for(K[1]=0,Z=1;n>Z;Z++)K[Z+1]=K[Z]+j[Z];for(R=0;c>R;R++)0!==e[a+R]&&(m[K[e[a+R]]++]=R);if(t===o?(L=M=m,z=19):t===l?(L=d,H-=257,M=f,P-=257,z=256):(L=_,M=u,z=-1),D=0,R=0,Z=C,y=g,I=O,U=0,k=-1,T=1<r||t===h&&T>s)return 1;for(var Y=0;;){Y++,B=Z-U,m[R]z?(S=M[P+m[R]],E=L[H+m[R]]):(S=96,E=0),p=1<>U)+v]=B<<24|S<<16|E|0;while(0!==v);for(p=1<>=1;if(0!==p?(D&=p-1,D+=p):D=0,R++,0===--j[Z]){if(Z===N)break;Z=e[a+m[R]]}if(Z>O&&(D&x)!==k){for(0===U&&(U=O),y+=C,I=Z-U,F=1<I+U&&(F-=j[I+U],!(0>=F));)I++,F<<=1;if(T+=1<r||t===h&&T>s)return 1;k=D&x,b[k]=O<<24|I<<16|y-g|0}}return 0!==D&&(b[y+D]=Z-U<<24|64<<16|0),w.bits=O,0}},{"../utils/common":3}],13:[function(t,e,a){"use strict";e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],14:[function(t,e,a){"use strict";function i(t){for(var e=t.length;--e>=0;)t[e]=0}function n(t){return 256>t?st[t]:st[256+(t>>>7)]}function r(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function s(t,e,a){t.bi_valid>G-a?(t.bi_buf|=e<>G-t.bi_valid,t.bi_valid+=a-G):(t.bi_buf|=e<>>=1,a<<=1;while(--e>0);return a>>>1}function h(t){16===t.bi_valid?(r(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function d(t,e){var a,i,n,r,s,o,l=e.dyn_tree,h=e.max_code,d=e.stat_desc.static_tree,f=e.stat_desc.has_stree,_=e.stat_desc.extra_bits,u=e.stat_desc.extra_base,c=e.stat_desc.max_length,b=0;for(r=0;q>=r;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;Y>a;a++)i=t.heap[a],r=l[2*l[2*i+1]+1]+1,r>c&&(r=c,b++),l[2*i+1]=r,i>h||(t.bl_count[r]++,s=0,i>=u&&(s=_[i-u]),o=l[2*i],t.opt_len+=o*(r+s),f&&(t.static_len+=o*(d[2*i+1]+s)));if(0!==b){do{for(r=c-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[c]--,b-=2}while(b>0);for(r=c;0!==r;r--)for(i=t.bl_count[r];0!==i;)n=t.heap[--a],n>h||(l[2*n+1]!==r&&(t.opt_len+=(r-l[2*n+1])*l[2*n],l[2*n+1]=r),i--)}}function f(t,e,a){var i,n,r=new Array(q+1),s=0;for(i=1;q>=i;i++)r[i]=s=s+a[i-1]<<1;for(n=0;e>=n;n++){var o=t[2*n+1];0!==o&&(t[2*n]=l(r[o]++,o))}}function _(){var t,e,a,i,n,r=new Array(q+1);for(a=0,i=0;H-1>i;i++)for(lt[i]=a,t=0;t<1<<$[i];t++)ot[a++]=i;for(ot[a-1]=i,n=0,i=0;16>i;i++)for(ht[i]=n,t=0;t<1<>=7;M>i;i++)for(ht[i]=n<<7,t=0;t<1<=e;e++)r[e]=0;for(t=0;143>=t;)nt[2*t+1]=8,t++,r[8]++;for(;255>=t;)nt[2*t+1]=9,t++,r[9]++;for(;279>=t;)nt[2*t+1]=7,t++,r[7]++;for(;287>=t;)nt[2*t+1]=8,t++,r[8]++;for(f(nt,K+1,r),t=0;M>t;t++)rt[2*t+1]=5,rt[2*t]=l(t,5);dt=new ut(nt,$,j+1,K,q),ft=new ut(rt,tt,0,M,q),_t=new ut(new Array(0),et,0,P,X)}function u(t){var e;for(e=0;K>e;e++)t.dyn_ltree[2*e]=0;for(e=0;M>e;e++)t.dyn_dtree[2*e]=0;for(e=0;P>e;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*W]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function c(t){t.bi_valid>8?r(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function b(t,e,a,i){c(t),i&&(r(t,a),r(t,~a)),R.arraySet(t.pending_buf,t.window,e,a,t.pending),t.pending+=a}function g(t,e,a,i){var n=2*e,r=2*a;return t[n]a;a++)0!==r[2*a]?(t.heap[++t.heap_len]=h=a,t.depth[a]=0):r[2*a+1]=0;for(;t.heap_len<2;)n=t.heap[++t.heap_len]=2>h?++h:0,r[2*n]=1,t.depth[n]=0,t.opt_len--,o&&(t.static_len-=s[2*n+1]);for(e.max_code=h,a=t.heap_len>>1;a>=1;a--)m(t,r,a);n=l;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],m(t,r,1),i=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=i,r[2*n]=r[2*a]+r[2*i],t.depth[n]=(t.depth[a]>=t.depth[i]?t.depth[a]:t.depth[i])+1,r[2*a+1]=r[2*i+1]=n,t.heap[1]=n++,m(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],d(t,e),f(r,h,t.bl_count)}function v(t,e,a){var i,n,r=-1,s=e[1],o=0,l=7,h=4;for(0===s&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;a>=i;i++)n=s,s=e[2*(i+1)+1],++oo?t.bl_tree[2*n]+=o:0!==n?(n!==r&&t.bl_tree[2*n]++,t.bl_tree[2*J]++):10>=o?t.bl_tree[2*Q]++:t.bl_tree[2*V]++,o=0,r=n,0===s?(l=138,h=3):n===s?(l=6,h=3):(l=7,h=4))}function k(t,e,a){var i,n,r=-1,l=e[1],h=0,d=7,f=4;for(0===l&&(d=138,f=3),i=0;a>=i;i++)if(n=l,l=e[2*(i+1)+1],!(++hh){do o(t,n,t.bl_tree);while(0!==--h)}else 0!==n?(n!==r&&(o(t,n,t.bl_tree),h--),o(t,J,t.bl_tree),s(t,h-3,2)):10>=h?(o(t,Q,t.bl_tree),s(t,h-3,3)):(o(t,V,t.bl_tree),s(t,h-11,7));h=0,r=n,0===l?(d=138,f=3):n===l?(d=6,f=3):(d=7,f=4)}}function x(t){var e;for(v(t,t.dyn_ltree,t.l_desc.max_code),v(t,t.dyn_dtree,t.d_desc.max_code),p(t,t.bl_desc),e=P-1;e>=3&&0===t.bl_tree[2*at[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function y(t,e,a,i){var n;for(s(t,e-257,5),s(t,a-1,5),s(t,i-4,4),n=0;i>n;n++)s(t,t.bl_tree[2*at[n]+1],3);k(t,t.dyn_ltree,e-1),k(t,t.dyn_dtree,a-1)}function z(t){var e,a=4093624447;for(e=0;31>=e;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return N;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return O;for(e=32;j>e;e++)if(0!==t.dyn_ltree[2*e])return O;return N}function B(t){bt||(_(),bt=!0),t.l_desc=new ct(t.dyn_ltree,dt),t.d_desc=new ct(t.dyn_dtree,ft),t.bl_desc=new ct(t.bl_tree,_t),t.bi_buf=0,t.bi_valid=0,u(t)}function S(t,e,a,i){s(t,(U<<1)+(i?1:0),3),b(t,e,a,!0)}function E(t){s(t,F<<1,3),o(t,W,nt),h(t)}function A(t,e,a,i){var n,r,o=0;t.level>0?(t.strm.data_type===I&&(t.strm.data_type=z(t)),p(t,t.l_desc),p(t,t.d_desc),o=x(t),n=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,n>=r&&(n=r)):n=r=a+5,n>=a+4&&-1!==e?S(t,e,a,i):t.strategy===C||r===n?(s(t,(F<<1)+(i?1:0),3),w(t,nt,rt)):(s(t,(T<<1)+(i?1:0),3),y(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),w(t,t.dyn_ltree,t.dyn_dtree)),u(t),i&&c(t)}function Z(t,e,a){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(ot[a]+j+1)]++,t.dyn_dtree[2*n(e)]++),t.last_lit===t.lit_bufsize-1}var R=t("../utils/common"),C=4,N=0,O=1,I=2,U=0,F=1,T=2,D=3,L=258,H=29,j=256,K=j+1+H,M=30,P=19,Y=2*K+1,q=15,G=16,X=7,W=256,J=16,Q=17,V=18,$=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],tt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],et=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],at=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],it=512,nt=new Array(2*(K+2));i(nt);var rt=new Array(2*M);i(rt);var st=new Array(it);i(st);var ot=new Array(L-D+1);i(ot);var lt=new Array(H);i(lt);var ht=new Array(M);i(ht);var dt,ft,_t,ut=function(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length},ct=function(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e},bt=!1;a._tr_init=B,a._tr_stored_block=S,a._tr_flush_block=A,a._tr_tally=Z,a._tr_align=E},{"../utils/common":3}],15:[function(t,e,a){"use strict";function i(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}e.exports=i},{}],"/":[function(t,e,a){"use strict";var i=t("./lib/utils/common").assign,n=t("./lib/deflate"),r=t("./lib/inflate"),s=t("./lib/zlib/constants"),o={};i(o,n,r,s),e.exports=o},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_deflate.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_deflate.js new file mode 100644 index 0000000..76aa5a6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_deflate.js @@ -0,0 +1,3762 @@ +/* pako 0.2.8 nodeca/pako */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254]=_utf8len[254]=1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { + c2 = str.charCodeAt(m_pos+1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i=0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { + c2 = str.charCodeAt(m_pos+1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // use fallback for big arrays to avoid stack overflow + if (len < 65537) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i=0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i=0, len=buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len*2); + + for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function(buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max-1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Fuckup - very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means vuffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +},{"./common":1}],3:[function(require,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It doesn't worth to make additional optimizationa as in original. +// Small size is preferable. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],4:[function(require,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n =0; n < 256; n++) { + c = n; + for (var k =0; k < 8; k++) { + c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc = crc ^ (-1); + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],5:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2*L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only (s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH-1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length-1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH-1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +var Config = function (good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +}; + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); + this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS+1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + s.d_buf = s.lit_bufsize >> 1; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state + */ +//function deflateCopy(dest, source) { +// +//} + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +},{"../utils/common":1,"./adler32":3,"./crc32":4,"./messages":6,"./trees":7}],6:[function(require,module,exports){ +'use strict'; + +module.exports = { + '2': 'need dictionary', /* Z_NEED_DICT 2 */ + '1': 'stream end', /* Z_STREAM_END 1 */ + '0': '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],7:[function(require,module,exports){ +'use strict'; + + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2*L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES+2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +}; + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +var TreeDesc = function(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +}; + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short (s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max+1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n*2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n-base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m*2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; + tree[m*2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n*2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n*2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n*2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n*2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n*2 + 1]/*.Len*/ = 5; + static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n*2; + var _m2 = m*2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n*2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node*2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n+1)*2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6*2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10*2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138*2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n+1)*2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count-11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3*(max_blindex+1) + 5+5+4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len+3+7) >>> 3; + static_lenb = (s.static_len+3+7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc*2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + +},{"../utils/common":1}],8:[function(require,module,exports){ +'use strict'; + + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],"/lib/deflate.js":[function(require,module,exports){ +'use strict'; + + +var zlib_deflate = require('./zlib/deflate.js'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var msg = require('./zlib/messages'); +var zstream = require('./zlib/zstream'); + +var toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH = 0; +var Z_FINISH = 4; + +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_SYNC_FLUSH = 2; + +var Z_DEFAULT_COMPRESSION = -1; + +var Z_DEFAULT_STRATEGY = 0; + +var Z_DEFLATED = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overriden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +var Deflate = function(options) { + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } +}; + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): ouput data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function(status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate alrorythm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; + +},{"./utils/common":1,"./utils/strings":2,"./zlib/deflate.js":5,"./zlib/messages":6,"./zlib/zstream":8}]},{},[])("/lib/deflate.js") +}); \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_deflate.min.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_deflate.min.js new file mode 100644 index 0000000..f67f968 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_deflate.min.js @@ -0,0 +1,2 @@ +/* pako 0.2.8 nodeca/pako */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.pako=t()}}(function(){return function t(e,a,n){function r(s,h){if(!a[s]){if(!e[s]){var l="function"==typeof require&&require;if(!h&&l)return l(s,!0);if(i)return i(s,!0);var o=new Error("Cannot find module '"+s+"'");throw o.code="MODULE_NOT_FOUND",o}var _=a[s]={exports:{}};e[s][0].call(_.exports,function(t){var a=e[s][1][t];return r(a?a:t)},_,_.exports,t,e,a,n)}return a[s].exports}for(var i="function"==typeof require&&require,s=0;si;i++)t[r+i]=e[a+i]},flattenChunks:function(t){var e,a,n,r,i,s;for(n=0,e=0,a=t.length;a>e;e++)n+=t[e].length;for(s=new Uint8Array(n),r=0,e=0,a=t.length;a>e;e++)i=t[e],s.set(i,r),r+=i.length;return s}},i={arraySet:function(t,e,a,n,r){for(var i=0;n>i;i++)t[r+i]=e[a+i]},flattenChunks:function(t){return[].concat.apply([],t)}};a.setTyped=function(t){t?(a.Buf8=Uint8Array,a.Buf16=Uint16Array,a.Buf32=Int32Array,a.assign(a,r)):(a.Buf8=Array,a.Buf16=Array,a.Buf32=Array,a.assign(a,i))},a.setTyped(n)},{}],2:[function(t,e,a){"use strict";function n(t,e){if(65537>e&&(t.subarray&&s||!t.subarray&&i))return String.fromCharCode.apply(null,r.shrinkBuf(t,e));for(var a="",n=0;e>n;n++)a+=String.fromCharCode(t[n]);return a}var r=t("./common"),i=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch(h){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){s=!1}for(var l=new r.Buf8(256),o=0;256>o;o++)l[o]=o>=252?6:o>=248?5:o>=240?4:o>=224?3:o>=192?2:1;l[254]=l[254]=1,a.string2buf=function(t){var e,a,n,i,s,h=t.length,l=0;for(i=0;h>i;i++)a=t.charCodeAt(i),55296===(64512&a)&&h>i+1&&(n=t.charCodeAt(i+1),56320===(64512&n)&&(a=65536+(a-55296<<10)+(n-56320),i++)),l+=128>a?1:2048>a?2:65536>a?3:4;for(e=new r.Buf8(l),s=0,i=0;l>s;i++)a=t.charCodeAt(i),55296===(64512&a)&&h>i+1&&(n=t.charCodeAt(i+1),56320===(64512&n)&&(a=65536+(a-55296<<10)+(n-56320),i++)),128>a?e[s++]=a:2048>a?(e[s++]=192|a>>>6,e[s++]=128|63&a):65536>a?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},a.buf2binstring=function(t){return n(t,t.length)},a.binstring2buf=function(t){for(var e=new r.Buf8(t.length),a=0,n=e.length;n>a;a++)e[a]=t.charCodeAt(a);return e},a.buf2string=function(t,e){var a,r,i,s,h=e||t.length,o=new Array(2*h);for(r=0,a=0;h>a;)if(i=t[a++],128>i)o[r++]=i;else if(s=l[i],s>4)o[r++]=65533,a+=s-1;else{for(i&=2===s?31:3===s?15:7;s>1&&h>a;)i=i<<6|63&t[a++],s--;s>1?o[r++]=65533:65536>i?o[r++]=i:(i-=65536,o[r++]=55296|i>>10&1023,o[r++]=56320|1023&i)}return n(o,r)},a.utf8border=function(t,e){var a;for(e=e||t.length,e>t.length&&(e=t.length),a=e-1;a>=0&&128===(192&t[a]);)a--;return 0>a?e:0===a?e:a+l[t[a]]>e?a:e}},{"./common":1}],3:[function(t,e,a){"use strict";function n(t,e,a,n){for(var r=65535&t|0,i=t>>>16&65535|0,s=0;0!==a;){s=a>2e3?2e3:a,a-=s;do r=r+e[n++]|0,i=i+r|0;while(--s);r%=65521,i%=65521}return r|i<<16|0}e.exports=n},{}],4:[function(t,e,a){"use strict";function n(){for(var t,e=[],a=0;256>a;a++){t=a;for(var n=0;8>n;n++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e}function r(t,e,a,n){var r=i,s=n+a;t=-1^t;for(var h=n;s>h;h++)t=t>>>8^r[255&(t^e[h])];return-1^t}var i=n();e.exports=r},{}],5:[function(t,e,a){"use strict";function n(t,e){return t.msg=I[e],e}function r(t){return(t<<1)-(t>4?9:0)}function i(t){for(var e=t.length;--e>=0;)t[e]=0}function s(t){var e=t.state,a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(S.arraySet(t.output,e.pending_buf,e.pending_out,a,t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))}function h(t,e){j._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,s(t.strm)}function l(t,e){t.pending_buf[t.pending++]=e}function o(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function _(t,e,a,n){var r=t.avail_in;return r>n&&(r=n),0===r?0:(t.avail_in-=r,S.arraySet(e,t.input,t.next_in,r,a),1===t.state.wrap?t.adler=E(t.adler,e,r,a):2===t.state.wrap&&(t.adler=U(t.adler,e,r,a)),t.next_in+=r,t.total_in+=r,r)}function d(t,e){var a,n,r=t.max_chain_length,i=t.strstart,s=t.prev_length,h=t.nice_match,l=t.strstart>t.w_size-ot?t.strstart-(t.w_size-ot):0,o=t.window,_=t.w_mask,d=t.prev,u=t.strstart+lt,f=o[i+s-1],c=o[i+s];t.prev_length>=t.good_match&&(r>>=2),h>t.lookahead&&(h=t.lookahead);do if(a=e,o[a+s]===c&&o[a+s-1]===f&&o[a]===o[i]&&o[++a]===o[i+1]){i+=2,a++;do;while(o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&o[++i]===o[++a]&&u>i);if(n=lt-(u-i),i=u-lt,n>s){if(t.match_start=e,s=n,n>=h)break;f=o[i+s-1],c=o[i+s]}}while((e=d[e&_])>l&&0!==--r);return s<=t.lookahead?s:t.lookahead}function u(t){var e,a,n,r,i,s=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=s+(s-ot)){S.arraySet(t.window,t.window,s,s,0),t.match_start-=s,t.strstart-=s,t.block_start-=s,a=t.hash_size,e=a;do n=t.head[--e],t.head[e]=n>=s?n-s:0;while(--a);a=s,e=a;do n=t.prev[--e],t.prev[e]=n>=s?n-s:0;while(--a);r+=s}if(0===t.strm.avail_in)break;if(a=_(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=a,t.lookahead+t.insert>=ht)for(i=t.strstart-t.insert,t.ins_h=t.window[i],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(u(t),0===t.lookahead&&e===D)return bt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+a;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,h(t,!1),0===t.strm.avail_out))return bt;if(t.strstart-t.block_start>=t.w_size-ot&&(h(t,!1),0===t.strm.avail_out))return bt}return t.insert=0,e===T?(h(t,!0),0===t.strm.avail_out?wt:yt):t.strstart>t.block_start&&(h(t,!1),0===t.strm.avail_out)?bt:bt}function c(t,e){for(var a,n;;){if(t.lookahead=ht&&(t.ins_h=(t.ins_h<=ht)if(n=j._tr_tally(t,t.strstart-t.match_start,t.match_length-ht),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ht){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=ht&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=ht-1)),t.prev_length>=ht&&t.match_length<=t.prev_length){r=t.strstart+t.lookahead-ht,n=j._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ht),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=r&&(t.ins_h=(t.ins_h<=ht&&t.strstart>0&&(r=t.strstart-1,n=s[r],n===s[++r]&&n===s[++r]&&n===s[++r])){i=t.strstart+lt;do;while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&i>r);t.match_length=lt-(i-r),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ht?(a=j._tr_tally(t,1,t.match_length-ht),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(h(t,!1),0===t.strm.avail_out))return bt}return t.insert=0,e===T?(h(t,!0),0===t.strm.avail_out?wt:yt):t.last_lit&&(h(t,!1),0===t.strm.avail_out)?bt:vt}function m(t,e){for(var a;;){if(0===t.lookahead&&(u(t),0===t.lookahead)){if(e===D)return bt;break}if(t.match_length=0,a=j._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(h(t,!1),0===t.strm.avail_out))return bt}return t.insert=0,e===T?(h(t,!0),0===t.strm.avail_out?wt:yt):t.last_lit&&(h(t,!1),0===t.strm.avail_out)?bt:vt}function b(t){t.window_size=2*t.w_size,i(t.head),t.max_lazy_match=C[t.level].max_lazy,t.good_match=C[t.level].good_length,t.nice_match=C[t.level].nice_length,t.max_chain_length=C[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ht-1,t.match_available=0,t.ins_h=0}function v(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=X,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new S.Buf16(2*it),this.dyn_dtree=new S.Buf16(2*(2*nt+1)),this.bl_tree=new S.Buf16(2*(2*rt+1)),i(this.dyn_ltree),i(this.dyn_dtree),i(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new S.Buf16(st+1),this.heap=new S.Buf16(2*at+1),i(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new S.Buf16(2*at+1),i(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function w(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=W,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?dt:pt,t.adler=2===e.wrap?0:1,e.last_flush=D,j._tr_init(e),N):n(t,H)}function y(t){var e=w(t);return e===N&&b(t.state),e}function z(t,e){return t&&t.state?2!==t.state.wrap?H:(t.state.gzhead=e,N):H}function k(t,e,a,r,i,s){if(!t)return H;var h=1;if(e===M&&(e=6),0>r?(h=0,r=-r):r>15&&(h=2,r-=16),1>i||i>Y||a!==X||8>r||r>15||0>e||e>9||0>s||s>Q)return n(t,H);8===r&&(r=9);var l=new v;return t.state=l,l.strm=t,l.wrap=h,l.gzhead=null,l.w_bits=r,l.w_size=1<>1,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=s,l.method=a,y(t)}function x(t,e){return k(t,e,X,Z,$,V)}function B(t,e){var a,h,_,d;if(!t||!t.state||e>L||0>e)return t?n(t,H):H;if(h=t.state,!t.output||!t.input&&0!==t.avail_in||h.status===mt&&e!==T)return n(t,0===t.avail_out?K:H);if(h.strm=t,a=h.last_flush,h.last_flush=e,h.status===dt)if(2===h.wrap)t.adler=0,l(h,31),l(h,139),l(h,8),h.gzhead?(l(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),l(h,255&h.gzhead.time),l(h,h.gzhead.time>>8&255),l(h,h.gzhead.time>>16&255),l(h,h.gzhead.time>>24&255),l(h,9===h.level?2:h.strategy>=G||h.level<2?4:0),l(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(l(h,255&h.gzhead.extra.length),l(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(t.adler=U(t.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ut):(l(h,0),l(h,0),l(h,0),l(h,0),l(h,0),l(h,9===h.level?2:h.strategy>=G||h.level<2?4:0),l(h,zt),h.status=pt);else{var u=X+(h.w_bits-8<<4)<<8,f=-1;f=h.strategy>=G||h.level<2?0:h.level<6?1:6===h.level?2:3,u|=f<<6,0!==h.strstart&&(u|=_t),u+=31-u%31,h.status=pt,o(h,u),0!==h.strstart&&(o(h,t.adler>>>16),o(h,65535&t.adler)),t.adler=1}if(h.status===ut)if(h.gzhead.extra){for(_=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>_&&(t.adler=U(t.adler,h.pending_buf,h.pending-_,_)),s(t),_=h.pending,h.pending!==h.pending_buf_size));)l(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>_&&(t.adler=U(t.adler,h.pending_buf,h.pending-_,_)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=ft)}else h.status=ft;if(h.status===ft)if(h.gzhead.name){_=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>_&&(t.adler=U(t.adler,h.pending_buf,h.pending-_,_)),s(t),_=h.pending,h.pending===h.pending_buf_size)){d=1;break}d=h.gzindex_&&(t.adler=U(t.adler,h.pending_buf,h.pending-_,_)),0===d&&(h.gzindex=0,h.status=ct)}else h.status=ct;if(h.status===ct)if(h.gzhead.comment){_=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>_&&(t.adler=U(t.adler,h.pending_buf,h.pending-_,_)),s(t),_=h.pending,h.pending===h.pending_buf_size)){d=1;break}d=h.gzindex_&&(t.adler=U(t.adler,h.pending_buf,h.pending-_,_)),0===d&&(h.status=gt)}else h.status=gt;if(h.status===gt&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&s(t),h.pending+2<=h.pending_buf_size&&(l(h,255&t.adler),l(h,t.adler>>8&255),t.adler=0,h.status=pt)):h.status=pt),0!==h.pending){if(s(t),0===t.avail_out)return h.last_flush=-1,N}else if(0===t.avail_in&&r(e)<=r(a)&&e!==T)return n(t,K);if(h.status===mt&&0!==t.avail_in)return n(t,K);if(0!==t.avail_in||0!==h.lookahead||e!==D&&h.status!==mt){var c=h.strategy===G?m(h,e):h.strategy===J?p(h,e):C[h.level].func(h,e);if((c===wt||c===yt)&&(h.status=mt),c===bt||c===wt)return 0===t.avail_out&&(h.last_flush=-1),N;if(c===vt&&(e===O?j._tr_align(h):e!==L&&(j._tr_stored_block(h,0,0,!1),e===q&&(i(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),s(t),0===t.avail_out))return h.last_flush=-1,N}return e!==T?N:h.wrap<=0?R:(2===h.wrap?(l(h,255&t.adler),l(h,t.adler>>8&255),l(h,t.adler>>16&255),l(h,t.adler>>24&255),l(h,255&t.total_in),l(h,t.total_in>>8&255),l(h,t.total_in>>16&255),l(h,t.total_in>>24&255)):(o(h,t.adler>>>16),o(h,65535&t.adler)),s(t),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?N:R)}function A(t){var e;return t&&t.state?(e=t.state.status,e!==dt&&e!==ut&&e!==ft&&e!==ct&&e!==gt&&e!==pt&&e!==mt?n(t,H):(t.state=null,e===pt?n(t,F):N)):H}var C,S=t("../utils/common"),j=t("./trees"),E=t("./adler32"),U=t("./crc32"),I=t("./messages"),D=0,O=1,q=3,T=4,L=5,N=0,R=1,H=-2,F=-3,K=-5,M=-1,P=1,G=2,J=3,Q=4,V=0,W=2,X=8,Y=9,Z=15,$=8,tt=29,et=256,at=et+1+tt,nt=30,rt=19,it=2*at+1,st=15,ht=3,lt=258,ot=lt+ht+1,_t=32,dt=42,ut=69,ft=73,ct=91,gt=103,pt=113,mt=666,bt=1,vt=2,wt=3,yt=4,zt=3,kt=function(t,e,a,n,r){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=n,this.func=r};C=[new kt(0,0,0,0,f),new kt(4,4,8,4,c),new kt(4,5,16,8,c),new kt(4,6,32,32,c),new kt(4,4,16,16,g),new kt(8,16,32,32,g),new kt(8,16,128,128,g),new kt(8,32,128,256,g),new kt(32,128,258,1024,g),new kt(32,258,258,4096,g)],a.deflateInit=x,a.deflateInit2=k,a.deflateReset=y,a.deflateResetKeep=w,a.deflateSetHeader=z,a.deflate=B,a.deflateEnd=A,a.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":4,"./messages":6,"./trees":7}],6:[function(t,e,a){"use strict";e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],7:[function(t,e,a){"use strict";function n(t){for(var e=t.length;--e>=0;)t[e]=0}function r(t){return 256>t?st[t]:st[256+(t>>>7)]}function i(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function s(t,e,a){t.bi_valid>Q-a?(t.bi_buf|=e<>Q-t.bi_valid,t.bi_valid+=a-Q):(t.bi_buf|=e<>>=1,a<<=1;while(--e>0);return a>>>1}function o(t){16===t.bi_valid?(i(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function _(t,e){var a,n,r,i,s,h,l=e.dyn_tree,o=e.max_code,_=e.stat_desc.static_tree,d=e.stat_desc.has_stree,u=e.stat_desc.extra_bits,f=e.stat_desc.extra_base,c=e.stat_desc.max_length,g=0;for(i=0;J>=i;i++)t.bl_count[i]=0;for(l[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;G>a;a++)n=t.heap[a],i=l[2*l[2*n+1]+1]+1,i>c&&(i=c,g++),l[2*n+1]=i,n>o||(t.bl_count[i]++,s=0,n>=f&&(s=u[n-f]),h=l[2*n],t.opt_len+=h*(i+s),d&&(t.static_len+=h*(_[2*n+1]+s)));if(0!==g){do{for(i=c-1;0===t.bl_count[i];)i--;t.bl_count[i]--,t.bl_count[i+1]+=2,t.bl_count[c]--,g-=2}while(g>0);for(i=c;0!==i;i--)for(n=t.bl_count[i];0!==n;)r=t.heap[--a],r>o||(l[2*r+1]!==i&&(t.opt_len+=(i-l[2*r+1])*l[2*r],l[2*r+1]=i),n--)}}function d(t,e,a){var n,r,i=new Array(J+1),s=0;for(n=1;J>=n;n++)i[n]=s=s+a[n-1]<<1;for(r=0;e>=r;r++){var h=t[2*r+1];0!==h&&(t[2*r]=l(i[h]++,h))}}function u(){var t,e,a,n,r,i=new Array(J+1);for(a=0,n=0;H-1>n;n++)for(lt[n]=a,t=0;t<1<<$[n];t++)ht[a++]=n;for(ht[a-1]=n,r=0,n=0;16>n;n++)for(ot[n]=r,t=0;t<1<>=7;M>n;n++)for(ot[n]=r<<7,t=0;t<1<=e;e++)i[e]=0;for(t=0;143>=t;)rt[2*t+1]=8,t++,i[8]++;for(;255>=t;)rt[2*t+1]=9,t++,i[9]++;for(;279>=t;)rt[2*t+1]=7,t++,i[7]++;for(;287>=t;)rt[2*t+1]=8,t++,i[8]++;for(d(rt,K+1,i),t=0;M>t;t++)it[2*t+1]=5,it[2*t]=l(t,5);_t=new ft(rt,$,F+1,K,J),dt=new ft(it,tt,0,M,J),ut=new ft(new Array(0),et,0,P,V)}function f(t){var e;for(e=0;K>e;e++)t.dyn_ltree[2*e]=0;for(e=0;M>e;e++)t.dyn_dtree[2*e]=0;for(e=0;P>e;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*W]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function c(t){t.bi_valid>8?i(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function g(t,e,a,n){c(t),n&&(i(t,a),i(t,~a)),E.arraySet(t.pending_buf,t.window,e,a,t.pending),t.pending+=a}function p(t,e,a,n){var r=2*e,i=2*a;return t[r]a;a++)0!==i[2*a]?(t.heap[++t.heap_len]=o=a,t.depth[a]=0):i[2*a+1]=0;for(;t.heap_len<2;)r=t.heap[++t.heap_len]=2>o?++o:0,i[2*r]=1,t.depth[r]=0,t.opt_len--,h&&(t.static_len-=s[2*r+1]);for(e.max_code=o,a=t.heap_len>>1;a>=1;a--)m(t,i,a);r=l;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],m(t,i,1),n=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=n,i[2*r]=i[2*a]+i[2*n],t.depth[r]=(t.depth[a]>=t.depth[n]?t.depth[a]:t.depth[n])+1,i[2*a+1]=i[2*n+1]=r,t.heap[1]=r++,m(t,i,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],_(t,e),d(i,o,t.bl_count)}function w(t,e,a){var n,r,i=-1,s=e[1],h=0,l=7,o=4;for(0===s&&(l=138,o=3),e[2*(a+1)+1]=65535,n=0;a>=n;n++)r=s,s=e[2*(n+1)+1],++hh?t.bl_tree[2*r]+=h:0!==r?(r!==i&&t.bl_tree[2*r]++,t.bl_tree[2*X]++):10>=h?t.bl_tree[2*Y]++:t.bl_tree[2*Z]++,h=0,i=r,0===s?(l=138,o=3):r===s?(l=6,o=3):(l=7,o=4))}function y(t,e,a){var n,r,i=-1,l=e[1],o=0,_=7,d=4;for(0===l&&(_=138,d=3),n=0;a>=n;n++)if(r=l,l=e[2*(n+1)+1],!(++o<_&&r===l)){if(d>o){do h(t,r,t.bl_tree);while(0!==--o)}else 0!==r?(r!==i&&(h(t,r,t.bl_tree),o--),h(t,X,t.bl_tree),s(t,o-3,2)):10>=o?(h(t,Y,t.bl_tree),s(t,o-3,3)):(h(t,Z,t.bl_tree),s(t,o-11,7));o=0,i=r,0===l?(_=138,d=3):r===l?(_=6,d=3):(_=7,d=4)}}function z(t){var e;for(w(t,t.dyn_ltree,t.l_desc.max_code),w(t,t.dyn_dtree,t.d_desc.max_code),v(t,t.bl_desc),e=P-1;e>=3&&0===t.bl_tree[2*at[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function k(t,e,a,n){var r;for(s(t,e-257,5),s(t,a-1,5),s(t,n-4,4),r=0;n>r;r++)s(t,t.bl_tree[2*at[r]+1],3);y(t,t.dyn_ltree,e-1),y(t,t.dyn_dtree,a-1)}function x(t){var e,a=4093624447;for(e=0;31>=e;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return I;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return D;for(e=32;F>e;e++)if(0!==t.dyn_ltree[2*e])return D;return I}function B(t){gt||(u(),gt=!0),t.l_desc=new ct(t.dyn_ltree,_t),t.d_desc=new ct(t.dyn_dtree,dt),t.bl_desc=new ct(t.bl_tree,ut),t.bi_buf=0,t.bi_valid=0,f(t)}function A(t,e,a,n){s(t,(q<<1)+(n?1:0),3),g(t,e,a,!0)}function C(t){s(t,T<<1,3),h(t,W,rt),o(t)}function S(t,e,a,n){var r,i,h=0;t.level>0?(t.strm.data_type===O&&(t.strm.data_type=x(t)),v(t,t.l_desc),v(t,t.d_desc),h=z(t),r=t.opt_len+3+7>>>3,i=t.static_len+3+7>>>3,r>=i&&(r=i)):r=i=a+5,r>=a+4&&-1!==e?A(t,e,a,n):t.strategy===U||i===r?(s(t,(T<<1)+(n?1:0),3),b(t,rt,it)):(s(t,(L<<1)+(n?1:0),3),k(t,t.l_desc.max_code+1,t.d_desc.max_code+1,h+1),b(t,t.dyn_ltree,t.dyn_dtree)),f(t),n&&c(t)}function j(t,e,a){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(ht[a]+F+1)]++,t.dyn_dtree[2*r(e)]++),t.last_lit===t.lit_bufsize-1}var E=t("../utils/common"),U=4,I=0,D=1,O=2,q=0,T=1,L=2,N=3,R=258,H=29,F=256,K=F+1+H,M=30,P=19,G=2*K+1,J=15,Q=16,V=7,W=256,X=16,Y=17,Z=18,$=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],tt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],et=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],at=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],nt=512,rt=new Array(2*(K+2));n(rt);var it=new Array(2*M);n(it);var st=new Array(nt);n(st);var ht=new Array(R-N+1);n(ht);var lt=new Array(H);n(lt);var ot=new Array(M);n(ot);var _t,dt,ut,ft=function(t,e,a,n,r){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=n,this.max_length=r,this.has_stree=t&&t.length},ct=function(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e},gt=!1;a._tr_init=B,a._tr_stored_block=A,a._tr_flush_block=S,a._tr_tally=j,a._tr_align=C},{"../utils/common":1}],8:[function(t,e,a){"use strict";function n(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}e.exports=n},{}],"/lib/deflate.js":[function(t,e,a){"use strict";function n(t,e){var a=new w(e);if(a.push(t,!0),a.err)throw a.msg;return a.result}function r(t,e){return e=e||{},e.raw=!0,n(t,e)}function i(t,e){return e=e||{},e.gzip=!0,n(t,e)}var s=t("./zlib/deflate.js"),h=t("./utils/common"),l=t("./utils/strings"),o=t("./zlib/messages"),_=t("./zlib/zstream"),d=Object.prototype.toString,u=0,f=4,c=0,g=1,p=2,m=-1,b=0,v=8,w=function(t){this.options=h.assign({level:m,method:v,chunkSize:16384,windowBits:15,memLevel:8,strategy:b,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _,this.strm.avail_out=0;var a=s.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==c)throw new Error(o[a]);e.header&&s.deflateSetHeader(this.strm,e.header)};w.prototype.push=function(t,e){var a,n,r=this.strm,i=this.options.chunkSize;if(this.ended)return!1;n=e===~~e?e:e===!0?f:u,"string"==typeof t?r.input=l.string2buf(t):"[object ArrayBuffer]"===d.call(t)?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(0===r.avail_out&&(r.output=new h.Buf8(i),r.next_out=0,r.avail_out=i),a=s.deflate(r,n),a!==g&&a!==c)return this.onEnd(a),this.ended=!0,!1;(0===r.avail_out||0===r.avail_in&&(n===f||n===p))&&this.onData("string"===this.options.to?l.buf2binstring(h.shrinkBuf(r.output,r.next_out)):h.shrinkBuf(r.output,r.next_out))}while((r.avail_in>0||0===r.avail_out)&&a!==g);return n===f?(a=s.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===c):n===p?(this.onEnd(c),r.avail_out=0,!0):!0},w.prototype.onData=function(t){this.chunks.push(t)},w.prototype.onEnd=function(t){t===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},a.Deflate=w,a.deflate=n,a.deflateRaw=r,a.gzip=i},{"./utils/common":1,"./utils/strings":2,"./zlib/deflate.js":5,"./zlib/messages":6,"./zlib/zstream":8}]},{},[])("/lib/deflate.js")}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_inflate.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_inflate.js new file mode 100644 index 0000000..06844d1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_inflate.js @@ -0,0 +1,3071 @@ +/* pako 0.2.8 nodeca/pako */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254]=_utf8len[254]=1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { + c2 = str.charCodeAt(m_pos+1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i=0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { + c2 = str.charCodeAt(m_pos+1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // use fallback for big arrays to avoid stack overflow + if (len < 65537) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i=0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i=0, len=buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len*2); + + for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function(buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max-1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Fuckup - very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means vuffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +},{"./common":1}],3:[function(require,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It doesn't worth to make additional optimizationa as in original. +// Small size is preferable. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],4:[function(require,module,exports){ +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + +},{}],5:[function(require,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n =0; n < 256; n++) { + c = n; + for (var k =0; k < 8; k++) { + c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc = crc ^ (-1); + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],6:[function(require,module,exports){ +'use strict'; + + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; + +},{}],7:[function(require,module,exports){ +'use strict'; + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +},{}],8:[function(require,module,exports){ +'use strict'; + + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function ZSWAP32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window,src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window,src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more conveniend processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = ZSWAP32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = {bits: state.lenbits}; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = {bits: state.lenbits}; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = {bits: state.distbits}; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' insdead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too + if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(require,module,exports){ +'use strict'; + + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + var i=0; + /* process all codes and make table entries */ + for (;;) { + i++; + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +},{"../utils/common":1}],10:[function(require,module,exports){ +'use strict'; + +module.exports = { + '2': 'need dictionary', /* Z_NEED_DICT 2 */ + '1': 'stream end', /* Z_STREAM_END 1 */ + '0': '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],11:[function(require,module,exports){ +'use strict'; + + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],"/lib/inflate.js":[function(require,module,exports){ +'use strict'; + + +var zlib_inflate = require('./zlib/inflate.js'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var c = require('./zlib/constants'); +var msg = require('./zlib/messages'); +var zstream = require('./zlib/zstream'); +var gzheader = require('./zlib/gzheader'); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overriden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +var Inflate = function(options) { + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new gzheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); +}; + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): ouput data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function(status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 alligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; + +},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate.js":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js") +}); \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_inflate.min.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_inflate.min.js new file mode 100644 index 0000000..77f6c00 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/dist/pako_inflate.min.js @@ -0,0 +1,2 @@ +/* pako 0.2.8 nodeca/pako */ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.pako=e()}}(function(){return function e(t,i,n){function a(o,s){if(!i[o]){if(!t[o]){var f="function"==typeof require&&require;if(!s&&f)return f(o,!0);if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var d=i[o]={exports:{}};t[o][0].call(d.exports,function(e){var i=t[o][1][e];return a(i?i:e)},d,d.exports,e,t,i,n)}return i[o].exports}for(var r="function"==typeof require&&require,o=0;or;r++)e[a+r]=t[i+r]},flattenChunks:function(e){var t,i,n,a,r,o;for(n=0,t=0,i=e.length;i>t;t++)n+=e[t].length;for(o=new Uint8Array(n),a=0,t=0,i=e.length;i>t;t++)r=e[t],o.set(r,a),a+=r.length;return o}},r={arraySet:function(e,t,i,n,a){for(var r=0;n>r;r++)e[a+r]=t[i+r]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,a)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],2:[function(e,t,i){"use strict";function n(e,t){if(65537>t&&(e.subarray&&o||!e.subarray&&r))return String.fromCharCode.apply(null,a.shrinkBuf(e,t));for(var i="",n=0;t>n;n++)i+=String.fromCharCode(e[n]);return i}var a=e("./common"),r=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(s){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(s){o=!1}for(var f=new a.Buf8(256),l=0;256>l;l++)f[l]=l>=252?6:l>=248?5:l>=240?4:l>=224?3:l>=192?2:1;f[254]=f[254]=1,i.string2buf=function(e){var t,i,n,r,o,s=e.length,f=0;for(r=0;s>r;r++)i=e.charCodeAt(r),55296===(64512&i)&&s>r+1&&(n=e.charCodeAt(r+1),56320===(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),f+=128>i?1:2048>i?2:65536>i?3:4;for(t=new a.Buf8(f),o=0,r=0;f>o;r++)i=e.charCodeAt(r),55296===(64512&i)&&s>r+1&&(n=e.charCodeAt(r+1),56320===(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),128>i?t[o++]=i:2048>i?(t[o++]=192|i>>>6,t[o++]=128|63&i):65536>i?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},i.buf2binstring=function(e){return n(e,e.length)},i.binstring2buf=function(e){for(var t=new a.Buf8(e.length),i=0,n=t.length;n>i;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,a,r,o,s=t||e.length,l=new Array(2*s);for(a=0,i=0;s>i;)if(r=e[i++],128>r)l[a++]=r;else if(o=f[r],o>4)l[a++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&s>i;)r=r<<6|63&e[i++],o--;o>1?l[a++]=65533:65536>r?l[a++]=r:(r-=65536,l[a++]=55296|r>>10&1023,l[a++]=56320|1023&r)}return n(l,a)},i.utf8border=function(e,t){var i;for(t=t||e.length,t>e.length&&(t=e.length),i=t-1;i>=0&&128===(192&e[i]);)i--;return 0>i?t:0===i?t:i+f[e[i]]>t?i:t}},{"./common":1}],3:[function(e,t,i){"use strict";function n(e,t,i,n){for(var a=65535&e|0,r=e>>>16&65535|0,o=0;0!==i;){o=i>2e3?2e3:i,i-=o;do a=a+t[n++]|0,r=r+a|0;while(--o);a%=65521,r%=65521}return a|r<<16|0}t.exports=n},{}],4:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,i){"use strict";function n(){for(var e,t=[],i=0;256>i;i++){e=i;for(var n=0;8>n;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}function a(e,t,i,n){var a=r,o=n+i;e=-1^e;for(var s=n;o>s;s++)e=e>>>8^a[255&(e^t[s])];return-1^e}var r=n();t.exports=a},{}],6:[function(e,t,i){"use strict";function n(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}t.exports=n},{}],7:[function(e,t,i){"use strict";var n=30,a=12;t.exports=function(e,t){var i,r,o,s,f,l,d,u,h,c,b,w,m,k,_,g,v,p,x,y,S,E,B,Z,A;i=e.state,r=e.next_in,Z=e.input,o=r+(e.avail_in-5),s=e.next_out,A=e.output,f=s-(t-e.avail_out),l=s+(e.avail_out-257),d=i.dmax,u=i.wsize,h=i.whave,c=i.wnext,b=i.window,w=i.hold,m=i.bits,k=i.lencode,_=i.distcode,g=(1<m&&(w+=Z[r++]<>>24,w>>>=x,m-=x,x=p>>>16&255,0===x)A[s++]=65535&p;else{if(!(16&x)){if(0===(64&x)){p=k[(65535&p)+(w&(1<m&&(w+=Z[r++]<>>=x,m-=x),15>m&&(w+=Z[r++]<>>24,w>>>=x,m-=x,x=p>>>16&255,!(16&x)){if(0===(64&x)){p=_[(65535&p)+(w&(1<m&&(w+=Z[r++]<m&&(w+=Z[r++]<d){e.msg="invalid distance too far back",i.mode=n;break e}if(w>>>=x,m-=x,x=s-f,S>x){if(x=S-x,x>h&&i.sane){e.msg="invalid distance too far back",i.mode=n;break e}if(E=0,B=b,0===c){if(E+=u-x,y>x){y-=x;do A[s++]=b[E++];while(--x);E=s-S,B=A}}else if(x>c){if(E+=u+c-x,x-=c,y>x){y-=x;do A[s++]=b[E++];while(--x);if(E=0,y>c){x=c,y-=x;do A[s++]=b[E++];while(--x);E=s-S,B=A}}}else if(E+=c-x,y>x){y-=x;do A[s++]=b[E++];while(--x);E=s-S,B=A}for(;y>2;)A[s++]=B[E++],A[s++]=B[E++],A[s++]=B[E++],y-=3;y&&(A[s++]=B[E++],y>1&&(A[s++]=B[E++]))}else{E=s-S;do A[s++]=A[E++],A[s++]=A[E++],A[s++]=A[E++],y-=3;while(y>2);y&&(A[s++]=A[E++],y>1&&(A[s++]=A[E++]))}break}}break}}while(o>r&&l>s);y=m>>3,r-=y,m-=y<<3,w&=(1<r?5+(o-r):5-(r-o),e.avail_out=l>s?257+(l-s):257-(s-l),i.hold=w,i.bits=m}},{}],8:[function(e,t,i){"use strict";function n(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function a(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new k.Buf16(320),this.work=new k.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function r(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=T,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new k.Buf32(be),t.distcode=t.distdyn=new k.Buf32(we),t.sane=1,t.back=-1,A):N}function o(e){var t;return e&&e.state?(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,r(e)):N}function s(e,t){var i,n;return e&&e.state?(n=e.state,0>t?(i=0,t=-t):(i=(t>>4)+1,48>t&&(t&=15)),t&&(8>t||t>15)?N:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,o(e))):N}function f(e,t){var i,n;return e?(n=new a,e.state=n,n.window=null,i=s(e,t),i!==A&&(e.state=null),i):N}function l(e){return f(e,ke)}function d(e){if(_e){var t;for(w=new k.Buf32(512),m=new k.Buf32(32),t=0;144>t;)e.lens[t++]=8;for(;256>t;)e.lens[t++]=9;for(;280>t;)e.lens[t++]=7;for(;288>t;)e.lens[t++]=8;for(p(y,e.lens,0,288,w,0,e.work,{bits:9}),t=0;32>t;)e.lens[t++]=5;p(S,e.lens,0,32,m,0,e.work,{bits:5}),_e=!1}e.lencode=w,e.lenbits=9,e.distcode=m,e.distbits=5}function u(e,t,i,n){var a,r=e.state;return null===r.window&&(r.wsize=1<=r.wsize?(k.arraySet(r.window,t,i-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(a=r.wsize-r.wnext,a>n&&(a=n),k.arraySet(r.window,t,i-n,a,r.wnext),n-=a,n?(k.arraySet(r.window,t,i-n,n,0),r.wnext=n,r.whave=r.wsize):(r.wnext+=a,r.wnext===r.wsize&&(r.wnext=0),r.whavec;){if(0===f)break e;f--,h+=a[o++]<>>8&255,i.check=g(i.check,Ze,2,0),h=0,c=0,i.mode=U;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",i.mode=ue;break}if((15&h)!==F){e.msg="unknown compression method",i.mode=ue;break}if(h>>>=4,c-=4,xe=(15&h)+8,0===i.wbits)i.wbits=xe;else if(xe>i.wbits){e.msg="invalid window size",i.mode=ue;break}i.dmax=1<c;){if(0===f)break e;f--,h+=a[o++]<>8&1),512&i.flags&&(Ze[0]=255&h,Ze[1]=h>>>8&255,i.check=g(i.check,Ze,2,0)),h=0,c=0,i.mode=D;case D:for(;32>c;){if(0===f)break e;f--,h+=a[o++]<>>8&255,Ze[2]=h>>>16&255,Ze[3]=h>>>24&255,i.check=g(i.check,Ze,4,0)),h=0,c=0,i.mode=L;case L:for(;16>c;){if(0===f)break e;f--,h+=a[o++]<>8),512&i.flags&&(Ze[0]=255&h,Ze[1]=h>>>8&255,i.check=g(i.check,Ze,2,0)),h=0,c=0,i.mode=H;case H:if(1024&i.flags){for(;16>c;){if(0===f)break e;f--,h+=a[o++]<>>8&255,i.check=g(i.check,Ze,2,0)),h=0,c=0}else i.head&&(i.head.extra=null);i.mode=j;case j:if(1024&i.flags&&(m=i.length,m>f&&(m=f),m&&(i.head&&(xe=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),k.arraySet(i.head.extra,a,o,m,xe)),512&i.flags&&(i.check=g(i.check,a,m,o)),f-=m,o+=m,i.length-=m),i.length))break e;i.length=0,i.mode=M;case M:if(2048&i.flags){if(0===f)break e;m=0;do xe=a[o+m++],i.head&&xe&&i.length<65536&&(i.head.name+=String.fromCharCode(xe));while(xe&&f>m);if(512&i.flags&&(i.check=g(i.check,a,m,o)),f-=m,o+=m,xe)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=K;case K:if(4096&i.flags){if(0===f)break e;m=0;do xe=a[o+m++],i.head&&xe&&i.length<65536&&(i.head.comment+=String.fromCharCode(xe));while(xe&&f>m);if(512&i.flags&&(i.check=g(i.check,a,m,o)),f-=m,o+=m,xe)break e}else i.head&&(i.head.comment=null);i.mode=P;case P:if(512&i.flags){for(;16>c;){if(0===f)break e;f--,h+=a[o++]<>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=G;break;case Y:for(;32>c;){if(0===f)break e;f--,h+=a[o++]<>>=7&c,c-=7&c,i.mode=fe;break}for(;3>c;){if(0===f)break e;f--,h+=a[o++]<>>=1,c-=1,3&h){case 0:i.mode=W;break;case 1:if(d(i),i.mode=te,t===Z){h>>>=2,c-=2;break e}break;case 2:i.mode=V;break;case 3:e.msg="invalid block type",i.mode=ue}h>>>=2,c-=2;break;case W:for(h>>>=7&c,c-=7&c;32>c;){if(0===f)break e;f--,h+=a[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=ue;break}if(i.length=65535&h,h=0,c=0,i.mode=J,t===Z)break e;case J:i.mode=Q;case Q:if(m=i.length){if(m>f&&(m=f),m>l&&(m=l),0===m)break e;k.arraySet(r,a,o,m,s),f-=m,o+=m,l-=m,s+=m,i.length-=m;break}i.mode=G;break;case V:for(;14>c;){if(0===f)break e;f--,h+=a[o++]<>>=5,c-=5,i.ndist=(31&h)+1,h>>>=5,c-=5,i.ncode=(15&h)+4,h>>>=4,c-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=ue;break}i.have=0,i.mode=$;case $:for(;i.havec;){if(0===f)break e;f--,h+=a[o++]<>>=3,c-=3}for(;i.have<19;)i.lens[Ae[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,Se={bits:i.lenbits},ye=p(x,i.lens,0,19,i.lencode,0,i.work,Se),i.lenbits=Se.bits,ye){e.msg="invalid code lengths set",i.mode=ue;break}i.have=0,i.mode=ee;case ee:for(;i.have>>24,ke=Be>>>16&255,_e=65535&Be,!(c>=me);){if(0===f)break e;f--,h+=a[o++]<_e)h>>>=me,c-=me,i.lens[i.have++]=_e;else{if(16===_e){for(Ee=me+2;Ee>c;){if(0===f)break e;f--,h+=a[o++]<>>=me,c-=me,0===i.have){e.msg="invalid bit length repeat",i.mode=ue;break}xe=i.lens[i.have-1],m=3+(3&h),h>>>=2,c-=2}else if(17===_e){for(Ee=me+3;Ee>c;){if(0===f)break e;f--,h+=a[o++]<>>=me,c-=me,xe=0,m=3+(7&h),h>>>=3,c-=3}else{for(Ee=me+7;Ee>c;){if(0===f)break e;f--,h+=a[o++]<>>=me,c-=me,xe=0,m=11+(127&h),h>>>=7,c-=7}if(i.have+m>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=ue;break}for(;m--;)i.lens[i.have++]=xe}}if(i.mode===ue)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=ue;break}if(i.lenbits=9,Se={bits:i.lenbits},ye=p(y,i.lens,0,i.nlen,i.lencode,0,i.work,Se),i.lenbits=Se.bits,ye){e.msg="invalid literal/lengths set",i.mode=ue;break}if(i.distbits=6,i.distcode=i.distdyn,Se={bits:i.distbits},ye=p(S,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,Se),i.distbits=Se.bits,ye){e.msg="invalid distances set",i.mode=ue;break}if(i.mode=te,t===Z)break e;case te:i.mode=ie;case ie:if(f>=6&&l>=258){e.next_out=s,e.avail_out=l,e.next_in=o,e.avail_in=f,i.hold=h,i.bits=c,v(e,w),s=e.next_out,r=e.output,l=e.avail_out,o=e.next_in,a=e.input,f=e.avail_in,h=i.hold,c=i.bits,i.mode===G&&(i.back=-1);break}for(i.back=0;Be=i.lencode[h&(1<>>24,ke=Be>>>16&255,_e=65535&Be,!(c>=me);){if(0===f)break e;f--,h+=a[o++]<>ge)],me=Be>>>24,ke=Be>>>16&255,_e=65535&Be,!(c>=ge+me);){if(0===f)break e;f--,h+=a[o++]<>>=ge,c-=ge,i.back+=ge}if(h>>>=me,c-=me,i.back+=me,i.length=_e,0===ke){i.mode=se;break}if(32&ke){i.back=-1,i.mode=G;break}if(64&ke){e.msg="invalid literal/length code",i.mode=ue;break}i.extra=15&ke,i.mode=ne;case ne:if(i.extra){for(Ee=i.extra;Ee>c;){if(0===f)break e;f--,h+=a[o++]<>>=i.extra,c-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=ae;case ae:for(;Be=i.distcode[h&(1<>>24,ke=Be>>>16&255,_e=65535&Be,!(c>=me);){if(0===f)break e;f--,h+=a[o++]<>ge)],me=Be>>>24,ke=Be>>>16&255,_e=65535&Be,!(c>=ge+me);){if(0===f)break e;f--,h+=a[o++]<>>=ge,c-=ge,i.back+=ge}if(h>>>=me,c-=me,i.back+=me,64&ke){e.msg="invalid distance code",i.mode=ue;break}i.offset=_e,i.extra=15&ke,i.mode=re;case re:if(i.extra){for(Ee=i.extra;Ee>c;){if(0===f)break e;f--,h+=a[o++]<>>=i.extra,c-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=ue;break}i.mode=oe;case oe:if(0===l)break e;if(m=w-l,i.offset>m){if(m=i.offset-m,m>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=ue;break}m>i.wnext?(m-=i.wnext,be=i.wsize-m):be=i.wnext-m,m>i.length&&(m=i.length),we=i.window}else we=r,be=s-i.offset,m=i.length;m>l&&(m=l),l-=m,i.length-=m;do r[s++]=we[be++];while(--m);0===i.length&&(i.mode=ie);break;case se:if(0===l)break e;r[s++]=i.length,l--,i.mode=ie;break;case fe:if(i.wrap){for(;32>c;){if(0===f)break e;f--,h|=a[o++]<c;){if(0===f)break e;f--,h+=a[o++]<=z;z++)j[z]=0;for(R=0;b>R;R++)j[t[i+R]]++;for(C=A,O=a;O>=1&&0===j[O];O--);if(C>O&&(C=O),0===O)return w[m++]=20971520,w[m++]=20971520,_.bits=1,0;for(N=1;O>N&&0===j[N];N++);for(N>C&&(C=N),T=1,z=1;a>=z;z++)if(T<<=1,T-=j[z],0>T)return-1;if(T>0&&(e===s||1!==O))return-1;for(M[1]=0,z=1;a>z;z++)M[z+1]=M[z]+j[z];for(R=0;b>R;R++)0!==t[i+R]&&(k[M[t[i+R]]++]=R);if(e===s?(L=K=k,S=19):e===f?(L=d,H-=257,K=u,P-=257,S=256):(L=h,K=c,S=-1),D=0,R=0,z=N,y=m,I=C,F=0,p=-1,U=1<r||e===l&&U>o)return 1;for(var Y=0;;){Y++,E=z-F,k[R]S?(B=K[P+k[R]],Z=L[H+k[R]]):(B=96,Z=0),g=1<>F)+v]=E<<24|B<<16|Z|0;while(0!==v);for(g=1<>=1;if(0!==g?(D&=g-1,D+=g):D=0,R++,0===--j[z]){if(z===O)break;z=t[i+k[R]]}if(z>C&&(D&x)!==p){for(0===F&&(F=C),y+=N,I=z-F,T=1<I+F&&(T-=j[I+F],!(0>=T));)I++,T<<=1;if(U+=1<r||e===l&&U>o)return 1;p=D&x,w[p]=C<<24|I<<16|y-m|0}}return 0!==D&&(w[y+D]=z-F<<24|64<<16|0),_.bits=C,0}},{"../utils/common":1}],10:[function(e,t,i){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,i){"use strict";function n(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=n},{}],"/lib/inflate.js":[function(e,t,i){"use strict";function n(e,t){var i=new c(t);if(i.push(e,!0),i.err)throw i.msg;return i.result}function a(e,t){return t=t||{},t.raw=!0,n(e,t)}var r=e("./zlib/inflate.js"),o=e("./utils/common"),s=e("./utils/strings"),f=e("./zlib/constants"),l=e("./zlib/messages"),d=e("./zlib/zstream"),u=e("./zlib/gzheader"),h=Object.prototype.toString,c=function(e){this.options=o.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0===(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var i=r.inflateInit2(this.strm,t.windowBits);if(i!==f.Z_OK)throw new Error(l[i]);this.header=new u,r.inflateGetHeader(this.strm,this.header)};c.prototype.push=function(e,t){var i,n,a,l,d,u=this.strm,c=this.options.chunkSize,b=!1;if(this.ended)return!1;n=t===~~t?t:t===!0?f.Z_FINISH:f.Z_NO_FLUSH,"string"==typeof e?u.input=s.binstring2buf(e):"[object ArrayBuffer]"===h.call(e)?u.input=new Uint8Array(e):u.input=e,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new o.Buf8(c),u.next_out=0,u.avail_out=c),i=r.inflate(u,f.Z_NO_FLUSH),i===f.Z_BUF_ERROR&&b===!0&&(i=f.Z_OK,b=!1),i!==f.Z_STREAM_END&&i!==f.Z_OK)return this.onEnd(i),this.ended=!0,!1;u.next_out&&(0===u.avail_out||i===f.Z_STREAM_END||0===u.avail_in&&(n===f.Z_FINISH||n===f.Z_SYNC_FLUSH))&&("string"===this.options.to?(a=s.utf8border(u.output,u.next_out),l=u.next_out-a,d=s.buf2string(u.output,a),u.next_out=l,u.avail_out=c-l,l&&o.arraySet(u.output,u.output,a,l,0),this.onData(d)):this.onData(o.shrinkBuf(u.output,u.next_out))),0===u.avail_in&&0===u.avail_out&&(b=!0)}while((u.avail_in>0||0===u.avail_out)&&i!==f.Z_STREAM_END);return i===f.Z_STREAM_END&&(n=f.Z_FINISH),n===f.Z_FINISH?(i=r.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===f.Z_OK):n===f.Z_SYNC_FLUSH?(this.onEnd(f.Z_OK),u.avail_out=0,!0):!0},c.prototype.onData=function(e){this.chunks.push(e)},c.prototype.onEnd=function(e){e===f.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=c,i.inflate=n,i.inflateRaw=a,i.ungzip=n},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate.js":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/doc/index.html b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/doc/index.html new file mode 100644 index 0000000..da6b946 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/doc/index.html @@ -0,0 +1,1639 @@ +pako 0.2.8 API documentation

pako - zlib port to javascript, very fast!

+

Build Status +NPM version

+

Why pako is cool:

+
    +
  • Almost as fast in modern JS engines as C implementation (see benchmarks).
  • +
  • Works in browsers, you can browserify any separate component.
  • +
  • Chunking support for big blobs.
  • +
  • Results are binary equal to well known zlib (now v1.2.8 ported).
  • +
+

This project was done to understand how fast JS can be and is it necessary to +develop native C modules for CPU-intensive tasks. Enjoy the result!

+

Famous projects, using pako:

+ +

Benchmarks:

+
node v0.10.26, 1mb sample:
+
+   deflate-dankogai x 4.73 ops/sec ±0.82% (15 runs sampled)
+   deflate-gildas x 4.58 ops/sec ±2.33% (15 runs sampled)
+   deflate-imaya x 3.22 ops/sec ±3.95% (12 runs sampled)
+ ! deflate-pako x 6.99 ops/sec ±0.51% (21 runs sampled)
+   deflate-pako-string x 5.89 ops/sec ±0.77% (18 runs sampled)
+   deflate-pako-untyped x 4.39 ops/sec ±1.58% (14 runs sampled)
+ * deflate-zlib x 14.71 ops/sec ±4.23% (59 runs sampled)
+   inflate-dankogai x 32.16 ops/sec ±0.13% (56 runs sampled)
+   inflate-imaya x 30.35 ops/sec ±0.92% (53 runs sampled)
+ ! inflate-pako x 69.89 ops/sec ±1.46% (71 runs sampled)
+   inflate-pako-string x 19.22 ops/sec ±1.86% (49 runs sampled)
+   inflate-pako-untyped x 17.19 ops/sec ±0.85% (32 runs sampled)
+ * inflate-zlib x 70.03 ops/sec ±1.64% (81 runs sampled)
+
+node v0.11.12, 1mb sample:
+
+   deflate-dankogai x 5.60 ops/sec ±0.49% (17 runs sampled)
+   deflate-gildas x 5.06 ops/sec ±6.00% (16 runs sampled)
+   deflate-imaya x 3.52 ops/sec ±3.71% (13 runs sampled)
+ ! deflate-pako x 11.52 ops/sec ±0.22% (32 runs sampled)
+   deflate-pako-string x 9.53 ops/sec ±1.12% (27 runs sampled)
+   deflate-pako-untyped x 5.44 ops/sec ±0.72% (17 runs sampled)
+ * deflate-zlib x 14.05 ops/sec ±3.34% (63 runs sampled)
+   inflate-dankogai x 42.19 ops/sec ±0.09% (56 runs sampled)
+   inflate-imaya x 79.68 ops/sec ±1.07% (68 runs sampled)
+ ! inflate-pako x 97.52 ops/sec ±0.83% (80 runs sampled)
+   inflate-pako-string x 45.19 ops/sec ±1.69% (57 runs sampled)
+   inflate-pako-untyped x 24.35 ops/sec ±2.59% (40 runs sampled)
+ * inflate-zlib x 60.32 ops/sec ±1.36% (69 runs sampled)
+

zlib's test is partialy afferted by marshling (that make sense for inflate only). +You can change deflate level to 0 in benchmark source, to investigate details. +For deflate level 6 results can be considered as correct.

+

Install:

+

node.js:

+
npm install pako
+

browser:

+
bower install pako
+

Example & API

+

Full docs - http://nodeca.github.io/pako/

+
var pako = require('pako');
+
+// Deflate
+//
+var input = new Uint8Array();
+//... fill input data here
+var output = pako.deflate(input);
+
+// Inflate (simple wrapper can throw exception on broken stream)
+//
+var compressed = new Uint8Array();
+//... fill data to uncompress here
+try {
+  var result = pako.inflate(compressed);
+} catch (err) {
+  console.log(err);
+}
+
+//
+// Alternate interface for chunking & without exceptions
+//
+
+var inflator = new pako.Inflate();
+
+inflator.push(chunk1, false);
+inflator.push(chunk2, false);
+...
+inflator.push(chunkN, true); // true -> last chunk
+
+if (inflator.err) {
+  console.log(inflator.msg);
+}
+
+var output = inflator.result;
+

Sometime you can wish to work with strings. For example, to send +big objects as json to server. Pako detects input data type. You can +force output to be string with option { to: 'string' }.

+
var pako = require('pako');
+
+var test = { my: 'super', puper: [456, 567], awesome: 'pako' };
+
+var binaryString = pako.deflate(JSON.stringify(test), { to: 'string' });
+
+//
+// Here you can do base64 encode, make xhr requests and so on.
+//
+
+var restored = JSON.parse(pako.inflate(binaryString, { to: 'string' }));
+

Notes

+

Pako does not contain some specific zlib functions:

+
    +
  • deflate - methods deflateCopy, deflateBound, deflateParams, +deflatePending, deflatePrime, deflateSetDictionary, deflateTune.
  • +
  • inflate - inflateGetDictionary, inflateCopy, inflateMark, +inflatePrime, inflateSetDictionary, inflateSync, inflateSyncPoint, +inflateUndermine.
  • +
+

Authors

+ +

Personal thanks to:

+
    +
  • Vyacheslav Egorov (@mraleph) for his awesome +tutoruals about optimising JS code for v8, IRHydra +tool and his advices.
  • +
  • David Duponchel (@dduponchel) for help with +testing.
  • +
+

License

+

MIT

+
constructor

Deflate.new

    • new Deflate(options)
    • options
      • Object
    • zlib deflate options.

      +

Creates new deflator instance with specified params. Throws exception +on bad params. Supported options:

+
    +
  • level
  • +
  • windowBits
  • +
  • memLevel
  • +
  • strategy
  • +
+

http://zlib.net/manual.html#Advanced +for more information on these.

+

Additional options, for internal needs:

+
    +
  • chunkSize - size of generated data chunks (16K by default)
  • +
  • raw (Boolean) - do raw deflate
  • +
  • gzip (Boolean) - create gzip wrapper
  • +
  • to (String) - if equal to 'string', then result will be "binary string" + (each char code [0..255])
  • +
  • header (Object) - custom header for gzip
      +
    • text (Boolean) - true if compressed data believed to be text
    • +
    • time (Number) - modification time, unix timestamp
    • +
    • os (Number) - operation system code
    • +
    • extra (Array) - array of bytes with extra data (max 65536)
    • +
    • name (String) - file name (binary string)
    • +
    • comment (String) - comment (binary string)
    • +
    • hcrc (Boolean) - true if header crc should be added
    • +
    +
  • +
+
Example:
+
var pako = require('pako')
+  , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
+  , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
+
+var deflate = new pako.Deflate({ level: 3});
+
+deflate.push(chunk1, false);
+deflate.push(chunk2, true);  // true -> last chunk
+
+if (deflate.err) { throw new Error(deflate.err); }
+
+console.log(deflate.result);
+
class property

Deflate.err

    • Deflate.err
      • Number

Error code after deflate finished. 0 (Z_OK) on success. +You will not need it in real life, because deflate errors +are possible only on wrong options or bad onData / onEnd +custom handlers.

+
instance method

Deflate#onData

    • Deflate#onData(chunk)
      • Void
    • chunk
      • Uint8Array
      • Array
      • String
    • ouput data. Type of array depends +on js engine support. When string output requested, each chunk +will be string.

      +

By default, stores data blocks in chunks[] property and glue +those in onEnd. Override this handler, if you need another behaviour.

+
instance method

Deflate#onEnd

    • Deflate#onEnd(status)
      • Void
    • status
      • Number
    • deflate status. 0 (Z_OK) on success, +other if not.

      +

Called once after you tell deflate that the input stream is +complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) +or if an error happened. By default - join collected chunks, +free memory and fill results / err properties.

+
instance method

Deflate#push

    • Deflate#push(data[, mode])
      • Boolean
    • data
      • Uint8Array
      • Array
      • ArrayBuffer
      • String
    • input data. Strings will be +converted to utf8 byte sequence.

      +
    • mode
      • Number
      • Boolean
    • 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. +See constants. Skipped or false means Z_NO_FLUSH, true meansh Z_FINISH.

      +

Sends input data to deflate pipe, generating Deflate#onData calls with +new compressed chunks. Returns true on success. The last data block must have +mode Z_FINISH (or true). That will flush internal pending buffers and call +Deflate#onEnd. For interim explicit flushes (without ending the stream) you +can use mode Z_SYNC_FLUSH, keeping the compression context.

+

On fail call Deflate#onEnd with error code and return false.

+

We strongly recommend to use Uint8Array on input for best speed (output +array format is detected automatically). Also, don't skip last param and always +use the same type in your code (boolean or number). That will improve JS speed.

+

For regular Array-s make sure all elements are [0..255].

+
Example
+
push(chunk, false); // push one of data chunks
+...
+push(chunk, true);  // push last chunk
+
method

deflate

    • deflate(data[, options])
      • Uint8Array
      • Array
      • String
    • data
      • Uint8Array
      • Array
      • String
    • input data to compress.

      +
    • options
      • Object
    • zlib deflate options.

      +

Compress data with deflate alrorythm and options.

+

Supported options are:

+
    +
  • level
  • +
  • windowBits
  • +
  • memLevel
  • +
  • strategy
  • +
+

http://zlib.net/manual.html#Advanced +for more information on these.

+

Sugar (options):

+
    +
  • raw (Boolean) - say that we work with raw stream, if you don't wish to specify +negative windowBits implicitly.
  • +
  • to (String) - if equal to 'string', then result will be "binary string" + (each char code [0..255])
  • +
+
Example:
+
var pako = require('pako')
+  , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
+
+console.log(pako.deflate(data));
+
method

deflateRaw

    • deflateRaw(data[, options])
      • Uint8Array
      • Array
      • String
    • data
      • Uint8Array
      • Array
      • String
    • input data to compress.

      +
    • options
      • Object
    • zlib deflate options.

      +

The same as deflate, but creates raw data, without wrapper +(header and adler32 crc).

+
method

gzip

    • gzip(data[, options])
      • Uint8Array
      • Array
      • String
    • data
      • Uint8Array
      • Array
      • String
    • input data to compress.

      +
    • options
      • Object
    • zlib deflate options.

      +

The same as deflate, but create gzip wrapper instead of +deflate one.

+
constructor

Inflate.new

    • new Inflate(options)
    • options
      • Object
    • zlib inflate options.

      +

Creates new inflator instance with specified params. Throws exception +on bad params. Supported options:

+
    +
  • windowBits
  • +
+

http://zlib.net/manual.html#Advanced +for more information on these.

+

Additional options, for internal needs:

+
    +
  • chunkSize - size of generated data chunks (16K by default)
  • +
  • raw (Boolean) - do raw inflate
  • +
  • to (String) - if equal to 'string', then result will be converted +from utf8 to utf16 (javascript) string. When string output requested, +chunk length can differ from chunkSize, depending on content.
  • +
+

By default, when no options set, autodetect deflate/gzip data format via +wrapper header.

+
Example:
+
var pako = require('pako')
+  , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
+  , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
+
+var inflate = new pako.Inflate({ level: 3});
+
+inflate.push(chunk1, false);
+inflate.push(chunk2, true);  // true -> last chunk
+
+if (inflate.err) { throw new Error(inflate.err); }
+
+console.log(inflate.result);
+
class property

Inflate.err

    • Inflate.err
      • Number

Error code after inflate finished. 0 (Z_OK) on success. +Should be checked if broken data possible.

+
instance method

Inflate#onData

    • Inflate#onData(chunk)
      • Void
    • chunk
      • Uint8Array
      • Array
      • String
    • ouput data. Type of array depends +on js engine support. When string output requested, each chunk +will be string.

      +

By default, stores data blocks in chunks[] property and glue +those in onEnd. Override this handler, if you need another behaviour.

+
instance method

Inflate#onEnd

    • Inflate#onEnd(status)
      • Void
    • status
      • Number
    • inflate status. 0 (Z_OK) on success, +other if not.

      +

Called either after you tell inflate that the input stream is +complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) +or if an error happened. By default - join collected chunks, +free memory and fill results / err properties.

+
instance method

Inflate#push

    • Inflate#push(data[, mode])
      • Boolean
    • data
      • Uint8Array
      • Array
      • ArrayBuffer
      • String
    • input data

      +
    • mode
      • Number
      • Boolean
    • 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. +See constants. Skipped or false means Z_NO_FLUSH, true meansh Z_FINISH.

      +

Sends input data to inflate pipe, generating Inflate#onData calls with +new output chunks. Returns true on success. The last data block must have +mode Z_FINISH (or true). That will flush internal pending buffers and call +Inflate#onEnd. For interim explicit flushes (without ending the stream) you +can use mode Z_SYNC_FLUSH, keeping the decompression context.

+

On fail call Inflate#onEnd with error code and return false.

+

We strongly recommend to use Uint8Array on input for best speed (output +format is detected automatically). Also, don't skip last param and always +use the same type in your code (boolean or number). That will improve JS speed.

+

For regular Array-s make sure all elements are [0..255].

+
Example
+
push(chunk, false); // push one of data chunks
+...
+push(chunk, true);  // push last chunk
+
method

inflate

    • inflate(data[, options])
      • Uint8Array
      • Array
      • String
    • data
      • Uint8Array
      • Array
      • String
    • input data to decompress.

      +
    • options
      • Object
    • zlib inflate options.

      +

Decompress data with inflate/ungzip and options. Autodetect +format via wrapper header by default. That's why we don't provide +separate ungzip method.

+

Supported options are:

+
    +
  • windowBits
  • +
+

http://zlib.net/manual.html#Advanced +for more information.

+

Sugar (options):

+
    +
  • raw (Boolean) - say that we work with raw stream, if you don't wish to specify +negative windowBits implicitly.
  • +
  • to (String) - if equal to 'string', then result will be converted +from utf8 to utf16 (javascript) string. When string output requested, +chunk length can differ from chunkSize, depending on content.
  • +
+
Example:
+
var pako = require('pako')
+  , input = pako.deflate([1,2,3,4,5,6,7,8,9])
+  , output;
+
+try {
+  output = pako.inflate(input);
+} catch (err)
+  console.log(err);
+}
+
method

inflateRaw

    • inflateRaw(data[, options])
      • Uint8Array
      • Array
      • String
    • data
      • Uint8Array
      • Array
      • String
    • input data to decompress.

      +
    • options
      • Object
    • zlib inflate options.

      +

The same as inflate, but creates raw data, without wrapper +(header and adler32 crc).

+
method

ungzip

    • ungzip(data[, options])
      • Uint8Array
      • Array
      • String
    • data
      • Uint8Array
      • Array
      • String
    • input data to decompress.

      +
    • options
      • Object
    • zlib inflate options.

      +

Just shortcut to inflate, because it autodetects format +by header.content. Done for convenience.

+

Last updated on Mon, 14 Sep 2015 12:20:55 GMT. Generated by ndoc

\ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/index.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/index.js new file mode 100644 index 0000000..cd07251 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/index.js @@ -0,0 +1,14 @@ +// Top level file is just a mixin of submodules & constants +'use strict'; + +var assign = require('./lib/utils/common').assign; + +var deflate = require('./lib/deflate'); +var inflate = require('./lib/inflate'); +var constants = require('./lib/zlib/constants'); + +var pako = {}; + +assign(pako, deflate, inflate, constants); + +module.exports = pako; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/deflate.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/deflate.js new file mode 100644 index 0000000..6768561 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/deflate.js @@ -0,0 +1,376 @@ +'use strict'; + + +var zlib_deflate = require('./zlib/deflate.js'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var msg = require('./zlib/messages'); +var zstream = require('./zlib/zstream'); + +var toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH = 0; +var Z_FINISH = 4; + +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_SYNC_FLUSH = 2; + +var Z_DEFAULT_COMPRESSION = -1; + +var Z_DEFAULT_STRATEGY = 0; + +var Z_DEFLATED = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overriden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +var Deflate = function(options) { + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } +}; + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): ouput data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function(status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate alrorythm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/inflate.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/inflate.js new file mode 100644 index 0000000..d863f8f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/inflate.js @@ -0,0 +1,400 @@ +'use strict'; + + +var zlib_inflate = require('./zlib/inflate.js'); +var utils = require('./utils/common'); +var strings = require('./utils/strings'); +var c = require('./zlib/constants'); +var msg = require('./zlib/messages'); +var zstream = require('./zlib/zstream'); +var gzheader = require('./zlib/gzheader'); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overriden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +var Inflate = function(options) { + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new gzheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); +}; + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): ouput data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function(status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 alligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/utils/common.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/utils/common.js new file mode 100644 index 0000000..67aaba1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/utils/common.js @@ -0,0 +1,102 @@ +'use strict'; + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (source.hasOwnProperty(p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs+len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i=0; i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254]=_utf8len[254]=1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { + c2 = str.charCodeAt(m_pos+1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i=0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { + c2 = str.charCodeAt(m_pos+1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // use fallback for big arrays to avoid stack overflow + if (len < 65537) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i=0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i=0, len=buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len*2); + + for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function(buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max-1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Fuckup - very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means vuffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/adler32.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/adler32.js new file mode 100644 index 0000000..dcefe93 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/adler32.js @@ -0,0 +1,32 @@ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It doesn't worth to make additional optimizationa as in original. +// Small size is preferable. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/constants.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/constants.js new file mode 100644 index 0000000..f32af66 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/constants.js @@ -0,0 +1,47 @@ +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/crc32.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/crc32.js new file mode 100644 index 0000000..767aa80 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/crc32.js @@ -0,0 +1,41 @@ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n =0; n < 256; n++) { + c = n; + for (var k =0; k < 8; k++) { + c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc = crc ^ (-1); + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/deflate.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/deflate.js new file mode 100644 index 0000000..ff0bb06 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/deflate.js @@ -0,0 +1,1765 @@ +'use strict'; + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2*L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only (s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH-1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length-1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH-1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +var Config = function (good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +}; + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); + this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS+1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + s.d_buf = s.lit_bufsize >> 1; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state + */ +//function deflateCopy(dest, source) { +// +//} + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/gzheader.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/gzheader.js new file mode 100644 index 0000000..300bdee --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/gzheader.js @@ -0,0 +1,40 @@ +'use strict'; + + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inffast.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inffast.js new file mode 100644 index 0000000..a419f65 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inffast.js @@ -0,0 +1,326 @@ +'use strict'; + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inflate.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inflate.js new file mode 100644 index 0000000..a92af63 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inflate.js @@ -0,0 +1,1503 @@ +'use strict'; + + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function ZSWAP32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window,src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window,src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more conveniend processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = ZSWAP32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = {bits: state.lenbits}; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = {bits: state.lenbits}; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = {bits: state.distbits}; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' insdead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too + if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inftrees.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inftrees.js new file mode 100644 index 0000000..1852df2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/inftrees.js @@ -0,0 +1,327 @@ +'use strict'; + + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + var i=0; + /* process all codes and make table entries */ + for (;;) { + i++; + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/messages.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/messages.js new file mode 100644 index 0000000..75bd583 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/messages.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = { + '2': 'need dictionary', /* Z_NEED_DICT 2 */ + '1': 'stream end', /* Z_STREAM_END 1 */ + '0': '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/trees.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/trees.js new file mode 100644 index 0000000..a2a5f66 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/trees.js @@ -0,0 +1,1199 @@ +'use strict'; + + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2*L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES+2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +}; + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +var TreeDesc = function(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +}; + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short (s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max+1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n*2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n-base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m*2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; + tree[m*2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n*2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n*2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n*2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n*2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n*2 + 1]/*.Len*/ = 5; + static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n*2; + var _m2 = m*2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n*2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node*2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n+1)*2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6*2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10*2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138*2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n+1)*2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count-11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3*(max_blindex+1) + 5+5+4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len+3+7) >>> 3; + static_lenb = (s.static_len+3+7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc*2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defailts, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/zstream.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/zstream.js new file mode 100644 index 0000000..2d93a39 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/lib/zlib/zstream.js @@ -0,0 +1,29 @@ +'use strict'; + + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/package.json b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/package.json new file mode 100644 index 0000000..1a9d606 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/node_modules/pako/package.json @@ -0,0 +1,57 @@ +{ + "name": "pako", + "description": "zlib port to javascript - fast, modularized, with browser support", + "version": "0.2.8", + "keywords": [ + "zlib", + "deflate", + "inflate", + "gzip" + ], + "homepage": "https://github.com/nodeca/pako", + "contributors": [ + { + "name": "Andrei Tuputcyn", + "url": "https://github.com/andr83" + }, + { + "name": "Vitaly Puzrin", + "url": "https://github.com/puzrin" + } + ], + "bugs": { + "url": "https://github.com/nodeca/pako/issues" + }, + "license": { + "type": "MIT", + "url": "https://github.com/nodeca/pako/blob/master/LICENSE" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodeca/pako.git" + }, + "main": "./index.js", + "devDependencies": { + "mocha": "1.21.5", + "benchmark": "*", + "ansi": "*", + "browserify": "*", + "eslint": "0.17.1", + "eslint-plugin-nodeca": "~1.0.3", + "uglify-js": "*", + "istanbul": "*", + "ndoc": "*", + "lodash": "*", + "async": "*", + "grunt": "~0.4.4", + "grunt-cli": "~0.1.13", + "grunt-saucelabs": "~8.6.0", + "grunt-contrib-connect": "~0.9.0" + }, + "readme": "pako - zlib port to javascript, very fast!\n==========================================\n\n[![Build Status](https://travis-ci.org/nodeca/pako.svg?branch=master)](https://travis-ci.org/nodeca/pako)\n[![NPM version](https://img.shields.io/npm/v/pako.svg)](https://www.npmjs.org/package/pako)\n\n__Why pako is cool:__\n\n- Almost as fast in modern JS engines as C implementation (see benchmarks).\n- Works in browsers, you can browserify any separate component.\n- Chunking support for big blobs.\n- Results are binary equal to well known [zlib](http://www.zlib.net/) (now v1.2.8 ported).\n\nThis project was done to understand how fast JS can be and is it necessary to\ndevelop native C modules for CPU-intensive tasks. Enjoy the result!\n\n\n__Famous projects, using pako:__\n\n- [browserify](http://browserify.org/) (via [browserify-zlib](https://github.com/devongovett/browserify-zlib))\n- [JSZip](http://stuk.github.io/jszip/)\n- [mincer](https://github.com/nodeca/mincer)\n- [JS-Git](https://github.com/creationix/js-git) and\n [Tedit](https://chrome.google.com/webstore/detail/tedit-development-environ/ooekdijbnbbjdfjocaiflnjgoohnblgf)\n by [@creatronix](https://github.com/creationix)\n\n\n__Benchmarks:__\n\n```\nnode v0.10.26, 1mb sample:\n\n deflate-dankogai x 4.73 ops/sec ±0.82% (15 runs sampled)\n deflate-gildas x 4.58 ops/sec ±2.33% (15 runs sampled)\n deflate-imaya x 3.22 ops/sec ±3.95% (12 runs sampled)\n ! deflate-pako x 6.99 ops/sec ±0.51% (21 runs sampled)\n deflate-pako-string x 5.89 ops/sec ±0.77% (18 runs sampled)\n deflate-pako-untyped x 4.39 ops/sec ±1.58% (14 runs sampled)\n * deflate-zlib x 14.71 ops/sec ±4.23% (59 runs sampled)\n inflate-dankogai x 32.16 ops/sec ±0.13% (56 runs sampled)\n inflate-imaya x 30.35 ops/sec ±0.92% (53 runs sampled)\n ! inflate-pako x 69.89 ops/sec ±1.46% (71 runs sampled)\n inflate-pako-string x 19.22 ops/sec ±1.86% (49 runs sampled)\n inflate-pako-untyped x 17.19 ops/sec ±0.85% (32 runs sampled)\n * inflate-zlib x 70.03 ops/sec ±1.64% (81 runs sampled)\n\nnode v0.11.12, 1mb sample:\n\n deflate-dankogai x 5.60 ops/sec ±0.49% (17 runs sampled)\n deflate-gildas x 5.06 ops/sec ±6.00% (16 runs sampled)\n deflate-imaya x 3.52 ops/sec ±3.71% (13 runs sampled)\n ! deflate-pako x 11.52 ops/sec ±0.22% (32 runs sampled)\n deflate-pako-string x 9.53 ops/sec ±1.12% (27 runs sampled)\n deflate-pako-untyped x 5.44 ops/sec ±0.72% (17 runs sampled)\n * deflate-zlib x 14.05 ops/sec ±3.34% (63 runs sampled)\n inflate-dankogai x 42.19 ops/sec ±0.09% (56 runs sampled)\n inflate-imaya x 79.68 ops/sec ±1.07% (68 runs sampled)\n ! inflate-pako x 97.52 ops/sec ±0.83% (80 runs sampled)\n inflate-pako-string x 45.19 ops/sec ±1.69% (57 runs sampled)\n inflate-pako-untyped x 24.35 ops/sec ±2.59% (40 runs sampled)\n * inflate-zlib x 60.32 ops/sec ±1.36% (69 runs sampled)\n```\n\nzlib's test is partialy afferted by marshling (that make sense for inflate only).\nYou can change deflate level to 0 in benchmark source, to investigate details.\nFor deflate level 6 results can be considered as correct.\n\n__Install:__\n\nnode.js:\n\n```\nnpm install pako\n```\n\nbrowser:\n\n```\nbower install pako\n```\n\n\nExample & API\n-------------\n\nFull docs - http://nodeca.github.io/pako/\n\n```javascript\nvar pako = require('pako');\n\n// Deflate\n//\nvar input = new Uint8Array();\n//... fill input data here\nvar output = pako.deflate(input);\n\n// Inflate (simple wrapper can throw exception on broken stream)\n//\nvar compressed = new Uint8Array();\n//... fill data to uncompress here\ntry {\n var result = pako.inflate(compressed);\n} catch (err) {\n console.log(err);\n}\n\n//\n// Alternate interface for chunking & without exceptions\n//\n\nvar inflator = new pako.Inflate();\n\ninflator.push(chunk1, false);\ninflator.push(chunk2, false);\n...\ninflator.push(chunkN, true); // true -> last chunk\n\nif (inflator.err) {\n console.log(inflator.msg);\n}\n\nvar output = inflator.result;\n\n```\n\nSometime you can wish to work with strings. For example, to send\nbig objects as json to server. Pako detects input data type. You can\nforce output to be string with option `{ to: 'string' }`.\n\n```javascript\nvar pako = require('pako');\n\nvar test = { my: 'super', puper: [456, 567], awesome: 'pako' };\n\nvar binaryString = pako.deflate(JSON.stringify(test), { to: 'string' });\n\n//\n// Here you can do base64 encode, make xhr requests and so on.\n//\n\nvar restored = JSON.parse(pako.inflate(binaryString, { to: 'string' }));\n```\n\n\nNotes\n-----\n\nPako does not contain some specific zlib functions:\n\n- __deflate__ - methods `deflateCopy`, `deflateBound`, `deflateParams`,\n `deflatePending`, `deflatePrime`, `deflateSetDictionary`, `deflateTune`.\n- __inflate__ - `inflateGetDictionary`, `inflateCopy`, `inflateMark`,\n `inflatePrime`, `inflateSetDictionary`, `inflateSync`, `inflateSyncPoint`,\n `inflateUndermine`.\n\n\nAuthors\n-------\n\n- Andrey Tupitsin [@anrd83](https://github.com/andr83)\n- Vitaly Puzrin [@puzrin](https://github.com/puzrin)\n\nPersonal thanks to:\n\n- Vyacheslav Egorov ([@mraleph](https://github.com/mraleph)) for his awesome\n tutoruals about optimising JS code for v8, [IRHydra](http://mrale.ph/irhydra/)\n tool and his advices.\n- David Duponchel ([@dduponchel](https://github.com/dduponchel)) for help with\n testing.\n\n\nLicense\n-------\n\nMIT\n", + "readmeFilename": "README.md", + "_id": "pako@0.2.8", + "_shasum": "15ad772915362913f20de4a8a164b4aacc6165d6", + "_resolved": "https://registry.npmjs.org/pako/-/pako-0.2.8.tgz", + "_from": "https://registry.npmjs.org/pako/-/pako-0.2.8.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/package.json b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/package.json new file mode 100644 index 0000000..2dcaeec --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/package.json @@ -0,0 +1,55 @@ +{ + "name": "browserify-zlib", + "version": "0.1.4", + "description": "Full zlib module for browserify", + "keywords": [ + "zlib", + "browserify" + ], + "main": "src/index.js", + "directories": { + "test": "test" + }, + "dependencies": { + "pako": "~0.2.0" + }, + "devDependencies": { + "tape": "^2.12.3", + "brfs": "^1.0.1" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "chrome/22..latest", + "firefox/16..latest", + "safari/latest", + "opera/11.0..latest", + "iphone/6", + "ipad/6", + "android-browser/latest" + ] + }, + "scripts": { + "test": "node_modules/tape/bin/tape test/*.js" + }, + "author": { + "name": "Devon Govett", + "email": "devongovett@gmail.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/devongovett/browserify-zlib.git" + }, + "readme": "# browserify-zlib\n\nEmulates Node's [zlib](http://nodejs.org/api/zlib.html) module for [Browserify](http://browserify.org)\nusing [pako](https://github.com/nodeca/pako). It uses the actual Node source code and passes the Node zlib tests\nby emulating the C++ binding that actually calls zlib.\n\n[![browser support](https://ci.testling.com/devongovett/browserify-zlib.png)\n](https://ci.testling.com/devongovett/browserify-zlib)\n\n[![node tests](https://travis-ci.org/devongovett/browserify-zlib.svg)\n](https://travis-ci.org/devongovett/browserify-zlib)\n\n## Not implemented\n\nThe following options/methods are not supported because pako does not support them yet.\n\n* The `params` method\n* The `dictionary` option\n\n## License\n\nMIT\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/devongovett/browserify-zlib/issues" + }, + "homepage": "https://github.com/devongovett/browserify-zlib#readme", + "_id": "browserify-zlib@0.1.4", + "_shasum": "bb35f8a519f600e0fa6b8485241c979d0141fb2d", + "_resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.1.4.tgz", + "_from": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.1.4.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/src/binding.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/src/binding.js new file mode 100644 index 0000000..7244b43 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/src/binding.js @@ -0,0 +1,236 @@ +var msg = require('pako/lib/zlib/messages'); +var zstream = require('pako/lib/zlib/zstream'); +var zlib_deflate = require('pako/lib/zlib/deflate.js'); +var zlib_inflate = require('pako/lib/zlib/inflate.js'); +var constants = require('pako/lib/zlib/constants'); + +for (var key in constants) { + exports[key] = constants[key]; +} + +// zlib modes +exports.NONE = 0; +exports.DEFLATE = 1; +exports.INFLATE = 2; +exports.GZIP = 3; +exports.GUNZIP = 4; +exports.DEFLATERAW = 5; +exports.INFLATERAW = 6; +exports.UNZIP = 7; + +/** + * Emulate Node's zlib C++ layer for use by the JS layer in index.js + */ +function Zlib(mode) { + if (mode < exports.DEFLATE || mode > exports.UNZIP) + throw new TypeError("Bad argument"); + + this.mode = mode; + this.init_done = false; + this.write_in_progress = false; + this.pending_close = false; + this.windowBits = 0; + this.level = 0; + this.memLevel = 0; + this.strategy = 0; + this.dictionary = null; +} + +Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) { + this.windowBits = windowBits; + this.level = level; + this.memLevel = memLevel; + this.strategy = strategy; + // dictionary not supported. + + if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) + this.windowBits += 16; + + if (this.mode === exports.UNZIP) + this.windowBits += 32; + + if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) + this.windowBits = -this.windowBits; + + this.strm = new zstream(); + + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + var status = zlib_deflate.deflateInit2( + this.strm, + this.level, + exports.Z_DEFLATED, + this.windowBits, + this.memLevel, + this.strategy + ); + break; + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + case exports.UNZIP: + var status = zlib_inflate.inflateInit2( + this.strm, + this.windowBits + ); + break; + default: + throw new Error("Unknown mode " + this.mode); + } + + if (status !== exports.Z_OK) { + this._error(status); + return; + } + + this.write_in_progress = false; + this.init_done = true; +}; + +Zlib.prototype.params = function() { + throw new Error("deflateParams Not supported"); +}; + +Zlib.prototype._writeCheck = function() { + if (!this.init_done) + throw new Error("write before init"); + + if (this.mode === exports.NONE) + throw new Error("already finalized"); + + if (this.write_in_progress) + throw new Error("write already in progress"); + + if (this.pending_close) + throw new Error("close is pending"); +}; + +Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) { + this._writeCheck(); + this.write_in_progress = true; + + var self = this; + process.nextTick(function() { + self.write_in_progress = false; + var res = self._write(flush, input, in_off, in_len, out, out_off, out_len); + self.callback(res[0], res[1]); + + if (self.pending_close) + self.close(); + }); + + return this; +}; + +// set method for Node buffers, used by pako +function bufferSet(data, offset) { + for (var i = 0; i < data.length; i++) { + this[offset + i] = data[i]; + } +} + +Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) { + this._writeCheck(); + return this._write(flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) { + this.write_in_progress = true; + + if (flush !== exports.Z_NO_FLUSH && + flush !== exports.Z_PARTIAL_FLUSH && + flush !== exports.Z_SYNC_FLUSH && + flush !== exports.Z_FULL_FLUSH && + flush !== exports.Z_FINISH && + flush !== exports.Z_BLOCK) { + throw new Error("Invalid flush value"); + } + + if (input == null) { + input = new Buffer(0); + in_len = 0; + in_off = 0; + } + + if (out._set) + out.set = out._set; + else + out.set = bufferSet; + + var strm = this.strm; + strm.avail_in = in_len; + strm.input = input; + strm.next_in = in_off; + strm.avail_out = out_len; + strm.output = out; + strm.next_out = out_off; + + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + var status = zlib_deflate.deflate(strm, flush); + break; + case exports.UNZIP: + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + var status = zlib_inflate.inflate(strm, flush); + break; + default: + throw new Error("Unknown mode " + this.mode); + } + + if (status !== exports.Z_STREAM_END && status !== exports.Z_OK) { + this._error(status); + } + + this.write_in_progress = false; + return [strm.avail_in, strm.avail_out]; +}; + +Zlib.prototype.close = function() { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + + this.pending_close = false; + + if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { + zlib_deflate.deflateEnd(this.strm); + } else { + zlib_inflate.inflateEnd(this.strm); + } + + this.mode = exports.NONE; +}; + +Zlib.prototype.reset = function() { + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + var status = zlib_deflate.deflateReset(this.strm); + break; + case exports.INFLATE: + case exports.INFLATERAW: + var status = zlib_inflate.inflateReset(this.strm); + break; + } + + if (status !== exports.Z_OK) { + this._error(status); + } +}; + +Zlib.prototype._error = function(status) { + this.onerror(msg[status] + ': ' + this.strm.msg, status); + + this.write_in_progress = false; + if (this.pending_close) + this.close(); +}; + +exports.Zlib = Zlib; diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/src/index.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/src/index.js new file mode 100644 index 0000000..032689c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/src/index.js @@ -0,0 +1,610 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Transform = require('_stream_transform'); + +var binding = require('./binding'); +var util = require('util'); +var assert = require('assert').ok; + +// zlib doesn't provide these, so kludge them in following the same +// const naming scheme zlib uses. +binding.Z_MIN_WINDOWBITS = 8; +binding.Z_MAX_WINDOWBITS = 15; +binding.Z_DEFAULT_WINDOWBITS = 15; + +// fewer than 64 bytes per chunk is stupid. +// technically it could work with as few as 8, but even 64 bytes +// is absurdly low. Usually a MB or more is best. +binding.Z_MIN_CHUNK = 64; +binding.Z_MAX_CHUNK = Infinity; +binding.Z_DEFAULT_CHUNK = (16 * 1024); + +binding.Z_MIN_MEMLEVEL = 1; +binding.Z_MAX_MEMLEVEL = 9; +binding.Z_DEFAULT_MEMLEVEL = 8; + +binding.Z_MIN_LEVEL = -1; +binding.Z_MAX_LEVEL = 9; +binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; + +// expose all the zlib constants +Object.keys(binding).forEach(function(k) { + if (k.match(/^Z/)) exports[k] = binding[k]; +}); + +// translation table for return codes. +exports.codes = { + Z_OK: binding.Z_OK, + Z_STREAM_END: binding.Z_STREAM_END, + Z_NEED_DICT: binding.Z_NEED_DICT, + Z_ERRNO: binding.Z_ERRNO, + Z_STREAM_ERROR: binding.Z_STREAM_ERROR, + Z_DATA_ERROR: binding.Z_DATA_ERROR, + Z_MEM_ERROR: binding.Z_MEM_ERROR, + Z_BUF_ERROR: binding.Z_BUF_ERROR, + Z_VERSION_ERROR: binding.Z_VERSION_ERROR +}; + +Object.keys(exports.codes).forEach(function(k) { + exports.codes[exports.codes[k]] = k; +}); + +exports.Deflate = Deflate; +exports.Inflate = Inflate; +exports.Gzip = Gzip; +exports.Gunzip = Gunzip; +exports.DeflateRaw = DeflateRaw; +exports.InflateRaw = InflateRaw; +exports.Unzip = Unzip; + +exports.createDeflate = function(o) { + return new Deflate(o); +}; + +exports.createInflate = function(o) { + return new Inflate(o); +}; + +exports.createDeflateRaw = function(o) { + return new DeflateRaw(o); +}; + +exports.createInflateRaw = function(o) { + return new InflateRaw(o); +}; + +exports.createGzip = function(o) { + return new Gzip(o); +}; + +exports.createGunzip = function(o) { + return new Gunzip(o); +}; + +exports.createUnzip = function(o) { + return new Unzip(o); +}; + + +// Convenience methods. +// compress/decompress a string or buffer in one step. +exports.deflate = function(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer, callback); +}; + +exports.deflateSync = function(buffer, opts) { + return zlibBufferSync(new Deflate(opts), buffer); +}; + +exports.gzip = function(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer, callback); +}; + +exports.gzipSync = function(buffer, opts) { + return zlibBufferSync(new Gzip(opts), buffer); +}; + +exports.deflateRaw = function(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer, callback); +}; + +exports.deflateRawSync = function(buffer, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer); +}; + +exports.unzip = function(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer, callback); +}; + +exports.unzipSync = function(buffer, opts) { + return zlibBufferSync(new Unzip(opts), buffer); +}; + +exports.inflate = function(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer, callback); +}; + +exports.inflateSync = function(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +}; + +exports.gunzip = function(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer, callback); +}; + +exports.gunzipSync = function(buffer, opts) { + return zlibBufferSync(new Gunzip(opts), buffer); +}; + +exports.inflateRaw = function(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer, callback); +}; + +exports.inflateRawSync = function(buffer, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer); +}; + +function zlibBuffer(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once('readable', flow); + } + + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); + } + + function onEnd() { + var buf = Buffer.concat(buffers, nread); + buffers = []; + callback(null, buf); + engine.close(); + } +} + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') + buffer = new Buffer(buffer); + if (!Buffer.isBuffer(buffer)) + throw new TypeError('Not a string or buffer'); + + var flushFlag = binding.Z_FINISH; + + return engine._processChunk(buffer, flushFlag); +} + +// generic zlib +// minimal 2-byte header +function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib.call(this, opts, binding.DEFLATE); +} + +function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib.call(this, opts, binding.INFLATE); +} + + + +// gzip - bigger header, same deflate compression +function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib.call(this, opts, binding.GZIP); +} + +function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib.call(this, opts, binding.GUNZIP); +} + + + +// raw - no header +function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib.call(this, opts, binding.DEFLATERAW); +} + +function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib.call(this, opts, binding.INFLATERAW); +} + + +// auto-detect header. +function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib.call(this, opts, binding.UNZIP); +} + + +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. + +function Zlib(opts, mode) { + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; + + Transform.call(this, opts); + + if (opts.flush) { + if (opts.flush !== binding.Z_NO_FLUSH && + opts.flush !== binding.Z_PARTIAL_FLUSH && + opts.flush !== binding.Z_SYNC_FLUSH && + opts.flush !== binding.Z_FULL_FLUSH && + opts.flush !== binding.Z_FINISH && + opts.flush !== binding.Z_BLOCK) { + throw new Error('Invalid flush flag: ' + opts.flush); + } + } + this._flushFlag = opts.flush || binding.Z_NO_FLUSH; + + if (opts.chunkSize) { + if (opts.chunkSize < exports.Z_MIN_CHUNK || + opts.chunkSize > exports.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); + } + } + + if (opts.windowBits) { + if (opts.windowBits < exports.Z_MIN_WINDOWBITS || + opts.windowBits > exports.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < exports.Z_MIN_LEVEL || + opts.level > exports.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < exports.Z_MIN_MEMLEVEL || + opts.memLevel > exports.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != exports.Z_FILTERED && + opts.strategy != exports.Z_HUFFMAN_ONLY && + opts.strategy != exports.Z_RLE && + opts.strategy != exports.Z_FIXED && + opts.strategy != exports.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!Buffer.isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._binding = new binding.Zlib(mode); + + var self = this; + this._hadError = false; + this._binding.onerror = function(message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + self._binding = null; + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = exports.codes[errno]; + self.emit('error', error); + }; + + var level = exports.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = exports.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, + level, + opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, + strategy, + opts.dictionary); + + this._buffer = new Buffer(this._chunkSize); + this._offset = 0; + this._closed = false; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); +} + +util.inherits(Zlib, Transform); + +Zlib.prototype.params = function(level, strategy, callback) { + if (level < exports.Z_MIN_LEVEL || + level > exports.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != exports.Z_FILTERED && + strategy != exports.Z_HUFFMAN_ONLY && + strategy != exports.Z_RLE && + strategy != exports.Z_FIXED && + strategy != exports.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding.Z_SYNC_FLUSH, function() { + self._binding.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); + } + }); + } else { + process.nextTick(callback); + } +}; + +Zlib.prototype.reset = function() { + return this._binding.reset(); +}; + +// This is the _flush function called by the transform class, +// internally, when the last chunk has been written. +Zlib.prototype._flush = function(callback) { + this._transform(new Buffer(0), '', callback); +}; + +Zlib.prototype.flush = function(kind, callback) { + var ws = this._writableState; + + if (typeof kind === 'function' || (kind === void 0 && !callback)) { + callback = kind; + kind = binding.Z_FULL_FLUSH; + } + + if (ws.ended) { + if (callback) + process.nextTick(callback); + } else if (ws.ending) { + if (callback) + this.once('end', callback); + } else if (ws.needDrain) { + var self = this; + this.once('drain', function() { + self.flush(callback); + }); + } else { + this._flushFlag = kind; + this.write(new Buffer(0), '', callback); + } +}; + +Zlib.prototype.close = function(callback) { + if (callback) + process.nextTick(callback); + + if (this._closed) + return; + + this._closed = true; + + this._binding.close(); + + var self = this; + process.nextTick(function() { + self.emit('close'); + }); +}; + +Zlib.prototype._transform = function(chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (!chunk === null && !Buffer.isBuffer(chunk)) + return cb(new Error('invalid input')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag. + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) + flushFlag = binding.Z_FINISH; + else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; + } + } + + var self = this; + this._processChunk(chunk, flushFlag, cb); +}; + +Zlib.prototype._processChunk = function(chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function(er) { + error = er; + }); + + do { + var res = this._binding.writeSync(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + var buf = Buffer.concat(buffers, nread); + this.close(); + + return buf; + } + + var req = this._binding.write(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + if (self._hadError) + return; + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = new Buffer(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += (availInBefore - availInAfter); + availInBefore = availInAfter; + + if (!async) + return true; + + var newReq = self._binding.write(flushFlag, + chunk, + inOff, + availInBefore, + self._buffer, + self._offset, + self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) + return false; + + // finished with the chunk. + cb(); + } +}; + +util.inherits(Deflate, Zlib); +util.inherits(Inflate, Zlib); +util.inherits(Gzip, Zlib); +util.inherits(Gunzip, Zlib); +util.inherits(DeflateRaw, Zlib); +util.inherits(InflateRaw, Zlib); +util.inherits(Unzip, Zlib); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/elipses.txt b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/elipses.txt new file mode 100644 index 0000000..6105600 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/elipses.txt @@ -0,0 +1 @@ +………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………… \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/empty.txt b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/empty.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/empty.txt @@ -0,0 +1 @@ + diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/person.jpg b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/person.jpg new file mode 100644 index 0000000..4f71881 Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/fixtures/person.jpg differ diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary-fail.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary-fail.js new file mode 100644 index 0000000..fd35a01 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary-fail.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); + +// Should raise an error, not trigger an assertion in src/node_zlib.cc +(function() { + var stream = zlib.createInflate(); + + stream.on('error', common.mustCall(function(err) { + assert(/Missing dictionary/.test(err.message)); + })); + + // String "test" encoded with dictionary "dict". + stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5])); +})(); + +// Should raise an error, not trigger an assertion in src/node_zlib.cc +(function() { + var stream = zlib.createInflate({ dictionary: Buffer('fail') }); + + stream.on('error', common.mustCall(function(err) { + assert(/Bad dictionary/.test(err.message)); + })); + + // String "test" encoded with dictionary "dict". + stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5])); +})(); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary.js new file mode 100644 index 0000000..58da810 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary.js @@ -0,0 +1,95 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test compression/decompression with dictionary + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); + +var spdyDict = new Buffer([ + 'optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-', + 'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi', + 'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser', + '-agent10010120020120220320420520630030130230330430530630740040140240340440', + '5406407408409410411412413414415416417500501502503504505accept-rangesageeta', + 'glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic', + 'ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran', + 'sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati', + 'oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo', + 'ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe', + 'pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic', + 'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1', + '.1statusversionurl\0' +].join('')); + +var deflate = zlib.createDeflate({ dictionary: spdyDict }); + +var input = [ + 'HTTP/1.1 200 Ok', + 'Server: node.js', + 'Content-Length: 0', + '' +].join('\r\n'); + +var called = 0; + +// +// We'll use clean-new inflate stream each time +// and .reset() old dirty deflate one +// +function run(num) { + var inflate = zlib.createInflate({ dictionary: spdyDict }); + + if (num === 2) { + deflate.reset(); + deflate.removeAllListeners('data'); + } + + // Put data into deflate stream + deflate.on('data', function(chunk) { + inflate.write(chunk); + }); + + // Get data from inflate stream + var output = []; + inflate.on('data', function(chunk) { + output.push(chunk); + }); + inflate.on('end', function() { + called++; + + assert.equal(output.join(''), input); + + if (num < 2) run(num + 1); + }); + + deflate.write(input); + deflate.flush(function() { + inflate.end(); + }); +} +run(1); + +process.on('exit', function() { + assert.equal(called, 2); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-params.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-params.js new file mode 100644 index 0000000..006f1ea --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/ignored/test-zlib-params.js @@ -0,0 +1,33 @@ +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); +var fs = require('fs'); + +var file = fs.readFileSync(path.resolve(common.fixturesDir, 'person.jpg')), + chunkSize = 24 * 1024, + opts = { level: 9, strategy: zlib.Z_DEFAULT_STRATEGY }, + deflater = zlib.createDeflate(opts); + +var chunk1 = file.slice(0, chunkSize), + chunk2 = file.slice(chunkSize), + blkhdr = new Buffer([0x00, 0x48, 0x82, 0xb7, 0x7d]), + expected = Buffer.concat([blkhdr, chunk2]), + actual; + +deflater.write(chunk1, function() { + deflater.params(0, zlib.Z_DEFAULT_STRATEGY, function() { + while (deflater.read()); + deflater.end(chunk2, function() { + var bufs = [], buf; + while (buf = deflater.read()) + bufs.push(buf); + actual = Buffer.concat(bufs); + }); + }); + while (deflater.read()); +}); + +process.once('exit', function() { + assert.deepEqual(actual, expected); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/package.json b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/package.json new file mode 100644 index 0000000..189e120 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/package.json @@ -0,0 +1,7 @@ +{ + "browserify": { + "transform": [ + "brfs" + ] + } +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-close-after-write.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-close-after-write.js new file mode 100644 index 0000000..6d5a083 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-close-after-write.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var tape = require('tape'); +var zlib = require('../'); + +tape(function(t) { + t.plan(1); + + zlib.gzip('hello', function(err, out) { + var unzip = zlib.createGunzip(); + unzip.write(out); + unzip.close(function() { + t.ok(true); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-convenience-methods.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-convenience-methods.js new file mode 100644 index 0000000..223160b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-convenience-methods.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test convenience methods with and without options supplied + +var tape = require('tape'); +var zlib = require('../'); + +var expect = 'blahblahblahblahblahblah'; +var opts = { + level: 9, + chunkSize: 1024, +}; + +[ + ['gzip', 'gunzip'], + ['gzip', 'unzip'], + ['deflate', 'inflate'], + ['deflateRaw', 'inflateRaw'], +].forEach(function(method) { + tape(method.join(' '), function(t) { + t.plan(4); + + zlib[method[0]](expect, opts, function(err, result) { + zlib[method[1]](result, opts, function(err, result) { + t.deepEqual(result, new Buffer(expect), + 'Should get original string after ' + + method[0] + '/' + method[1] + ' with options.'); + }); + }); + + zlib[method[0]](expect, function(err, result) { + zlib[method[1]](result, function(err, result) { + t.deepEqual(result, new Buffer(expect), + 'Should get original string after ' + + method[0] + '/' + method[1] + ' without options.'); + }); + }); + + var result = zlib[method[0] + 'Sync'](expect, opts); + result = zlib[method[1] + 'Sync'](result, opts); + t.deepEqual(result, new Buffer(expect), + 'Should get original string after ' + + method[0] + '/' + method[1] + ' with options.'); + + result = zlib[method[0] + 'Sync'](expect); + result = zlib[method[1] + 'Sync'](result); + t.deepEqual(result, new Buffer(expect), + 'Should get original string after ' + + method[0] + '/' + method[1] + ' without options.'); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-from-string.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-from-string.js new file mode 100644 index 0000000..0376c55 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-from-string.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test compressing and uncompressing a string with zlib + +var tape = require('tape'); +var zlib = require('../'); + +var inputString = '\u03A9\u03A9Lorem ipsum dolor sit amet, consectetur adipiscing el' + + 'it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la' + + 'cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta' + + ' placerat, nisi est fermentum augue, vitae gravida tellus sapien sit ' + + 'amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss' + + 'e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m' + + 'i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar' + + 'cu malesuada fermentum. Nunc sed. '; +var expectedBase64Deflate = 'eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm' + + 'XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3' + + 'Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo' + + 'AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N' + + 'WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq' + + 'qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9'; +var expectedBase64Gzip = 'H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN' + + '496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT' + + 'cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr' + + 'Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G' + + 'OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h' + + 'N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s' + + 'HnHNzRtagj5AQAA'; + +tape('deflate', function(t) { + t.plan(1); + zlib.deflate(inputString, function(err, buffer) { + t.equal(buffer.toString('base64'), expectedBase64Deflate, + 'deflate encoded string should match'); + }); +}); + +tape('gzip', function(t) { + t.plan(1); + zlib.gzip(inputString, function(err, buffer) { + // Can't actually guarantee that we'll get exactly the same + // deflated bytes when we compress a string, since the header + // depends on stuff other than the input string itself. + // However, decrypting it should definitely yield the same + // result that we're expecting, and this should match what we get + // from inflating the known valid deflate data. + zlib.gunzip(buffer, function(err, gunzipped) { + t.equal(gunzipped.toString(), inputString, + 'Should get original string after gzip/gunzip'); + }); + }); +}); + +tape('unzip deflate', function(t) { + t.plan(1); + var buffer = new Buffer(expectedBase64Deflate, 'base64'); + zlib.unzip(buffer, function(err, buffer) { + t.equal(buffer.toString(), inputString, + 'decoded inflated string should match'); + }); +}); + +tape('unzip gzip', function(t) { + t.plan(1); + buffer = new Buffer(expectedBase64Gzip, 'base64'); + zlib.unzip(buffer, function(err, buffer) { + t.equal(buffer.toString(), inputString, + 'decoded gunzipped string should match'); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-invalid-input.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-invalid-input.js new file mode 100644 index 0000000..5ac08c3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-invalid-input.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test uncompressing invalid input + +var tape = require('tape'), + zlib = require('../'); + +tape('non-strings', function(t) { + var nonStringInputs = [1, true, {a: 1}, ['a']]; + t.plan(12); + + nonStringInputs.forEach(function(input) { + // zlib.gunzip should not throw an error when called with bad input. + t.doesNotThrow(function() { + zlib.gunzip(input, function(err, buffer) { + // zlib.gunzip should pass the error to the callback. + t.ok(err); + }); + }); + }); +}); + +tape('unzips', function(t) { + // zlib.Unzip classes need to get valid data, or else they'll throw. + var unzips = [ zlib.Unzip(), + zlib.Gunzip(), + zlib.Inflate(), + zlib.InflateRaw() ]; + + t.plan(4); + unzips.forEach(function (uz, i) { + uz.on('error', function(er) { + t.ok(er); + }); + + uz.on('end', function(er) { + throw new Error('end event should not be emitted '+uz.constructor.name); + }); + + // this will trigger error event + uz.write('this is not valid compressed data.'); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-random-byte-pipes.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-random-byte-pipes.js new file mode 100644 index 0000000..6dba4c2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-random-byte-pipes.js @@ -0,0 +1,176 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var crypto = require('crypto'); +var stream = require('stream'); +var Stream = stream.Stream; +var util = require('util'); +var tape = require('tape'); +var zlib = require('../'); + + + +// emit random bytes, and keep a shasum +function RandomReadStream(opt) { + Stream.call(this); + + this.readable = true; + this._paused = false; + this._processing = false; + + this._hasher = crypto.createHash('sha1'); + opt = opt || {}; + + // base block size. + opt.block = opt.block || 256 * 1024; + + // total number of bytes to emit + opt.total = opt.total || 256 * 1024 * 1024; + this._remaining = opt.total; + + // how variable to make the block sizes + opt.jitter = opt.jitter || 1024; + + this._opt = opt; + + this._process = this._process.bind(this); + + process.nextTick(this._process); +} + +util.inherits(RandomReadStream, Stream); + +RandomReadStream.prototype.pause = function() { + this._paused = true; + this.emit('pause'); +}; + +RandomReadStream.prototype.resume = function() { + this._paused = false; + this.emit('resume'); + this._process(); +}; + +RandomReadStream.prototype._process = function() { + if (this._processing) return; + if (this._paused) return; + + this._processing = true; + + if (!this._remaining) { + this._hash = this._hasher.digest('hex').toLowerCase().trim(); + this._processing = false; + + this.emit('end'); + return; + } + + // figure out how many bytes to output + // if finished, then just emit end. + var block = this._opt.block; + var jitter = this._opt.jitter; + if (jitter) { + block += Math.ceil(Math.random() * jitter - (jitter / 2)); + } + block = Math.min(block, this._remaining); + var buf = new Buffer(block); + for (var i = 0; i < block; i++) { + buf[i] = Math.random() * 256; + } + + this._hasher.update(buf); + + this._remaining -= block; + + this._processing = false; + + this.emit('data', buf); + process.nextTick(this._process); +}; + + +// a filter that just verifies a shasum +function HashStream() { + Stream.call(this); + + this.readable = this.writable = true; + this._hasher = crypto.createHash('sha1'); +} + +util.inherits(HashStream, Stream); + +HashStream.prototype.write = function(c) { + // Simulate the way that an fs.ReadStream returns false + // on *every* write like a jerk, only to resume a + // moment later. + this._hasher.update(c); + process.nextTick(this.resume.bind(this)); + return false; +}; + +HashStream.prototype.resume = function() { + this.emit('resume'); + process.nextTick(this.emit.bind(this, 'drain')); +}; + +HashStream.prototype.end = function(c) { + if (c) { + this.write(c); + } + this._hash = this._hasher.digest('hex').toLowerCase().trim(); + this.emit('data', this._hash); + this.emit('end'); +}; + +tape('random byte pipes', function(t) { + var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 }); + var out = new HashStream(); + var gzip = zlib.createGzip(); + var gunz = zlib.createGunzip(); + + inp.pipe(gzip).pipe(gunz).pipe(out); + + inp.on('data', function(c) { + t.ok(c.length); + }); + + gzip.on('data', function(c) { + t.ok(c.length); + }); + + gunz.on('data', function(c) { + t.ok(c.length); + }); + + out.on('data', function(c) { + t.ok(c.length); + }); + + out.on('data', function(c) { + t.ok(c.length); + t.equal(c, inp._hash, 'hashes should match'); + }); + + out.on('end', function() { + t.end(); + }) +}); + diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-write-after-flush.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-write-after-flush.js new file mode 100644 index 0000000..5841ef8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-write-after-flush.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var tape = require('tape'); +var zlib = require('../'); +var fs = require('fs'); + +tape('write after flush', function(t) { + t.plan(2); + + var gzip = zlib.createGzip(); + var gunz = zlib.createUnzip(); + + gzip.pipe(gunz); + + var output = ''; + var input = 'A line of data\n'; + gunz.setEncoding('utf8'); + gunz.on('data', function(c) { + output += c; + }); + + gunz.on('end', function() { + t.equal(output, input); + + // Make sure that the flush flag was set back to normal + t.equal(gzip._flushFlag, zlib.Z_NO_FLUSH); + }); + + // make sure that flush/write doesn't trigger an assert failure + gzip.flush(); write(); + function write() { + gzip.write(input); + gzip.end(); + gunz.read(0); + } +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-zero-byte.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-zero-byte.js new file mode 100644 index 0000000..88bdd8c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib-zero-byte.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var tape = require('tape'); +var zlib = require('../'); + +tape('zero byte', function(t) { + t.plan(2); + var gz = zlib.Gzip() + var emptyBuffer = new Buffer(0); + var received = 0; + gz.on('data', function(c) { + received += c.length; + }); + gz.on('end', function() { + t.equal(received, 20); + }); + gz.on('finish', function() { + t.ok(true); + }); + gz.write(emptyBuffer); + gz.end(); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib.js b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib.js new file mode 100644 index 0000000..64c02c5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/browserify-zlib/test/test-zlib.js @@ -0,0 +1,206 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var zlib = require('../'); +var path = require('path'); + +var zlibPairs = + [[zlib.Deflate, zlib.Inflate], + [zlib.Gzip, zlib.Gunzip], + [zlib.Deflate, zlib.Unzip], + [zlib.Gzip, zlib.Unzip], + [zlib.DeflateRaw, zlib.InflateRaw]]; + +// how fast to trickle through the slowstream +var trickle = [128, 1024, 1024 * 1024]; + +// tunable options for zlib classes. + +// several different chunk sizes +var chunkSize = [128, 1024, 1024 * 16, 1024 * 1024]; + +// this is every possible value. +var level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; +var windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; +var memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; +var strategy = [0, 1, 2, 3, 4]; + +// it's nice in theory to test every combination, but it +// takes WAY too long. Maybe a pummel test could do this? +if (!process.env.PUMMEL) { + trickle = [1024]; + chunkSize = [1024 * 16]; + level = [6]; + memLevel = [8]; + windowBits = [15]; + strategy = [0]; +} + +var fs = require('fs'); + +if (process.env.FAST) { + zlibPairs = [[zlib.Gzip, zlib.Unzip]]; +} + +var tests = { + 'person.jpg': fs.readFileSync(__dirname + '/fixtures/person.jpg'), + 'elipses.txt': fs.readFileSync(__dirname + '/fixtures/elipses.txt'), + 'empty.txt': fs.readFileSync(__dirname + '/fixtures/empty.txt') +}; + +var util = require('util'); +var stream = require('stream'); + + +// stream that saves everything +function BufferStream() { + this.chunks = []; + this.length = 0; + this.writable = true; + this.readable = true; +} + +util.inherits(BufferStream, stream.Stream); + +BufferStream.prototype.write = function(c) { + this.chunks.push(c); + this.length += c.length; + return true; +}; + +BufferStream.prototype.end = function(c) { + if (c) this.write(c); + // flatten + var buf = new Buffer(this.length); + var i = 0; + this.chunks.forEach(function(c) { + c.copy(buf, i); + i += c.length; + }); + this.emit('data', buf); + this.emit('end'); + return true; +}; + + +function SlowStream(trickle) { + this.trickle = trickle; + this.offset = 0; + this.readable = this.writable = true; +} + +util.inherits(SlowStream, stream.Stream); + +SlowStream.prototype.write = function() { + throw new Error('not implemented, just call ss.end(chunk)'); +}; + +SlowStream.prototype.pause = function() { + this.paused = true; + this.emit('pause'); +}; + +SlowStream.prototype.resume = function() { + var self = this; + if (self.ended) return; + self.emit('resume'); + if (!self.chunk) return; + self.paused = false; + emit(); + function emit() { + if (self.paused) return; + if (self.offset >= self.length) { + self.ended = true; + return self.emit('end'); + } + var end = Math.min(self.offset + self.trickle, self.length); + var c = self.chunk.slice(self.offset, end); + self.offset += c.length; + self.emit('data', c); + process.nextTick(emit); + } +}; + +SlowStream.prototype.end = function(chunk) { + // walk over the chunk in blocks. + var self = this; + self.chunk = chunk; + self.length = chunk.length; + self.resume(); + return self.ended; +}; + + + +// for each of the files, make sure that compressing and +// decompressing results in the same data, for every combination +// of the options set above. +var tape = require('tape'); + +Object.keys(tests).forEach(function(file) { + var test = tests[file]; + chunkSize.forEach(function(chunkSize) { + trickle.forEach(function(trickle) { + windowBits.forEach(function(windowBits) { + level.forEach(function(level) { + memLevel.forEach(function(memLevel) { + strategy.forEach(function(strategy) { + zlibPairs.forEach(function(pair) { + var Def = pair[0]; + var Inf = pair[1]; + var opts = { + level: level, + windowBits: windowBits, + memLevel: memLevel, + strategy: strategy + }; + + var msg = file + ' ' + + chunkSize + ' ' + + JSON.stringify(opts) + ' ' + + Def.name + ' -> ' + Inf.name; + + tape('zlib ' + msg, function(t) { + t.plan(1); + + var def = new Def(opts); + var inf = new Inf(opts); + var ss = new SlowStream(trickle); + var buf = new BufferStream(); + + // verify that the same exact buffer comes out the other end. + buf.on('data', function(c) { + t.deepEqual(c, test); + }); + + // the magic happens here. + ss.pipe(def).pipe(inf).pipe(buf); + ss.end(test); + }); + }); + }); + }); + }); + }); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/.npmignore b/node_modules/meteor-node-stubs/node_modules/buffer/.npmignore new file mode 100644 index 0000000..4cea182 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/.npmignore @@ -0,0 +1 @@ +perf/ diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/.travis.yml b/node_modules/meteor-node-stubs/node_modules/buffer/.travis.yml new file mode 100644 index 0000000..6789094 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: +- 'node' +sudo: false +env: + global: + - secure: AUsK+8fYSpwIMHcVt8Mu9SpG9RPHp4XDAwCQfpU3d5U65q8OVVC6C+XjvnNmEd2PoEJRHem8ZXEyRVfGM1sttKZLZP70TEKZOpOiRQnZiTQCAJ92TfGsDj/F4LoWSjUZUpfeg9b3iSp8G5dVw3+q9QZPIu6eykASK6bfcg//Cyg= + - secure: eQBKJWu7XbhAN4ZvOOhMenC0IPpoYj+wZVVzzsLwUppfJqlrHV0CUW8rJdvZNiaGhYhoyHTnAcynpTE5kZfg3XjevOvF8PGY5wUYCki9BI+rp+pvVPZE/DNUAQpFR2gd2nxMJ4kYv7GVb6i/DfuqJa0h8IuY4zcMuKWwbQd3Az8= diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/buffer/.zuul.yml new file mode 100644 index 0000000..707d7e1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/.zuul.yml @@ -0,0 +1,18 @@ +ui: tape +scripts: + - ./test/_polyfill.js +browsers: + - name: chrome + version: '-2..latest' + - name: firefox + version: '-2..latest' + - name: safari + version: latest + - name: ie + version: 8..latest + - name: microsoftedge + version: 13..latest + - name: android + version: 4.4..latest + - name: iphone + version: latest diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/LICENSE b/node_modules/meteor-node-stubs/node_modules/buffer/LICENSE new file mode 100644 index 0000000..d6bf75d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, and other contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/README.md b/node_modules/meteor-node-stubs/node_modules/buffer/README.md new file mode 100644 index 0000000..394fd75 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/README.md @@ -0,0 +1,379 @@ +# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url] + +#### The buffer module from [node.js](https://nodejs.org/), for the browser. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[travis-image]: https://img.shields.io/travis/feross/buffer.svg +[travis-url]: https://travis-ci.org/feross/buffer +[npm-image]: https://img.shields.io/npm/v/buffer.svg +[npm-url]: https://npmjs.org/package/buffer +[downloads-image]: https://img.shields.io/npm/dm/buffer.svg +[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg +[saucelabs-url]: https://saucelabs.com/u/buffer + +With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. + +The goal is to provide an API that is 100% identical to +[node's Buffer API](https://nodejs.org/api/buffer.html). Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +## features + +- Manipulate binary data like a boss, in all browsers -- even IE6! +- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) +- Extremely small bundle size (**5.04KB minified + gzipped**, 35.5KB with comments) +- Excellent browser support (IE 6+, Chrome 4+, Firefox 3+, Safari 5.1+, Opera 11+, iOS, etc.) +- Preserves Node API exactly, with one important difference (see below) +- `.slice()` returns instances of the same type (Buffer) +- Square-bracket `buf[4]` notation works, even in old browsers like IE6! +- Does not modify any browser prototypes or put anything on `window` +- Comprehensive test suite (including all buffer tests from node.js core) + + +## install + +To use this module directly (without browserify), install it: + +```bash +npm install buffer +``` + +This module was previously called **native-buffer-browserify**, but please use **buffer** +from now on. + +A standalone bundle is available [here](https://wzrd.in/standalone/buffer), for non-browserify users. + + +## usage + +The module's API is identical to node's `Buffer` API. Read the +[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, +instance methods, and class methods that are supported. + +As mentioned above, `require('buffer')` or use the `Buffer` global with +[browserify](http://browserify.org) and this module will automatically be included +in your bundle. Almost any npm module will work in the browser, even if it assumes that +the node `Buffer` API will be available. + +To depend on this module explicitly (without browserify), require it like this: + +```js +var Buffer = require('buffer/').Buffer // note: the trailing slash is important! +``` + +To require this module explicitly, use `require('buffer/')` which tells the node.js module +lookup algorithm (also used by browserify) to use the **npm module** named `buffer` +instead of the **node.js core** module named `buffer`! + + +## how does it work? + +The Buffer constructor returns instances of `Uint8Array` that have their prototype +changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, +so the returned instances will have all the node `Buffer` methods and the +`Uint8Array` methods. Square bracket notation works as expected -- it returns a +single octet. + +The `Uint8Array` prototype remains unmodified. + + +## one minor difference + +#### In old browsers, `buf.slice()` does not modify parent buffer's memory + +If you only support modern browsers (specifically, those with typed array support), +then this issue does not affect you. If you support super old browsers, then read on. + +In node, the `slice()` method returns a new `Buffer` that shares underlying memory +with the original Buffer. When you modify one buffer, you modify the other. +[Read more.](https://nodejs.org/api/buffer.html#buffer_buf_slice_start_end) + +In browsers with typed array support, this `Buffer` implementation supports this +behavior. In browsers without typed arrays, an alternate buffer implementation is +used that is based on `Object` which has no mechanism to point separate +`Buffer`s to the same underlying slab of memory. + +You can see which browser versions lack typed array support +[here](https://github.com/feross/buffer/blob/master/index.js#L22-L48). + + +## tracking the latest node api + +This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer +API is considered **stable** in the +[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), +so it is unlikely that there will ever be breaking changes. +Nonetheless, when/if the Buffer API changes in node, this module's API will change +accordingly. + +## related packages + +- [`buffer-equals`](https://www.npmjs.com/package/buffer-equals) - Node.js 0.12 buffer.equals() ponyfill +- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - A lite module for reverse-operations on buffers +- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - A simple module for bitwise-xor on buffers +- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package +- [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) - Convert a typed array to a Buffer without a copy + +## performance + +See perf tests in `/perf`. + +`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a +sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will +always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, +which is included to compare against. + +NOTE: Performance has improved since these benchmarks were taken. PR welcoem to update the README. + +### Chrome 38 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | +| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | +| | | | | +| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | +| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | +| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | +| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | +| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | +| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | +| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | +| | | | | +| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | +| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | +| | | | | +| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | +| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | +| | | | | +| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | +| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | +| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | + + +### Firefox 33 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | +| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | +| | | | | +| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | +| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | +| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | +| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | +| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | +| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | +| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | +| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | +| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | +| | | | | +| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | +| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | +| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | + +### Safari 8 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | +| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | +| | | | | +| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | +| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | +| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | +| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | +| | | | | +| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | +| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | +| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | +| | | | | +| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | +| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | +| | | | | +| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | +| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | +| | | | | +| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | +| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | +| | | | | +| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | +| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | +| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | + + +### Node 0.11.14 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | +| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | +| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | +| | | | | +| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | +| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | +| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | +| | | | | +| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | +| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | +| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | +| | | | | +| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | +| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | +| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | +| | | | | +| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | +| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | +| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | +| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | +| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | +| | | | | +| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | +| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | +| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | +| | | | | +| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | +| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | +| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | +| | | | | +| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | +| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | +| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | +| | | | | +| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | +| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | +| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | +| | | | | +| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | +| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | +| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | + +### iojs 1.8.1 + +| Method | Operations | Accuracy | Sampled | Fastest | +|:-------|:-----------|:---------|:--------|:-------:| +| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | +| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | +| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | +| | | | | +| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | +| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | +| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | +| | | | | +| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | +| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | +| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | +| | | | | +| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | +| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | +| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | +| | | | | +| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | +| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | +| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | +| | | | | +| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | +| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | +| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | +| | | | | +| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | +| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | +| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | +| | | | | +| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | +| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | +| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | +| | | | | +| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | +| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | +| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | +| | | | | +| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | +| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | +| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | +| | | | | +| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | +| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | +| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | +| | | | | + +## Testing the project + +First, install the project: + + npm install + +Then, to run tests in Node.js, run: + + npm run test-node + +To test locally in a browser, you can run: + + npm run test-browser-local + +This will print out a URL that you can then open in a browser to run the tests, using [Zuul](https://github.com/defunctzombie/zuul). + +To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: + + npm test + +This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `.zuul.yml` file. + +## JavaScript Standard Style + +This module uses [JavaScript Standard Style](https://github.com/feross/standard). + +[![js-standard-style](https://raw.githubusercontent.com/feross/standard/master/badge.png)](https://github.com/feross/standard) + +To test that the code conforms to the style, `npm install` and run: + + ./node_modules/.bin/standard + +## credit + +This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/bin/download-node-tests.js b/node_modules/meteor-node-stubs/node_modules/buffer/bin/download-node-tests.js new file mode 100644 index 0000000..21c5a40 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/bin/download-node-tests.js @@ -0,0 +1,127 @@ +#!/usr/bin/env node + +var concat = require('concat-stream') +var cp = require('child_process') +var fs = require('fs') +var hyperquest = require('hyperquest') +var path = require('path') +var split = require('split') +var through = require('through2') + +var url = 'https://api.github.com/repos/nodejs/io.js/contents' +var dirs = [ + '/test/parallel', + '/test/pummel' +] + +cp.execSync('rm -rf node/*.js', { cwd: path.join(__dirname, '../test') }) +cp.execSync('rm -rf node-es6/*.js', { cwd: path.join(__dirname, '../test') }) + +var httpOpts = { + headers: { + 'User-Agent': null + // auth if github rate-limits you... + // 'Authorization': 'Basic ' + Buffer('username:password').toString('base64'), + } +} + +dirs.forEach(function (dir) { + var req = hyperquest(url + dir, httpOpts) + req.pipe(concat(function (data) { + if (req.response.statusCode !== 200) { + throw new Error(url + dir + ': ' + data.toString()) + } + downloadBufferTests(dir, JSON.parse(data)) + })) +}) + +function downloadBufferTests (dir, files) { + files.forEach(function (file) { + if (!/test-buffer.*/.test(file.name)) return + + var out + if (file.name === 'test-buffer-iterator.js' || + file.name === 'test-buffer-arraybuffer.js') { + out = path.join(__dirname, '../test/node-es6', file.name) + } else if (file.name === 'test-buffer-fakes.js') { + // These teses only apply to node, where they're calling into C++ and need to + // ensure the prototype can't be faked, or else there will be a segfault. + return + } else { + out = path.join(__dirname, '../test/node', file.name) + } + + console.log(file.download_url) + hyperquest(file.download_url, httpOpts) + .pipe(split()) + .pipe(testfixer(file.name)) + .pipe(fs.createWriteStream(out)) + .on('finish', function () { + console.log('wrote ' + file.name) + }) + }) +} + +function testfixer (filename) { + var firstline = true + + return through(function (line, enc, cb) { + line = line.toString() + + if (firstline) { + // require buffer explicitly + var preamble = 'if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false;\n' + + 'var Buffer = require(\'../../\').Buffer;' + if (/use strict/.test(line)) line += '\n' + preamble + else line + preamble + '\n' + line + firstline = false + } + + // use `var` instead of `const`/`let` + line = line.replace(/(const|let) /g, 'var ') + + // make `require('common')` work + line = line.replace(/(var common = require.*)/g, 'var common = {};') + + // use `Buffer.isBuffer` instead of `instanceof Buffer` + line = line.replace(/buf instanceof Buffer/g, 'Buffer.isBuffer(buf)') + + // require browser buffer + line = line.replace(/(.*)require\('buffer'\)(.*)/g, '$1require(\'../../\')$2') + + // smalloc is only used for kMaxLength + line = line.replace( + /require\('smalloc'\)/g, + '{ kMaxLength: process.env.OBJECT_IMPL ? 0x3fffffff : 0x7fffffff }' + ) + + // comment out console logs + line = line.replace(/(.*console\..*)/g, '// $1') + + // we can't reliably test typed array max-sizes in the browser + if (filename === 'test-buffer-big.js') { + line = line.replace(/(.*new Int8Array.*RangeError.*)/, '// $1') + line = line.replace(/(.*new ArrayBuffer.*RangeError.*)/, '// $1') + line = line.replace(/(.*new Float64Array.*RangeError.*)/, '// $1') + } + + // https://github.com/iojs/io.js/blob/v0.12/test/parallel/test-buffer.js#L38 + // we can't run this because we need to support + // browsers that don't have typed arrays + if (filename === 'test-buffer.js') { + line = line.replace(/b\[0\] = -1;/, 'b[0] = 255;') + } + + // https://github.com/iojs/io.js/blob/v0.12/test/parallel/test-buffer.js#L1138 + // unfortunately we can't run this as it touches + // node streams which do an instanceof check + // and crypto-browserify doesn't work in old + // versions of ie + if (filename === 'test-buffer.js') { + line = line.replace(/^(\s*)(var crypto = require.*)/, '$1// $2') + line = line.replace(/(crypto.createHash.*\))/, '1 /*$1*/') + } + + cb(null, line + '\n') + }) +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/bin/test.js b/node_modules/meteor-node-stubs/node_modules/buffer/bin/test.js new file mode 100644 index 0000000..2fc368b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/bin/test.js @@ -0,0 +1,18 @@ +#!/usr/bin/env node + +var cp = require('child_process') + +var runBrowserTests = !process.env.TRAVIS_PULL_REQUEST || + process.env.TRAVIS_PULL_REQUEST === 'false' + +var node = cp.spawn('npm', ['run', 'test-node'], { stdio: 'inherit' }) +node.on('close', function (code) { + if (code === 0 && runBrowserTests) { + var browser = cp.spawn('npm', ['run', 'test-browser'], { stdio: 'inherit' }) + browser.on('close', function (code) { + process.exit(code) + }) + } else { + process.exit(code) + } +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/index.js b/node_modules/meteor-node-stubs/node_modules/buffer/index.js new file mode 100644 index 0000000..5dae0da --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/index.js @@ -0,0 +1,1456 @@ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 // not used by this implementation + +var rootParent = {} + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.foo = function () { return 42 } + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ +function Buffer (arg) { + if (!(this instanceof Buffer)) { + // Avoid going through an ArgumentsAdaptorTrampoline in the common case. + if (arguments.length > 1) return new Buffer(arg, arguments[1]) + return new Buffer(arg) + } + + if (!Buffer.TYPED_ARRAY_SUPPORT) { + this.length = 0 + this.parent = undefined + } + + // Common case. + if (typeof arg === 'number') { + return fromNumber(this, arg) + } + + // Slightly less common case. + if (typeof arg === 'string') { + return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') + } + + // Unusual. + return fromObject(this, arg) +} + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function fromNumber (that, length) { + that = allocate(that, length < 0 ? 0 : checked(length) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < length; i++) { + that[i] = 0 + } + } + return that +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' + + // Assumption: byteLength() return value is always < kMaxLength. + var length = byteLength(string, encoding) | 0 + that = allocate(that, length) + + that.write(string, encoding) + return that +} + +function fromObject (that, object) { + if (Buffer.isBuffer(object)) return fromBuffer(that, object) + + if (isArray(object)) return fromArray(that, object) + + if (object == null) { + throw new TypeError('must start with number, buffer, array or string') + } + + if (typeof ArrayBuffer !== 'undefined') { + if (object.buffer instanceof ArrayBuffer) { + return fromTypedArray(that, object) + } + if (object instanceof ArrayBuffer) { + return fromArrayBuffer(that, object) + } + } + + if (object.length) return fromArrayLike(that, object) + + return fromJsonObject(that, object) +} + +function fromBuffer (that, buffer) { + var length = checked(buffer.length) | 0 + that = allocate(that, length) + buffer.copy(that, 0, 0, length) + return that +} + +function fromArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +// Duplicate of fromArray() to keep fromArray() monomorphic. +function fromTypedArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + // Truncating the elements is probably not what people expect from typed + // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior + // of the old Buffer constructor. + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(array) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromTypedArray(that, new Uint8Array(array)) + } + return that +} + +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. +// Returns a zero-length buffer for inputs that don't conform to the spec. +function fromJsonObject (that, object) { + var array + var length = 0 + + if (object.type === 'Buffer' && isArray(object.data)) { + array = object.data + length = checked(array.length) | 0 + } + that = allocate(that, length) + + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} else { + // pre-set for values that may exist in the future + Buffer.prototype.length = undefined + Buffer.prototype.parent = undefined +} + +function allocate (that, length) { + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that.length = length + } + + var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 + if (fromPool) that.parent = rootParent + + return that +} + +function checked (length) { + // Note: cannot use `length < kMaxLength` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (subject, encoding) { + if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) + + var buf = new Buffer(subject, encoding) + delete buf.parent + return buf +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + + if (list.length === 0) { + return new Buffer(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; i++) { + length += list[i].length + } + } + + var buf = new Buffer(length) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} + +function byteLength (string, encoding) { + if (typeof string !== 'string') string = '' + string + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'binary': + // Deprecated + case 'raw': + case 'raws': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + start = start | 0 + end = end === undefined || end === Infinity ? this.length : end | 0 + + if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'binary': + return binarySlice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + return Buffer.compare(this, b) +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset) { + if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff + else if (byteOffset < -0x80000000) byteOffset = -0x80000000 + byteOffset >>= 0 + + if (this.length === 0) return -1 + if (byteOffset >= this.length) return -1 + + // Negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + + if (typeof val === 'string') { + if (val.length === 0) return -1 // special case: looking for empty string always fails + return String.prototype.indexOf.call(this, val, byteOffset) + } + if (Buffer.isBuffer(val)) { + return arrayIndexOf(this, val, byteOffset) + } + if (typeof val === 'number') { + if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { + return Uint8Array.prototype.indexOf.call(this, val, byteOffset) + } + return arrayIndexOf(this, [ val ], byteOffset) + } + + function arrayIndexOf (arr, val, byteOffset) { + var foundIndex = -1 + for (var i = 0; byteOffset + i < arr.length; i++) { + if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex + } else { + foundIndex = -1 + } + } + return -1 + } + + throw new TypeError('val must be string, number or Buffer') +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) throw new Error('Invalid hex string') + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + var swap = encoding + encoding = offset + offset = length | 0 + length = swap + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'binary': + return binaryWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function binarySlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + } + + if (newBuf.length) newBuf.parent = this.parent || this + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('index out of range') + if (offset < 0) throw new RangeError('index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; i--) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; i++) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function fill (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length + + if (end < start) throw new RangeError('end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') + if (end < 0 || end > this.length) throw new RangeError('end out of bounds') + + var i + if (typeof value === 'number') { + for (i = start; i < end; i++) { + this[i] = value + } + } else { + var bytes = utf8ToBytes(value.toString()) + var len = bytes.length + for (i = start; i < end; i++) { + this[i] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; i++) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/.npmignore b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/.npmignore new file mode 100644 index 0000000..3bab996 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/.npmignore @@ -0,0 +1 @@ +bench \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/.travis.yml b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/.travis.yml new file mode 100644 index 0000000..db94261 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "node" diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/LICENSE.MIT b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/LICENSE.MIT new file mode 100644 index 0000000..96d3f68 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/LICENSE.MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/README.md b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/README.md new file mode 100644 index 0000000..ed31d1a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/README.md @@ -0,0 +1,31 @@ +base64-js +========= + +`base64-js` does basic base64 encoding/decoding in pure JS. + +[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) + +[![testling badge](https://ci.testling.com/beatgammit/base64-js.png)](https://ci.testling.com/beatgammit/base64-js) + +Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. + +Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. + +## install + +With [npm](https://npmjs.org) do: + +`npm install base64-js` + +## methods + +`var base64 = require('base64-js')` + +`base64` has two exposed functions, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/base64js.min.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/base64js.min.js new file mode 100644 index 0000000..8b04612 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(r){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=r()}else if(typeof define==="function"&&define.amd){define([],r)}else{var e;if(typeof window!=="undefined"){e=window}else if(typeof global!=="undefined"){e=global}else if(typeof self!=="undefined"){e=self}else{e=this}e.base64js=r()}})(function(){var r,e,t;return function n(r,e,t){function o(i,a){if(!e[i]){if(!r[i]){var u=typeof require=="function"&&require;if(!a&&u)return u(i,!0);if(f)return f(i,!0);var d=new Error("Cannot find module '"+i+"'");throw d.code="MODULE_NOT_FOUND",d}var c=e[i]={exports:{}};r[i][0].call(c.exports,function(e){var t=r[i][1][e];return o(t?t:e)},c,c.exports,n,r,e,t)}return e[i].exports}var f=typeof require=="function"&&require;for(var i=0;i0){throw new Error("Invalid string. Length must be a multiple of 4")}a=r[d-2]==="="?2:r[d-1]==="="?1:0;u=new f(d*3/4-a);n=a>0?d-4:d;var c=0;for(e=0,t=0;e>16&255;u[c++]=i>>8&255;u[c++]=i&255}if(a===2){i=o[r.charCodeAt(e)]<<2|o[r.charCodeAt(e+1)]>>4;u[c++]=i&255}else if(a===1){i=o[r.charCodeAt(e)]<<10|o[r.charCodeAt(e+1)]<<4|o[r.charCodeAt(e+2)]>>2;u[c++]=i>>8&255;u[c++]=i&255}return u}function u(r){return n[r>>18&63]+n[r>>12&63]+n[r>>6&63]+n[r&63]}function d(r,e,t){var n;var o=[];for(var f=e;fc?c:u+a))}if(o===1){e=r[t-1];f+=n[e>>2];f+=n[e<<4&63];f+="=="}else if(o===2){e=(r[t-2]<<8)+r[t-1];f+=n[e>>10];f+=n[e>>4&63];f+=n[e<<2&63];f+="="}i.push(f);return i.join("")}},{}]},{},[])("/")}); diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/bower.json b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/bower.json new file mode 100644 index 0000000..addcb15 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/bower.json @@ -0,0 +1,33 @@ +{ + "name": "base64-js", + "version": "1.0.0", + "homepage": "https://github.com/beatgammit/base64-js", + "authors": [ + "T. Jameson Little " + ], + "description": "Base64 encoding/decoding in pure JS", + "main": "lib/b64.js", + "moduleType": [ + "globals", + "node" + ], + "keywords": [ + "base64", + "b64", + "encode", + "decode", + "bytearray", + "typedarray", + "array", + "uint8array" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "bench", + "test", + "tests" + ] +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/lib/b64.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/lib/b64.js new file mode 100644 index 0000000..4b7c478 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/lib/b64.js @@ -0,0 +1,109 @@ +'use strict' + +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +function init () { + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 +} + +init() + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/package.json b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/package.json new file mode 100644 index 0000000..76eae61 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/package.json @@ -0,0 +1,37 @@ +{ + "author": { + "name": "T. Jameson Little", + "email": "t.jameson.little@gmail.com" + }, + "name": "base64-js", + "description": "Base64 encoding/decoding in pure JS", + "version": "1.1.2", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "main": "lib/b64.js", + "scripts": { + "build": "browserify -s base64js -r ./ | uglifyjs -m > base64js.min.js", + "test": "standard && tape test/*.js" + }, + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "benchmark": "^2.1.0", + "browserify": "^13.0.0", + "standard": "^6.0.5", + "tape": "4.x", + "uglify-js": "^2.6.2" + }, + "readme": "base64-js\n=========\n\n`base64-js` does basic base64 encoding/decoding in pure JS.\n\n[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js)\n\n[![testling badge](https://ci.testling.com/beatgammit/base64-js.png)](https://ci.testling.com/beatgammit/base64-js)\n\nMany browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data.\n\nSometimes encoding/decoding binary data in the browser is useful, and that is what this module does.\n\n## install\n\nWith [npm](https://npmjs.org) do:\n\n`npm install base64-js`\n\n## methods\n\n`var base64 = require('base64-js')`\n\n`base64` has two exposed functions, `toByteArray` and `fromByteArray`, which both take a single argument.\n\n* `toByteArray` - Takes a base64 string and returns a byte array\n* `fromByteArray` - Takes a byte array and returns a base64 string\n\n## license\n\nMIT", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "homepage": "https://github.com/beatgammit/base64-js#readme", + "_id": "base64-js@1.1.2", + "_shasum": "d6400cac1c4c660976d90d07a04351d89395f5e8", + "_resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.1.2.tgz", + "_from": "https://registry.npmjs.org/base64-js/-/base64-js-1.1.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/big-data.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/big-data.js new file mode 100644 index 0000000..59ad7f1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/big-data.js @@ -0,0 +1,24 @@ +var test = require('tape') +var b64 = require('../lib/b64') + +test('convert big data to base64', function (t) { + var b64str, arr, i, length + var big = new Uint8Array(64 * 1024 * 1024) + for (i = 0, length = big.length; i < length; ++i) { + big[i] = i % 256 + } + b64str = b64.fromByteArray(big) + arr = b64.toByteArray(b64str) + t.ok(equal(arr, big)) + t.end() +}) + +function equal (a, b) { + var i + var length = a.length + if (length !== b.length) return false + for (i = 0; i < length; ++i) { + if (a[i] !== b[i]) return false + } + return true +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/convert.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/convert.js new file mode 100644 index 0000000..ff275b2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/convert.js @@ -0,0 +1,47 @@ +var test = require('tape') +var b64 = require('../lib/b64') +var checks = [ + 'a', + 'aa', + 'aaa', + 'hi', + 'hi!', + 'hi!!', + 'sup', + 'sup?', + 'sup?!' +] + +test('convert to base64 and back', function (t) { + t.plan(checks.length) + + for (var i = 0; i < checks.length; i++) { + var check = checks[i] + var b64Str, arr, str + + b64Str = b64.fromByteArray(map(check, function (char) { return char.charCodeAt(0) })) + + arr = b64.toByteArray(b64Str) + str = map(arr, function (byte) { return String.fromCharCode(byte) }).join('') + + t.equal(check, str, 'Checked ' + check) + } +}) + +function map (arr, callback) { + var res = [] + var kValue, mappedValue + + for (var k = 0, len = arr.length; k < len; k++) { + if ((typeof arr === 'string' && !!arr.charAt(k))) { + kValue = arr.charAt(k) + mappedValue = callback(kValue, k, arr) + res[k] = mappedValue + } else if (typeof arr !== 'string' && k in arr) { + kValue = arr[k] + mappedValue = callback(kValue, k, arr) + res[k] = mappedValue + } + } + return res +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/url-safe.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/url-safe.js new file mode 100644 index 0000000..38023d4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/base64-js/test/url-safe.js @@ -0,0 +1,18 @@ +var test = require('tape') +var b64 = require('../lib/b64') + +test('decode url-safe style base64 strings', function (t) { + var expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff] + + var actual = b64.toByteArray('//++/++/++//') + for (var i = 0; i < actual.length; i++) { + t.equal(actual[i], expected[i]) + } + + actual = b64.toByteArray('__--_--_--__') + for (i = 0; i < actual.length; i++) { + t.equal(actual[i], expected[i]) + } + + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/.travis.yml b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/.travis.yml new file mode 100644 index 0000000..6236df7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: +- 'iojs' +env: + global: + - secure: f3NrmOV/A7oACn47J1mkIpH8Sn/LINtluZvo/9pGo3Ss4+D2lyt7UawpedHtnYgU9WEyjPSi7pDWopUrIzusQ2trLYRJr8WAOEyHlgaepDyy4BW3ghGMKHMsS05kilYLP8nu1sRd6y1AcUYKw+kUrrSPanI7kViWVQ5d5DuwXO8= + - secure: a6teILh33z5fbGQbh5/EkFfAyXfa2fPJG1upy9K+jLAbG4WZxXD+YmXG9Tz33/2NJm6UplGfTJ8IQEXgxEfAFk3ao3xfKxzm3i64XxtroSlXIFNSiQKogxDfLEtWDoNNCodPHaV3ATEqxGJ5rkkUeU1+ROWW0sjG5JR26k8/Hfg= diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/.zuul.yml new file mode 100644 index 0000000..bfa0cb4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/.zuul.yml @@ -0,0 +1,20 @@ +ui: tape +scripts: + - "./test/_polyfill.js" +browsers: + - name: chrome + version: 39..latest + - name: firefox + version: 34..latest + - name: safari + version: 5..latest + - name: ie + version: 8..latest + - name: opera + version: 11..latest + - name: iphone + version: 4.3..latest + - name: ipad + version: 4.3..latest + - name: android + version: 4.0..latest diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/LICENSE b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/LICENSE new file mode 100644 index 0000000..88a227d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/LICENSE @@ -0,0 +1,56 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +=========================================== +ieee754 originally contained this license: +=========================================== + +Copyright (c) 2008, Fair Oaks Labs, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +Modifications to writeIEEE754 to support negative zeroes made by Brian White. diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/README.md b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/README.md new file mode 100644 index 0000000..2594f04 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/README.md @@ -0,0 +1,47 @@ +# ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url] + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[travis-image]: https://img.shields.io/travis/feross/ieee754.svg?style=flat +[travis-url]: https://travis-ci.org/feross/ieee754 +[npm-image]: https://img.shields.io/npm/v/ieee754.svg?style=flat +[npm-url]: https://npmjs.org/package/ieee754 +[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg?style=flat +[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg +[saucelabs-url]: https://saucelabs.com/u/ieee754 + +### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. + +## install + +``` +npm install ieee754 +``` + +## methods + +`var ieee754 = require('ieee754')` + +The `ieee754` object has the following functions: + +``` +ieee754.read = function (buffer, offset, isLE, mLen, nBytes) +ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) +``` + +The arguments mean the following: + +- buffer = the buffer +- offset = offset into the buffer +- value = value to set (only for `write`) +- isLe = is little endian? +- mLen = mantissa length +- nBytes = number of bytes + +## what is ieee754? + +The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). + +## mit license + +Copyright (C) 2013 [Feross Aboukhadijeh](http://feross.org) & Romain Beauxis. diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/index.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/index.js new file mode 100644 index 0000000..95e190c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/index.js @@ -0,0 +1,84 @@ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/package.json b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/package.json new file mode 100644 index 0000000..5d628e5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/package.json @@ -0,0 +1,51 @@ +{ + "name": "ieee754", + "version": "1.1.6", + "description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "standard": "^4.1.1", + "tape": "^4.0.0", + "zuul": "^3.0.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/feross/ieee754.git" + }, + "keywords": [ + "ieee754", + "IEEE 754", + "floating point", + "buffer", + "convert" + ], + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org/" + }, + "contributors": [ + { + "name": "Romain Beauxis", + "email": "toots@rastageeks.org" + } + ], + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "zuul -- test/*.js", + "test-browser-local": "zuul --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "license": "MIT", + "readme": "# ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url]\n\n[![saucelabs][saucelabs-image]][saucelabs-url]\n\n[travis-image]: https://img.shields.io/travis/feross/ieee754.svg?style=flat\n[travis-url]: https://travis-ci.org/feross/ieee754\n[npm-image]: https://img.shields.io/npm/v/ieee754.svg?style=flat\n[npm-url]: https://npmjs.org/package/ieee754\n[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg?style=flat\n[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg\n[saucelabs-url]: https://saucelabs.com/u/ieee754\n\n### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object.\n\n## install\n\n```\nnpm install ieee754\n```\n\n## methods\n\n`var ieee754 = require('ieee754')`\n\nThe `ieee754` object has the following functions:\n\n```\nieee754.read = function (buffer, offset, isLE, mLen, nBytes)\nieee754.write = function (buffer, value, offset, isLE, mLen, nBytes)\n```\n\nThe arguments mean the following:\n\n- buffer = the buffer\n- offset = offset into the buffer\n- value = value to set (only for `write`)\n- isLe = is little endian?\n- mLen = mantissa length\n- nBytes = number of bytes\n\n## what is ieee754?\n\nThe IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point).\n\n## mit license\n\nCopyright (C) 2013 [Feross Aboukhadijeh](http://feross.org) & Romain Beauxis.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/feross/ieee754/issues" + }, + "homepage": "https://github.com/feross/ieee754#readme", + "_id": "ieee754@1.1.6", + "_shasum": "2e1013219c6d6712973ec54d981ec19e5579de97", + "_resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.6.tgz", + "_from": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.6.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/test/basic.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/test/basic.js new file mode 100644 index 0000000..58fae2b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/ieee754/test/basic.js @@ -0,0 +1,23 @@ +var ieee754 = require('../') +var test = require('tape') + +var EPSILON = 0.00001 + +test('read float', function (t) { + var buf = new Buffer(4) + buf.writeFloatLE(42.42, 0) + var num = ieee754.read(buf, 0, true, 23, 4) + t.ok(Math.abs(num - 42.42) < EPSILON) + + t.end() +}) + +test('write float', function (t) { + var buf = new Buffer(4) + ieee754.write(buf, 42.42, 0, true, 23, 4) + + var num = buf.readFloatLE(0) + t.ok(Math.abs(num - 42.42) < EPSILON) + + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/.npmignore b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/.travis.yml b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/Makefile b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/Makefile new file mode 100644 index 0000000..787d56e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test.js + +.PHONY: test + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/README.md b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/README.md new file mode 100644 index 0000000..16d2c59 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/README.md @@ -0,0 +1,60 @@ + +# isarray + +`Array#isArray` for older browsers. + +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) + +[![browser support](https://ci.testling.com/juliangruber/isarray.png) +](https://ci.testling.com/juliangruber/isarray) + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS 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. diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/component.json b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/index.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/index.js new file mode 100644 index 0000000..a57f634 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/index.js @@ -0,0 +1,5 @@ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/package.json b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/package.json new file mode 100644 index 0000000..3c39d55 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/package.json @@ -0,0 +1,54 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.4" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "scripts": { + "test": "tape test.js" + }, + "readme": "\n# isarray\n\n`Array#isArray` for older browsers.\n\n[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)\n[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)\n\n[![browser support](https://ci.testling.com/juliangruber/isarray.png)\n](https://ci.testling.com/juliangruber/isarray)\n\n## Usage\n\n```js\nvar isArray = require('isarray');\n\nconsole.log(isArray([])); // => true\nconsole.log(isArray({})); // => false\n```\n\n## Installation\n\nWith [npm](http://npmjs.org) do\n\n```bash\n$ npm install isarray\n```\n\nThen bundle for the browser with\n[browserify](https://github.com/substack/browserify).\n\nWith [component](http://component.io) do\n\n```bash\n$ component install juliangruber/isarray\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "_id": "isarray@1.0.0", + "_shasum": "bb935d48582cba168c06834957a54a3e07124f11", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "_from": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/test.js b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/test.js new file mode 100644 index 0000000..e0c3444 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/node_modules/isarray/test.js @@ -0,0 +1,20 @@ +var isArray = require('./'); +var test = require('tape'); + +test('is array', function(t){ + t.ok(isArray([])); + t.notOk(isArray({})); + t.notOk(isArray(null)); + t.notOk(isArray(false)); + + var obj = {}; + obj[0] = true; + t.notOk(isArray(obj)); + + var arr = []; + arr.foo = 'bar'; + t.ok(isArray(arr)); + + t.end(); +}); + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/package.json b/node_modules/meteor-node-stubs/node_modules/buffer/package.json new file mode 100644 index 0000000..10bbfe3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/package.json @@ -0,0 +1,87 @@ +{ + "name": "buffer", + "description": "Node.js Buffer API, for the browser", + "version": "4.5.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/buffer/issues" + }, + "contributors": [ + { + "name": "Romain Beauxis", + "email": "toots@rastageeks.org" + }, + { + "name": "James Halliday", + "email": "mail@substack.net" + } + ], + "dependencies": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" + }, + "devDependencies": { + "benchmark": "^2.0.0", + "browserify": "^13.0.0", + "concat-stream": "^1.4.7", + "hyperquest": "^1.0.1", + "is-buffer": "^1.1.1", + "is-nan": "^1.0.1", + "split": "^1.0.0", + "standard": "^6.0.5", + "tape": "^4.0.0", + "through2": "^2.0.0", + "zuul": "^3.0.0" + }, + "homepage": "https://github.com/feross/buffer", + "keywords": [ + "buffer", + "browserify", + "compatible", + "browser", + "arraybuffer", + "uint8array", + "dataview" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/feross/buffer.git" + }, + "scripts": { + "test": "standard && node ./bin/test.js", + "test-browser": "zuul -- test/*.js test/node/*.js", + "test-browser-local": "zuul --local -- test/*.js test/node/*.js", + "test-node": "tape test/*.js test/node/*.js test/node-es6/*.js && OBJECT_IMPL=true tape test/*.js test/node/*.js", + "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", + "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", + "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c" + }, + "standard": { + "ignore": [ + "test/node/*.js", + "test/node-es6/*.js", + "test/_polyfill.js", + "perf/*.js" + ] + }, + "jspm": { + "map": { + "./index.js": { + "node": "@node/buffer" + } + } + }, + "readme": "# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url]\n\n#### The buffer module from [node.js](https://nodejs.org/), for the browser.\n\n[![saucelabs][saucelabs-image]][saucelabs-url]\n\n[travis-image]: https://img.shields.io/travis/feross/buffer.svg\n[travis-url]: https://travis-ci.org/feross/buffer\n[npm-image]: https://img.shields.io/npm/v/buffer.svg\n[npm-url]: https://npmjs.org/package/buffer\n[downloads-image]: https://img.shields.io/npm/dm/buffer.svg\n[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg\n[saucelabs-url]: https://saucelabs.com/u/buffer\n\nWith [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module.\n\nThe goal is to provide an API that is 100% identical to\n[node's Buffer API](https://nodejs.org/api/buffer.html). Read the\n[official docs](https://nodejs.org/api/buffer.html) for the full list of properties,\ninstance methods, and class methods that are supported.\n\n## features\n\n- Manipulate binary data like a boss, in all browsers -- even IE6!\n- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`)\n- Extremely small bundle size (**5.04KB minified + gzipped**, 35.5KB with comments)\n- Excellent browser support (IE 6+, Chrome 4+, Firefox 3+, Safari 5.1+, Opera 11+, iOS, etc.)\n- Preserves Node API exactly, with one important difference (see below)\n- `.slice()` returns instances of the same type (Buffer)\n- Square-bracket `buf[4]` notation works, even in old browsers like IE6!\n- Does not modify any browser prototypes or put anything on `window`\n- Comprehensive test suite (including all buffer tests from node.js core)\n\n\n## install\n\nTo use this module directly (without browserify), install it:\n\n```bash\nnpm install buffer\n```\n\nThis module was previously called **native-buffer-browserify**, but please use **buffer**\nfrom now on.\n\nA standalone bundle is available [here](https://wzrd.in/standalone/buffer), for non-browserify users.\n\n\n## usage\n\nThe module's API is identical to node's `Buffer` API. Read the\n[official docs](https://nodejs.org/api/buffer.html) for the full list of properties,\ninstance methods, and class methods that are supported.\n\nAs mentioned above, `require('buffer')` or use the `Buffer` global with\n[browserify](http://browserify.org) and this module will automatically be included\nin your bundle. Almost any npm module will work in the browser, even if it assumes that\nthe node `Buffer` API will be available.\n\nTo depend on this module explicitly (without browserify), require it like this:\n\n```js\nvar Buffer = require('buffer/').Buffer // note: the trailing slash is important!\n```\n\nTo require this module explicitly, use `require('buffer/')` which tells the node.js module\nlookup algorithm (also used by browserify) to use the **npm module** named `buffer`\ninstead of the **node.js core** module named `buffer`!\n\n\n## how does it work?\n\nThe Buffer constructor returns instances of `Uint8Array` that have their prototype\nchanged to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`,\nso the returned instances will have all the node `Buffer` methods and the\n`Uint8Array` methods. Square bracket notation works as expected -- it returns a\nsingle octet.\n\nThe `Uint8Array` prototype remains unmodified.\n\n\n## one minor difference\n\n#### In old browsers, `buf.slice()` does not modify parent buffer's memory\n\nIf you only support modern browsers (specifically, those with typed array support),\nthen this issue does not affect you. If you support super old browsers, then read on.\n\nIn node, the `slice()` method returns a new `Buffer` that shares underlying memory\nwith the original Buffer. When you modify one buffer, you modify the other.\n[Read more.](https://nodejs.org/api/buffer.html#buffer_buf_slice_start_end)\n\nIn browsers with typed array support, this `Buffer` implementation supports this\nbehavior. In browsers without typed arrays, an alternate buffer implementation is\nused that is based on `Object` which has no mechanism to point separate\n`Buffer`s to the same underlying slab of memory.\n\nYou can see which browser versions lack typed array support\n[here](https://github.com/feross/buffer/blob/master/index.js#L22-L48).\n\n\n## tracking the latest node api\n\nThis module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer\nAPI is considered **stable** in the\n[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index),\nso it is unlikely that there will ever be breaking changes.\nNonetheless, when/if the Buffer API changes in node, this module's API will change\naccordingly.\n\n## related packages\n\n- [`buffer-equals`](https://www.npmjs.com/package/buffer-equals) - Node.js 0.12 buffer.equals() ponyfill\n- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - A lite module for reverse-operations on buffers\n- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - A simple module for bitwise-xor on buffers\n- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package\n- [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) - Convert a typed array to a Buffer without a copy\n\n## performance\n\nSee perf tests in `/perf`.\n\n`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a\nsanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will\nalways be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module,\nwhich is included to compare against.\n\nNOTE: Performance has improved since these benchmarks were taken. PR welcoem to update the README.\n\n### Chrome 38\n\n| Method | Operations | Accuracy | Sampled | Fastest |\n|:-------|:-----------|:---------|:--------|:-------:|\n| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ |\n| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | |\n| | | | |\n| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | |\n| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ |\n| | | | |\n| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | |\n| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ |\n| | | | |\n| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | |\n| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ |\n| | | | |\n| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | |\n| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ |\n| | | | |\n| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | |\n| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ |\n| | | | |\n| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ |\n| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | |\n| | | | |\n| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ |\n| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | |\n| | | | |\n| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ |\n| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | |\n| | | | |\n| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | |\n| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ |\n| | | | |\n| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | |\n| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ |\n\n\n### Firefox 33\n\n| Method | Operations | Accuracy | Sampled | Fastest |\n|:-------|:-----------|:---------|:--------|:-------:|\n| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | |\n| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ |\n| | | | |\n| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | |\n| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ |\n| | | | |\n| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | |\n| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ |\n| | | | |\n| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | |\n| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ |\n| | | | |\n| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | |\n| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ |\n| | | | |\n| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | |\n| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ |\n| | | | |\n| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | |\n| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ |\n| | | | |\n| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | |\n| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ |\n| | | | |\n| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ |\n| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | |\n| | | | |\n| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | |\n| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ |\n| | | | |\n| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | |\n| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ |\n\n### Safari 8\n\n| Method | Operations | Accuracy | Sampled | Fastest |\n|:-------|:-----------|:---------|:--------|:-------:|\n| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ |\n| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | |\n| | | | |\n| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | |\n| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ |\n| | | | |\n| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | |\n| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ |\n| | | | |\n| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | |\n| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ |\n| | | | |\n| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | |\n| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ |\n| | | | |\n| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | |\n| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ |\n| | | | |\n| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | |\n| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ |\n| | | | |\n| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | |\n| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ |\n| | | | |\n| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | |\n| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ |\n| | | | |\n| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | |\n| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ |\n| | | | |\n| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | |\n| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ |\n\n\n### Node 0.11.14\n\n| Method | Operations | Accuracy | Sampled | Fastest |\n|:-------|:-----------|:---------|:--------|:-------:|\n| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | |\n| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ |\n| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | |\n| | | | |\n| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | |\n| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ |\n| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | |\n| | | | |\n| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | |\n| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ |\n| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | |\n| | | | |\n| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | |\n| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ |\n| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | |\n| | | | |\n| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | |\n| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | |\n| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ |\n| | | | |\n| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | |\n| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ |\n| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | |\n| | | | |\n| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ |\n| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | |\n| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | |\n| | | | |\n| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ |\n| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | |\n| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | |\n| | | | |\n| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | |\n| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | |\n| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ |\n| | | | |\n| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | |\n| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ |\n| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | |\n| | | | |\n| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | |\n| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ |\n| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | |\n\n### iojs 1.8.1\n\n| Method | Operations | Accuracy | Sampled | Fastest |\n|:-------|:-----------|:---------|:--------|:-------:|\n| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | |\n| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | |\n| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ |\n| | | | |\n| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | |\n| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | |\n| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ |\n| | | | |\n| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | |\n| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | |\n| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ |\n| | | | |\n| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | |\n| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ |\n| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | |\n| | | | |\n| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | |\n| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | |\n| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ |\n| | | | |\n| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | |\n| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ |\n| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | |\n| | | | |\n| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ |\n| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | |\n| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | |\n| | | | |\n| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ |\n| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | |\n| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | |\n| | | | |\n| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | |\n| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | |\n| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ |\n| | | | |\n| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | |\n| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | |\n| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ |\n| | | | |\n| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | |\n| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ |\n| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | |\n| | | | |\n\n## Testing the project\n\nFirst, install the project:\n\n npm install\n\nThen, to run tests in Node.js, run:\n\n npm run test-node\n\nTo test locally in a browser, you can run:\n\n npm run test-browser-local\n\nThis will print out a URL that you can then open in a browser to run the tests, using [Zuul](https://github.com/defunctzombie/zuul).\n\nTo run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run:\n\n npm test\n\nThis is what's run in Travis, to check against various browsers. The list of browsers is kept in the `.zuul.yml` file.\n\n## JavaScript Standard Style\n\nThis module uses [JavaScript Standard Style](https://github.com/feross/standard).\n\n[![js-standard-style](https://raw.githubusercontent.com/feross/standard/master/badge.png)](https://github.com/feross/standard)\n\nTo test that the code conforms to the style, `npm install` and run:\n\n ./node_modules/.bin/standard\n\n## credit\n\nThis was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify).\n\n\n## license\n\nMIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis.\n", + "readmeFilename": "README.md", + "_id": "buffer@4.5.1", + "_shasum": "237b5bdef693c4c332385c1ded4ef4646e232d73", + "_resolved": "https://registry.npmjs.org/buffer/-/buffer-4.5.1.tgz", + "_from": "https://registry.npmjs.org/buffer/-/buffer-4.5.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/_polyfill.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/_polyfill.js new file mode 100644 index 0000000..61f9c18 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/_polyfill.js @@ -0,0 +1,150 @@ +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function(callback, thisArg) { + + var T, k; + + if (this == null) { + throw new TypeError(' this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the |this| value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== "function") { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = thisArg; + } + + // 6. Let k be 0 + k = 0; + + // 7. Repeat, while k < len + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal method of O with argument Pk. + kValue = O[k]; + + // ii. Call the Call internal method of callback with T as the this value and + // argument list containing kValue, k, and O. + callback.call(T, kValue, k, O); + } + // d. Increase k by 1. + k++; + } + // 8. return undefined + }; +} + +if (!Array.isArray) { + Array.isArray = function(arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; +} + +if (!Array.prototype.map) { + + Array.prototype.map = function(callback, thisArg) { + + var T, A, k; + + if (this == null) { + throw new TypeError(' this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the |this| + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal + // method of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = thisArg; + } + + // 6. Let A be a new array created as if by the expression new Array(len) + // where Array is the standard built-in constructor with that name and + // len is the value of len. + A = new Array(len); + + // 7. Let k be 0 + k = 0; + + // 8. Repeat, while k < len + while (k < len) { + + var kValue, mappedValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Let mappedValue be the result of calling the Call internal + // method of callback with T as the this value and argument + // list containing kValue, k, and O. + mappedValue = callback.call(T, kValue, k, O); + + // iii. Call the DefineOwnProperty internal method of A with arguments + // Pk, Property Descriptor + // { Value: mappedValue, + // Writable: true, + // Enumerable: true, + // Configurable: true }, + // and false. + + // In browsers that support Object.defineProperty, use the following: + // Object.defineProperty(A, k, { + // value: mappedValue, + // writable: true, + // enumerable: true, + // configurable: true + // }); + + // For best browser support, use the following: + A[k] = mappedValue; + } + // d. Increase k by 1. + k++; + } + + // 9. return A + return A; + }; +} diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/base64.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/base64.js new file mode 100644 index 0000000..e4ecc56 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/base64.js @@ -0,0 +1,47 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('base64: ignore whitespace', function (t) { + var text = '\n YW9ldQ== ' + var buf = new B(text, 'base64') + t.equal(buf.toString(), 'aoeu') + t.end() +}) + +test('base64: strings without padding', function (t) { + t.equal((new B('YW9ldQ', 'base64').toString()), 'aoeu') + t.end() +}) + +test('base64: newline in utf8 -- should not be an issue', function (t) { + t.equal( + new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK', 'base64').toString('utf8'), + '---\ntitle: Three dashes marks the spot\ntags:\n' + ) + t.end() +}) + +test('base64: newline in base64 -- should get stripped', function (t) { + t.equal( + new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK\nICAtIHlhbWwKICAtIGZyb250LW1hdHRlcgogIC0gZGFzaGVzCmV4cGFuZWQt', 'base64').toString('utf8'), + '---\ntitle: Three dashes marks the spot\ntags:\n - yaml\n - front-matter\n - dashes\nexpaned-' + ) + t.end() +}) + +test('base64: tab characters in base64 - should get stripped', function (t) { + t.equal( + new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK\t\t\t\tICAtIHlhbWwKICAtIGZyb250LW1hdHRlcgogIC0gZGFzaGVzCmV4cGFuZWQt', 'base64').toString('utf8'), + '---\ntitle: Three dashes marks the spot\ntags:\n - yaml\n - front-matter\n - dashes\nexpaned-' + ) + t.end() +}) + +test('base64: invalid non-alphanumeric characters -- should be stripped', function (t) { + t.equal( + new B('!"#$%&\'()*,.:;<=>?@[\\]^`{|}~', 'base64').toString('utf8'), + '' + ) + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/basic.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/basic.js new file mode 100644 index 0000000..0368ed9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/basic.js @@ -0,0 +1,85 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('instanceof Buffer', function (t) { + var buf = new B([1, 2]) + t.ok(buf instanceof B) + t.end() +}) + +test('convert to Uint8Array in modern browsers', function (t) { + if (B.TYPED_ARRAY_SUPPORT) { + var buf = new B([1, 2]) + var uint8array = new Uint8Array(buf.buffer) + t.ok(uint8array instanceof Uint8Array) + t.equal(uint8array[0], 1) + t.equal(uint8array[1], 2) + } else { + t.pass('object impl: skipping test') + } + t.end() +}) + +test('indexes from a string', function (t) { + var buf = new B('abc') + t.equal(buf[0], 97) + t.equal(buf[1], 98) + t.equal(buf[2], 99) + t.end() +}) + +test('indexes from an array', function (t) { + var buf = new B([ 97, 98, 99 ]) + t.equal(buf[0], 97) + t.equal(buf[1], 98) + t.equal(buf[2], 99) + t.end() +}) + +test('setting index value should modify buffer contents', function (t) { + var buf = new B([ 97, 98, 99 ]) + t.equal(buf[2], 99) + t.equal(buf.toString(), 'abc') + + buf[2] += 10 + t.equal(buf[2], 109) + t.equal(buf.toString(), 'abm') + t.end() +}) + +test('storing negative number should cast to unsigned', function (t) { + var buf = new B(1) + + if (B.TYPED_ARRAY_SUPPORT) { + // This does not work with the object implementation -- nothing we can do! + buf[0] = -3 + t.equal(buf[0], 253) + } + + buf = new B(1) + buf.writeInt8(-3, 0) + t.equal(buf[0], 253) + + t.end() +}) + +test('test that memory is copied from array-like', function (t) { + if (B.TYPED_ARRAY_SUPPORT) { + var u = new Uint8Array(4) + var b = new B(u) + b[0] = 1 + b[1] = 2 + b[2] = 3 + b[3] = 4 + + t.equal(u[0], 0) + t.equal(u[1], 0) + t.equal(u[2], 0) + t.equal(u[3], 0) + } else { + t.pass('object impl: skipping test') + } + + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/compare.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/compare.js new file mode 100644 index 0000000..62b478c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/compare.js @@ -0,0 +1,59 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('buffer.compare', function (t) { + var b = new B(1).fill('a') + var c = new B(1).fill('c') + var d = new B(2).fill('aa') + + t.equal(b.compare(c), -1) + t.equal(c.compare(d), 1) + t.equal(d.compare(b), 1) + t.equal(b.compare(d), -1) + + // static method + t.equal(B.compare(b, c), -1) + t.equal(B.compare(c, d), 1) + t.equal(B.compare(d, b), 1) + t.equal(B.compare(b, d), -1) + t.end() +}) + +test('buffer.compare argument validation', function (t) { + t.throws(function () { + var b = new B(1) + B.compare(b, 'abc') + }) + + t.throws(function () { + var b = new B(1) + B.compare('abc', b) + }) + + t.throws(function () { + var b = new B(1) + b.compare('abc') + }) + t.end() +}) + +test('buffer.equals', function (t) { + var b = new B(5).fill('abcdf') + var c = new B(5).fill('abcdf') + var d = new B(5).fill('abcde') + var e = new B(6).fill('abcdef') + + t.ok(b.equals(c)) + t.ok(!c.equals(d)) + t.ok(!d.equals(e)) + t.end() +}) + +test('buffer.equals argument validation', function (t) { + t.throws(function () { + var b = new B(1) + b.equals('abc') + }) + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/constructor.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/constructor.js new file mode 100644 index 0000000..cec5cdc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/constructor.js @@ -0,0 +1,193 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('new buffer from array', function (t) { + t.equal( + new B([1, 2, 3]).toString(), + '\u0001\u0002\u0003' + ) + t.end() +}) + +test('new buffer from array w/ negatives', function (t) { + t.equal( + new B([-1, -2, -3]).toString('hex'), + 'fffefd' + ) + t.end() +}) + +test('new buffer from array with mixed signed input', function (t) { + t.equal( + new B([-255, 255, -128, 128, 512, -512, 511, -511]).toString('hex'), + '01ff80800000ff01' + ) + t.end() +}) + +test('new buffer from string', function (t) { + t.equal( + new B('hey', 'utf8').toString(), + 'hey' + ) + t.end() +}) + +test('new buffer from buffer', function (t) { + var b1 = new B('asdf') + var b2 = new B(b1) + t.equal(b1.toString('hex'), b2.toString('hex')) + t.end() +}) + +test('new buffer from ArrayBuffer', function (t) { + if (typeof ArrayBuffer !== 'undefined') { + var arraybuffer = new Uint8Array([0, 1, 2, 3]).buffer + var b = new B(arraybuffer) + t.equal(b.length, 4) + t.equal(b[0], 0) + t.equal(b[1], 1) + t.equal(b[2], 2) + t.equal(b[3], 3) + t.equal(b[4], undefined) + } + t.end() +}) + +test('new buffer from ArrayBuffer, shares memory', function (t) { + if (Buffer.TYPED_ARRAY_SUPPORT) { + var u = new Uint8Array([0, 1, 2, 3]) + var arraybuffer = u.buffer + var b = new B(arraybuffer) + t.equal(b.length, 4) + t.equal(b[0], 0) + t.equal(b[1], 1) + t.equal(b[2], 2) + t.equal(b[3], 3) + t.equal(b[4], undefined) + + // changing the Uint8Array (and thus the ArrayBuffer), changes the Buffer + u[0] = 10 + t.equal(b[0], 10) + u[1] = 11 + t.equal(b[1], 11) + u[2] = 12 + t.equal(b[2], 12) + u[3] = 13 + t.equal(b[3], 13) + } + t.end() +}) + +test('new buffer from Uint8Array', function (t) { + if (typeof Uint8Array !== 'undefined') { + var b1 = new Uint8Array([0, 1, 2, 3]) + var b2 = new B(b1) + t.equal(b1.length, b2.length) + t.equal(b1[0], 0) + t.equal(b1[1], 1) + t.equal(b1[2], 2) + t.equal(b1[3], 3) + t.equal(b1[4], undefined) + } + t.end() +}) + +test('new buffer from Uint16Array', function (t) { + if (typeof Uint16Array !== 'undefined') { + var b1 = new Uint16Array([0, 1, 2, 3]) + var b2 = new B(b1) + t.equal(b1.length, b2.length) + t.equal(b1[0], 0) + t.equal(b1[1], 1) + t.equal(b1[2], 2) + t.equal(b1[3], 3) + t.equal(b1[4], undefined) + } + t.end() +}) + +test('new buffer from Uint32Array', function (t) { + if (typeof Uint32Array !== 'undefined') { + var b1 = new Uint32Array([0, 1, 2, 3]) + var b2 = new B(b1) + t.equal(b1.length, b2.length) + t.equal(b1[0], 0) + t.equal(b1[1], 1) + t.equal(b1[2], 2) + t.equal(b1[3], 3) + t.equal(b1[4], undefined) + } + t.end() +}) + +test('new buffer from Int16Array', function (t) { + if (typeof Int16Array !== 'undefined') { + var b1 = new Int16Array([0, 1, 2, 3]) + var b2 = new B(b1) + t.equal(b1.length, b2.length) + t.equal(b1[0], 0) + t.equal(b1[1], 1) + t.equal(b1[2], 2) + t.equal(b1[3], 3) + t.equal(b1[4], undefined) + } + t.end() +}) + +test('new buffer from Int32Array', function (t) { + if (typeof Int32Array !== 'undefined') { + var b1 = new Int32Array([0, 1, 2, 3]) + var b2 = new B(b1) + t.equal(b1.length, b2.length) + t.equal(b1[0], 0) + t.equal(b1[1], 1) + t.equal(b1[2], 2) + t.equal(b1[3], 3) + t.equal(b1[4], undefined) + } + t.end() +}) + +test('new buffer from Float32Array', function (t) { + if (typeof Float32Array !== 'undefined') { + var b1 = new Float32Array([0, 1, 2, 3]) + var b2 = new B(b1) + t.equal(b1.length, b2.length) + t.equal(b1[0], 0) + t.equal(b1[1], 1) + t.equal(b1[2], 2) + t.equal(b1[3], 3) + t.equal(b1[4], undefined) + } + t.end() +}) + +test('new buffer from Float64Array', function (t) { + if (typeof Float64Array !== 'undefined') { + var b1 = new Float64Array([0, 1, 2, 3]) + var b2 = new B(b1) + t.equal(b1.length, b2.length) + t.equal(b1[0], 0) + t.equal(b1[1], 1) + t.equal(b1[2], 2) + t.equal(b1[3], 3) + t.equal(b1[4], undefined) + } + t.end() +}) + +test('new buffer from buffer.toJSON() output', function (t) { + if (typeof JSON === 'undefined') { + // ie6, ie7 lack support + t.end() + return + } + var buf = new B('test') + var json = JSON.stringify(buf) + var obj = JSON.parse(json) + var copy = new B(obj) + t.ok(buf.equals(copy)) + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/from-string.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/from-string.js new file mode 100644 index 0000000..e25db26 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/from-string.js @@ -0,0 +1,132 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('detect utf16 surrogate pairs', function (t) { + var text = '\uD83D\uDE38' + '\uD83D\uDCAD' + '\uD83D\uDC4D' + var buf = new B(text) + t.equal(text, buf.toString()) + t.end() +}) + +test('detect utf16 surrogate pairs over U+20000 until U+10FFFF', function (t) { + var text = '\uD842\uDFB7' + '\uD93D\uDCAD' + '\uDBFF\uDFFF' + var buf = new B(text) + t.equal(text, buf.toString()) + t.end() +}) + +test('replace orphaned utf16 surrogate lead code point', function (t) { + var text = '\uD83D\uDE38' + '\uD83D' + '\uD83D\uDC4D' + var buf = new B(text) + t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0xef, 0xbf, 0xbd, 0xf0, 0x9f, 0x91, 0x8d ])) + t.end() +}) + +test('replace orphaned utf16 surrogate trail code point', function (t) { + var text = '\uD83D\uDE38' + '\uDCAD' + '\uD83D\uDC4D' + var buf = new B(text) + t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0xef, 0xbf, 0xbd, 0xf0, 0x9f, 0x91, 0x8d ])) + t.end() +}) + +test('do not write partial utf16 code units', function (t) { + var f = new B([0, 0, 0, 0, 0]) + t.equal(f.length, 5) + var size = f.write('あいうえお', 'utf16le') + t.equal(size, 4) + t.deepEqual(f, new B([0x42, 0x30, 0x44, 0x30, 0x00])) + t.end() +}) + +test('handle partial utf16 code points when encoding to utf8 the way node does', function (t) { + var text = '\uD83D\uDE38' + '\uD83D\uDC4D' + + var buf = new B(8) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0xf0, 0x9f, 0x91, 0x8d ])) + + buf = new B(7) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0x00, 0x00, 0x00 ])) + + buf = new B(6) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0x00, 0x00 ])) + + buf = new B(5) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0x00 ])) + + buf = new B(4) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8 ])) + + buf = new B(3) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x00, 0x00, 0x00 ])) + + buf = new B(2) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x00, 0x00 ])) + + buf = new B(1) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x00 ])) + + t.end() +}) + +test('handle invalid utf16 code points when encoding to utf8 the way node does', function (t) { + var text = 'a' + '\uDE38\uD83D' + 'b' + + var buf = new B(8) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd, 0x62 ])) + + buf = new B(7) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd ])) + + buf = new B(6) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd, 0x00, 0x00 ])) + + buf = new B(5) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd, 0x00 ])) + + buf = new B(4) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd ])) + + buf = new B(3) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x61, 0x00, 0x00 ])) + + buf = new B(2) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x61, 0x00 ])) + + buf = new B(1) + buf.fill(0) + buf.write(text) + t.deepEqual(buf, new B([ 0x61 ])) + + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/is-buffer.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/is-buffer.js new file mode 100644 index 0000000..3744b23 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/is-buffer.js @@ -0,0 +1,22 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var isBuffer = require('is-buffer') +var test = require('tape') + +test('is-buffer tests', function (t) { + t.ok(isBuffer(new B(4)), 'new Buffer(4)') + + t.notOk(isBuffer(undefined), 'undefined') + t.notOk(isBuffer(null), 'null') + t.notOk(isBuffer(''), 'empty string') + t.notOk(isBuffer(true), 'true') + t.notOk(isBuffer(false), 'false') + t.notOk(isBuffer(0), '0') + t.notOk(isBuffer(1), '1') + t.notOk(isBuffer(1.0), '1.0') + t.notOk(isBuffer('string'), 'string') + t.notOk(isBuffer({}), '{}') + t.notOk(isBuffer(function foo () {}), 'function foo () {}') + + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/methods.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/methods.js new file mode 100644 index 0000000..f4bd3f2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/methods.js @@ -0,0 +1,127 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('buffer.toJSON', function (t) { + var data = [1, 2, 3, 4] + t.deepEqual( + new B(data).toJSON(), + { type: 'Buffer', data: [ 1, 2, 3, 4 ] } + ) + t.end() +}) + +test('buffer.copy', function (t) { + // copied from nodejs.org example + var buf1 = new B(26) + var buf2 = new B(26) + + for (var i = 0; i < 26; i++) { + buf1[i] = i + 97 // 97 is ASCII a + buf2[i] = 33 // ASCII ! + } + + buf1.copy(buf2, 8, 16, 20) + + t.equal( + buf2.toString('ascii', 0, 25), + '!!!!!!!!qrst!!!!!!!!!!!!!' + ) + t.end() +}) + +test('test offset returns are correct', function (t) { + var b = new B(16) + t.equal(4, b.writeUInt32LE(0, 0)) + t.equal(6, b.writeUInt16LE(0, 4)) + t.equal(7, b.writeUInt8(0, 6)) + t.equal(8, b.writeInt8(0, 7)) + t.equal(16, b.writeDoubleLE(0, 8)) + t.end() +}) + +test('concat() a varying number of buffers', function (t) { + var zero = [] + var one = [ new B('asdf') ] + var long = [] + for (var i = 0; i < 10; i++) { + long.push(new B('asdf')) + } + + var flatZero = B.concat(zero) + var flatOne = B.concat(one) + var flatLong = B.concat(long) + var flatLongLen = B.concat(long, 40) + + t.equal(flatZero.length, 0) + t.equal(flatOne.toString(), 'asdf') + t.deepEqual(flatOne, one[0]) + t.equal(flatLong.toString(), (new Array(10 + 1).join('asdf'))) + t.equal(flatLongLen.toString(), (new Array(10 + 1).join('asdf'))) + t.end() +}) + +test('fill', function (t) { + var b = new B(10) + b.fill(2) + t.equal(b.toString('hex'), '02020202020202020202') + t.end() +}) + +test('fill (string)', function (t) { + var b = new B(10) + b.fill('abc') + t.equal(b.toString(), 'abcabcabca') + b.fill('է') + t.equal(b.toString(), 'էէէէէ') + t.end() +}) + +test('copy() empty buffer with sourceEnd=0', function (t) { + var source = new B([42]) + var destination = new B([43]) + source.copy(destination, 0, 0, 0) + t.equal(destination.readUInt8(0), 43) + t.end() +}) + +test('copy() after slice()', function (t) { + var source = new B(200) + var dest = new B(200) + var expected = new B(200) + for (var i = 0; i < 200; i++) { + source[i] = i + dest[i] = 0 + } + + source.slice(2).copy(dest) + source.copy(expected, 0, 2) + t.deepEqual(dest, expected) + t.end() +}) + +test('copy() ascending', function (t) { + var b = new B('abcdefghij') + b.copy(b, 0, 3, 10) + t.equal(b.toString(), 'defghijhij') + t.end() +}) + +test('copy() descending', function (t) { + var b = new B('abcdefghij') + b.copy(b, 3, 0, 7) + t.equal(b.toString(), 'abcabcdefg') + t.end() +}) + +test('buffer.slice sets indexes', function (t) { + t.equal((new B('hallo')).slice(0, 5).toString(), 'hallo') + t.end() +}) + +test('buffer.slice out of range', function (t) { + t.plan(2) + t.equal((new B('hallo')).slice(0, 10).toString(), 'hallo') + t.equal((new B('hallo')).slice(10, 2).toString(), '') + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/README.txt b/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/README.txt new file mode 100644 index 0000000..94199ff --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/README.txt @@ -0,0 +1 @@ +node buffer tests that require ES6 (e.g. "for..of" construct) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/test-buffer-arraybuffer.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/test-buffer-arraybuffer.js new file mode 100644 index 0000000..f0eb57c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/test-buffer-arraybuffer.js @@ -0,0 +1,49 @@ +'use strict'; +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false; +var Buffer = require('../../').Buffer; + +var common = {}; +var assert = require('assert'); + +var Buffer = require('../../').Buffer; +var LENGTH = 16; + +var ab = new ArrayBuffer(LENGTH); +var dv = new DataView(ab); +var ui = new Uint8Array(ab); +var buf = new Buffer(ab); + + +assert.ok(Buffer.isBuffer(buf)); +// For backwards compatibility of old .parent property test that if buf is not +// a slice then .parent should be undefined. +assert.equal(buf.parent, undefined); +assert.equal(buf.buffer, ab); +assert.equal(buf.length, ab.byteLength); + + +buf.fill(0xC); +for (var i = 0; i < LENGTH; i++) { + assert.equal(ui[i], 0xC); + ui[i] = 0xF; + assert.equal(buf[i], 0xF); +} + +buf.writeUInt32LE(0xF00, 0); +buf.writeUInt32BE(0xB47, 4); +buf.writeDoubleLE(3.1415, 8); + +assert.equal(dv.getUint32(0, true), 0xF00); +assert.equal(dv.getUint32(4), 0xB47); +assert.equal(dv.getFloat64(8, true), 3.1415); + + +// Now test protecting users from doing stupid things + +assert.throws(function() { + function AB() { } + AB.__proto__ = ArrayBuffer; + AB.prototype.__proto__ = ArrayBuffer.prototype; + new Buffer(new AB()); +}, TypeError); + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/test-buffer-iterator.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/test-buffer-iterator.js new file mode 100644 index 0000000..3aa3fbf --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node-es6/test-buffer-iterator.js @@ -0,0 +1,65 @@ +'use strict'; +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false; +var Buffer = require('../../').Buffer; +var common = {}; +var assert = require('assert'); + +var buffer = new Buffer([1, 2, 3, 4, 5]); +var arr; +var b; + +// buffers should be iterable + +arr = []; + +for (b of buffer) + arr.push(b); + +assert.deepEqual(arr, [1, 2, 3, 4, 5]); + + +// buffer iterators should be iterable + +arr = []; + +for (b of buffer[Symbol.iterator]()) + arr.push(b); + +assert.deepEqual(arr, [1, 2, 3, 4, 5]); + + +// buffer#values() should return iterator for values + +arr = []; + +for (b of buffer.values()) + arr.push(b); + +assert.deepEqual(arr, [1, 2, 3, 4, 5]); + + +// buffer#keys() should return iterator for keys + +arr = []; + +for (b of buffer.keys()) + arr.push(b); + +assert.deepEqual(arr, [0, 1, 2, 3, 4]); + + +// buffer#entries() should return iterator for entries + +arr = []; + +for (var b of buffer.entries()) + arr.push(b); + +assert.deepEqual(arr, [ + [0, 1], + [1, 2], + [2, 3], + [3, 4], + [4, 5] +]); + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node/README.txt b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/README.txt new file mode 100644 index 0000000..a0fd927 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/README.txt @@ -0,0 +1 @@ +node core buffer tests diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-ascii.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-ascii.js new file mode 100644 index 0000000..633a677 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-ascii.js @@ -0,0 +1,28 @@ +'use strict'; +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false; +var Buffer = require('../../').Buffer; +var common = {}; +var assert = require('assert'); + +// ASCII conversion in node.js simply masks off the high bits, +// it doesn't do transliteration. +assert.equal(Buffer('hérité').toString('ascii'), 'hC)ritC)'); + +// 71 characters, 78 bytes. The ’ character is a triple-byte sequence. +var input = 'C’est, graphiquement, la réunion d’un accent aigu ' + + 'et d’un accent grave.'; + +var expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' + + 'db\u0000\u0019un accent aigu et db\u0000\u0019un ' + + 'accent grave.'; + +var buf = Buffer(input); + +for (var i = 0; i < expected.length; ++i) { + assert.equal(buf.slice(i).toString('ascii'), expected.slice(i)); + + // Skip remainder of multi-byte sequence. + if (input.charCodeAt(i) > 65535) ++i; + if (input.charCodeAt(i) > 127) ++i; +} + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-bytelength.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-bytelength.js new file mode 100644 index 0000000..d63922e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-bytelength.js @@ -0,0 +1,49 @@ +'use strict'; +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false; +var Buffer = require('../../').Buffer; + +var common = {}; +var assert = require('assert'); +var Buffer = require('../../').Buffer; + +// coerce values to string +assert.equal(Buffer.byteLength(32, 'raw'), 2); +assert.equal(Buffer.byteLength(NaN, 'utf8'), 3); +assert.equal(Buffer.byteLength({}, 'raws'), 15); +assert.equal(Buffer.byteLength(), 9); + +// special case: zero length string +assert.equal(Buffer.byteLength('', 'ascii'), 0); +assert.equal(Buffer.byteLength('', 'HeX'), 0); + +// utf8 +assert.equal(Buffer.byteLength('∑éllö wørl∂!', 'utf-8'), 19); +assert.equal(Buffer.byteLength('κλμνξο', 'utf8'), 12); +assert.equal(Buffer.byteLength('挵挶挷挸挹', 'utf-8'), 15); +assert.equal(Buffer.byteLength('𠝹𠱓𠱸', 'UTF8'), 12); +// without an encoding, utf8 should be assumed +assert.equal(Buffer.byteLength('hey there'), 9); +assert.equal(Buffer.byteLength('𠱸挶νξ#xx :)'), 17); +assert.equal(Buffer.byteLength('hello world', ''), 11); +// it should also be assumed with unrecognized encoding +assert.equal(Buffer.byteLength('hello world', 'abc'), 11); +assert.equal(Buffer.byteLength('ßœ∑≈', 'unkn0wn enc0ding'), 10); + +// base64 +assert.equal(Buffer.byteLength('aGVsbG8gd29ybGQ=', 'base64'), 11); +assert.equal(Buffer.byteLength('bm9kZS5qcyByb2NrcyE=', 'base64'), 14); +assert.equal(Buffer.byteLength('aGkk', 'base64'), 3); +assert.equal(Buffer.byteLength('bHNrZGZsa3NqZmtsc2xrZmFqc2RsZmtqcw==', + 'base64'), 25); +// special padding +assert.equal(Buffer.byteLength('aaa=', 'base64'), 2); +assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3); + +assert.equal(Buffer.byteLength('Il était tué'), 14); +assert.equal(Buffer.byteLength('Il était tué', 'utf8'), 14); +assert.equal(Buffer.byteLength('Il était tué', 'ascii'), 12); +assert.equal(Buffer.byteLength('Il était tué', 'binary'), 12); +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + assert.equal(24, Buffer.byteLength('Il était tué', encoding)); +}); + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-concat.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-concat.js new file mode 100644 index 0000000..f6b60ae --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-concat.js @@ -0,0 +1,30 @@ +'use strict'; +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false; +var Buffer = require('../../').Buffer; +var common = {}; +var assert = require('assert'); + +var zero = []; +var one = [ new Buffer('asdf') ]; +var long = []; +for (var i = 0; i < 10; i++) long.push(new Buffer('asdf')); + +var flatZero = Buffer.concat(zero); +var flatOne = Buffer.concat(one); +var flatLong = Buffer.concat(long); +var flatLongLen = Buffer.concat(long, 40); + +assert(flatZero.length === 0); +assert(flatOne.toString() === 'asdf'); +// A special case where concat used to return the first item, +// if the length is one. This check is to make sure that we don't do that. +assert(flatOne !== one[0]); +assert(flatLong.toString() === (new Array(10 + 1).join('asdf'))); +assert(flatLongLen.toString() === (new Array(10 + 1).join('asdf'))); + +assert.throws(function() { + Buffer.concat([42]); +}, TypeError); + +// console.log('ok'); + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-indexof.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-indexof.js new file mode 100644 index 0000000..283b9c8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-indexof.js @@ -0,0 +1,79 @@ +'use strict'; +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false; +var Buffer = require('../../').Buffer; +var common = {}; +var assert = require('assert'); + +var Buffer = require('../../').Buffer; + +var b = new Buffer('abcdef'); +var buf_a = new Buffer('a'); +var buf_bc = new Buffer('bc'); +var buf_f = new Buffer('f'); +var buf_z = new Buffer('z'); +var buf_empty = new Buffer(''); + +assert.equal(b.indexOf('a'), 0); +assert.equal(b.indexOf('a', 1), -1); +assert.equal(b.indexOf('a', -1), -1); +assert.equal(b.indexOf('a', -4), -1); +assert.equal(b.indexOf('a', -b.length), 0); +assert.equal(b.indexOf('a', NaN), 0); +assert.equal(b.indexOf('a', -Infinity), 0); +assert.equal(b.indexOf('a', Infinity), -1); +assert.equal(b.indexOf('bc'), 1); +assert.equal(b.indexOf('bc', 2), -1); +assert.equal(b.indexOf('bc', -1), -1); +assert.equal(b.indexOf('bc', -3), -1); +assert.equal(b.indexOf('bc', -5), 1); +assert.equal(b.indexOf('bc', NaN), 1); +assert.equal(b.indexOf('bc', -Infinity), 1); +assert.equal(b.indexOf('bc', Infinity), -1); +assert.equal(b.indexOf('f'), b.length - 1); +assert.equal(b.indexOf('z'), -1); +assert.equal(b.indexOf(''), -1); +assert.equal(b.indexOf('', 1), -1); +assert.equal(b.indexOf('', b.length + 1), -1); +assert.equal(b.indexOf('', Infinity), -1); +assert.equal(b.indexOf(buf_a), 0); +assert.equal(b.indexOf(buf_a, 1), -1); +assert.equal(b.indexOf(buf_a, -1), -1); +assert.equal(b.indexOf(buf_a, -4), -1); +assert.equal(b.indexOf(buf_a, -b.length), 0); +assert.equal(b.indexOf(buf_a, NaN), 0); +assert.equal(b.indexOf(buf_a, -Infinity), 0); +assert.equal(b.indexOf(buf_a, Infinity), -1); +assert.equal(b.indexOf(buf_bc), 1); +assert.equal(b.indexOf(buf_bc, 2), -1); +assert.equal(b.indexOf(buf_bc, -1), -1); +assert.equal(b.indexOf(buf_bc, -3), -1); +assert.equal(b.indexOf(buf_bc, -5), 1); +assert.equal(b.indexOf(buf_bc, NaN), 1); +assert.equal(b.indexOf(buf_bc, -Infinity), 1); +assert.equal(b.indexOf(buf_bc, Infinity), -1); +assert.equal(b.indexOf(buf_f), b.length - 1); +assert.equal(b.indexOf(buf_z), -1); +assert.equal(b.indexOf(buf_empty), -1); +assert.equal(b.indexOf(buf_empty, 1), -1); +assert.equal(b.indexOf(buf_empty, b.length + 1), -1); +assert.equal(b.indexOf(buf_empty, Infinity), -1); +assert.equal(b.indexOf(0x61), 0); +assert.equal(b.indexOf(0x61, 1), -1); +assert.equal(b.indexOf(0x61, -1), -1); +assert.equal(b.indexOf(0x61, -4), -1); +assert.equal(b.indexOf(0x61, -b.length), 0); +assert.equal(b.indexOf(0x61, NaN), 0); +assert.equal(b.indexOf(0x61, -Infinity), 0); +assert.equal(b.indexOf(0x61, Infinity), -1); +assert.equal(b.indexOf(0x0), -1); + +assert.throws(function() { + b.indexOf(function() { }); +}); +assert.throws(function() { + b.indexOf({}); +}); +assert.throws(function() { + b.indexOf([]); +}); + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-inspect.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-inspect.js new file mode 100644 index 0000000..719444f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer-inspect.js @@ -0,0 +1,41 @@ +'use strict'; +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false; +var Buffer = require('../../').Buffer; +var common = {}; +var assert = require('assert'); + +var util = require('util'); + +var buffer = require('../../'); + +buffer.INSPECT_MAX_BYTES = 2; + +var b = new Buffer(4); +b.fill('1234'); + +var s = new buffer.SlowBuffer(4); +s.fill('1234'); + +var expected = ''; + +assert.strictEqual(util.inspect(b), expected); +assert.strictEqual(util.inspect(s), expected); + +b = new Buffer(2); +b.fill('12'); + +s = new buffer.SlowBuffer(2); +s.fill('12'); + +expected = ''; + +assert.strictEqual(util.inspect(b), expected); +assert.strictEqual(util.inspect(s), expected); + +buffer.INSPECT_MAX_BYTES = Infinity; + +assert.doesNotThrow(function() { + assert.strictEqual(util.inspect(b), expected); + assert.strictEqual(util.inspect(s), expected); +}); + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer.js new file mode 100644 index 0000000..d6468f6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/node/test-buffer.js @@ -0,0 +1,1194 @@ +'use strict'; +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false; +var Buffer = require('../../').Buffer; +var common = {}; +var assert = require('assert'); + +var Buffer = require('../../').Buffer; +var SlowBuffer = require('../../').SlowBuffer; + +// counter to ensure unique value is always copied +var cntr = 0; + +var b = Buffer(1024); // safe constructor + +// console.log('b.length == %d', b.length); +assert.strictEqual(1024, b.length); + +b[0] = 255; +assert.strictEqual(b[0], 255); + +for (var i = 0; i < 1024; i++) { + b[i] = i % 256; +} + +for (var i = 0; i < 1024; i++) { + assert.strictEqual(i % 256, b[i]); +} + +var c = new Buffer(512); +// console.log('c.length == %d', c.length); +assert.strictEqual(512, c.length); + +// First check Buffer#fill() works as expected. + +assert.throws(function() { + Buffer(8).fill('a', -1); +}); + +assert.throws(function() { + Buffer(8).fill('a', 0, 9); +}); + +// Make sure this doesn't hang indefinitely. +Buffer(8).fill(''); + +var buf = new Buffer(64); +buf.fill(10); +for (var i = 0; i < buf.length; i++) + assert.equal(buf[i], 10); + +buf.fill(11, 0, buf.length >> 1); +for (var i = 0; i < buf.length >> 1; i++) + assert.equal(buf[i], 11); +for (var i = (buf.length >> 1) + 1; i < buf.length; i++) + assert.equal(buf[i], 10); + +buf.fill('h'); +for (var i = 0; i < buf.length; i++) + assert.equal('h'.charCodeAt(0), buf[i]); + +buf.fill(0); +for (var i = 0; i < buf.length; i++) + assert.equal(0, buf[i]); + +buf.fill(null); +for (var i = 0; i < buf.length; i++) + assert.equal(0, buf[i]); + +buf.fill(1, 16, 32); +for (var i = 0; i < 16; i++) + assert.equal(0, buf[i]); +for (; i < 32; i++) + assert.equal(1, buf[i]); +for (; i < buf.length; i++) + assert.equal(0, buf[i]); + +var buf = new Buffer(10); +buf.fill('abc'); +assert.equal(buf.toString(), 'abcabcabca'); +buf.fill('է'); +assert.equal(buf.toString(), 'էէէէէ'); + +// copy 512 bytes, from 0 to 512. +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c, 0, 0, 512); +// console.log('copied %d bytes from b into c', copied); +assert.strictEqual(512, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); +} + +// copy c into b, without specifying sourceEnd +b.fill(++cntr); +c.fill(++cntr); +var copied = c.copy(b, 0, 0); +// console.log('copied %d bytes from c into b w/o sourceEnd', copied); +assert.strictEqual(c.length, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(c[i], b[i]); +} + +// copy c into b, without specifying sourceStart +b.fill(++cntr); +c.fill(++cntr); +var copied = c.copy(b, 0); +// console.log('copied %d bytes from c into b w/o sourceStart', copied); +assert.strictEqual(c.length, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(c[i], b[i]); +} + +// copy longer buffer b to shorter c without targetStart +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c); +// console.log('copied %d bytes from b into c w/o targetStart', copied); +assert.strictEqual(c.length, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); +} + +// copy starting near end of b to c +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c, 0, b.length - Math.floor(c.length / 2)); +// console.log('copied %d bytes from end of b into beginning of c', copied); +assert.strictEqual(Math.floor(c.length / 2), copied); +for (var i = 0; i < Math.floor(c.length / 2); i++) { + assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]); +} +for (var i = Math.floor(c.length / 2) + 1; i < c.length; i++) { + assert.strictEqual(c[c.length - 1], c[i]); +} + +// try to copy 513 bytes, and check we don't overrun c +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c, 0, 0, 513); +// console.log('copied %d bytes from b trying to overrun c', copied); +assert.strictEqual(c.length, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); +} + +// copy 768 bytes from b into b +b.fill(++cntr); +b.fill(++cntr, 256); +var copied = b.copy(b, 0, 256, 1024); +// console.log('copied %d bytes from b into b', copied); +assert.strictEqual(768, copied); +for (var i = 0; i < b.length; i++) { + assert.strictEqual(cntr, b[i]); +} + +// copy string longer than buffer length (failure will segfault) +var bb = new Buffer(10); +bb.fill('hello crazy world'); + + +var caught_error = null; + +// try to copy from before the beginning of b +caught_error = null; +try { + var copied = b.copy(c, 0, 100, 10); +} catch (err) { + caught_error = err; +} + +// copy throws at negative sourceStart +assert.throws(function() { + Buffer(5).copy(Buffer(5), 0, -1); +}, RangeError); + +// check sourceEnd resets to targetEnd if former is greater than the latter +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c, 0, 0, 1025); +// console.log('copied %d bytes from b into c', copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); +} + +// throw with negative sourceEnd +// console.log('test copy at negative sourceEnd'); +assert.throws(function() { + b.copy(c, 0, 0, -1); +}, RangeError); + +// when sourceStart is greater than sourceEnd, zero copied +assert.equal(b.copy(c, 0, 100, 10), 0); + +// when targetStart > targetLength, zero copied +assert.equal(b.copy(c, 512, 0, 10), 0); + +var caught_error; + +// invalid encoding for Buffer.toString +caught_error = null; +try { + var copied = b.toString('invalid'); +} catch (err) { + caught_error = err; +} +assert.strictEqual('Unknown encoding: invalid', caught_error.message); + +// invalid encoding for Buffer.write +caught_error = null; +try { + var copied = b.write('test string', 0, 5, 'invalid'); +} catch (err) { + caught_error = err; +} +assert.strictEqual('Unknown encoding: invalid', caught_error.message); + +// try to create 0-length buffers +new Buffer(''); +new Buffer('', 'ascii'); +new Buffer('', 'binary'); +new Buffer(0); + +// try to write a 0-length string beyond the end of b +assert.throws(function() { + b.write('', 2048); +}, RangeError); + +// throw when writing to negative offset +assert.throws(function() { + b.write('a', -1); +}, RangeError); + +// throw when writing past bounds from the pool +assert.throws(function() { + b.write('a', 2048); +}, RangeError); + +// throw when writing to negative offset +assert.throws(function() { + b.write('a', -1); +}, RangeError); + +// try to copy 0 bytes worth of data into an empty buffer +b.copy(new Buffer(0), 0, 0, 0); + +// try to copy 0 bytes past the end of the target buffer +b.copy(new Buffer(0), 1, 1, 1); +b.copy(new Buffer(1), 1, 1, 1); + +// try to copy 0 bytes from past the end of the source buffer +b.copy(new Buffer(1), 0, 2048, 2048); + +// try to toString() a 0-length slice of a buffer, both within and without the +// valid buffer range +assert.equal(new Buffer('abc').toString('ascii', 0, 0), ''); +assert.equal(new Buffer('abc').toString('ascii', -100, -100), ''); +assert.equal(new Buffer('abc').toString('ascii', 100, 100), ''); + +// try toString() with a object as a encoding +assert.equal(new Buffer('abc').toString({toString: function() { + return 'ascii'; +}}), 'abc'); + +// testing for smart defaults and ability to pass string values as offset +var writeTest = new Buffer('abcdes'); +writeTest.write('n', 'ascii'); +writeTest.write('o', 'ascii', '1'); +writeTest.write('d', '2', 'ascii'); +writeTest.write('e', 3, 'ascii'); +writeTest.write('j', 'ascii', 4); +assert.equal(writeTest.toString(), 'nodejs'); + +// ASCII slice test + +var asciiString = 'hello world'; +var offset = 100; + +for (var i = 0; i < asciiString.length; i++) { + b[i] = asciiString.charCodeAt(i); +} +var asciiSlice = b.toString('ascii', 0, asciiString.length); +assert.equal(asciiString, asciiSlice); + +var written = b.write(asciiString, offset, 'ascii'); +assert.equal(asciiString.length, written); +var asciiSlice = b.toString('ascii', offset, offset + asciiString.length); +assert.equal(asciiString, asciiSlice); + +var sliceA = b.slice(offset, offset + asciiString.length); +var sliceB = b.slice(offset, offset + asciiString.length); +for (var i = 0; i < asciiString.length; i++) { + assert.equal(sliceA[i], sliceB[i]); +} + +// UTF-8 slice test + +var utf8String = '¡hέlló wôrld!'; +var offset = 100; + +b.write(utf8String, 0, Buffer.byteLength(utf8String), 'utf8'); +var utf8Slice = b.toString('utf8', 0, Buffer.byteLength(utf8String)); +assert.equal(utf8String, utf8Slice); + +var written = b.write(utf8String, offset, 'utf8'); +assert.equal(Buffer.byteLength(utf8String), written); +utf8Slice = b.toString('utf8', offset, offset + Buffer.byteLength(utf8String)); +assert.equal(utf8String, utf8Slice); + +var sliceA = b.slice(offset, offset + Buffer.byteLength(utf8String)); +var sliceB = b.slice(offset, offset + Buffer.byteLength(utf8String)); +for (var i = 0; i < Buffer.byteLength(utf8String); i++) { + assert.equal(sliceA[i], sliceB[i]); +} + +var slice = b.slice(100, 150); +assert.equal(50, slice.length); +for (var i = 0; i < 50; i++) { + assert.equal(b[100 + i], slice[i]); +} + + +// make sure only top level parent propagates from allocPool +var b = new Buffer(5); +var c = b.slice(0, 4); +var d = c.slice(0, 2); +assert.equal(b.parent, c.parent); +assert.equal(b.parent, d.parent); + +// also from a non-pooled instance +var b = new SlowBuffer(5); +var c = b.slice(0, 4); +var d = c.slice(0, 2); + + +// Bug regression test +var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語 +var buffer = new Buffer(32); +var size = buffer.write(testValue, 0, 'utf8'); +// console.log('bytes written to buffer: ' + size); +var slice = buffer.toString('utf8', 0, size); +assert.equal(slice, testValue); + + +// Test triple slice +var a = new Buffer(8); +for (var i = 0; i < 8; i++) a[i] = i; +var b = a.slice(4, 8); +assert.equal(4, b[0]); +assert.equal(5, b[1]); +assert.equal(6, b[2]); +assert.equal(7, b[3]); +var c = b.slice(2, 4); +assert.equal(6, c[0]); +assert.equal(7, c[1]); + + +var d = new Buffer([23, 42, 255]); +assert.equal(d.length, 3); +assert.equal(d[0], 23); +assert.equal(d[1], 42); +assert.equal(d[2], 255); +assert.deepEqual(d, new Buffer(d)); + +var e = new Buffer('über'); +// console.error('uber: \'%s\'', e.toString()); +assert.deepEqual(e, new Buffer([195, 188, 98, 101, 114])); + +var f = new Buffer('über', 'ascii'); +// console.error('f.length: %d (should be 4)', f.length); +assert.deepEqual(f, new Buffer([252, 98, 101, 114])); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + var f = new Buffer('über', encoding); +// console.error('f.length: %d (should be 8)', f.length); + assert.deepEqual(f, new Buffer([252, 0, 98, 0, 101, 0, 114, 0])); + + var f = new Buffer('привет', encoding); +// console.error('f.length: %d (should be 12)', f.length); + assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4])); + assert.equal(f.toString(encoding), 'привет'); + + var f = new Buffer([0, 0, 0, 0, 0]); + assert.equal(f.length, 5); + var size = f.write('あいうえお', encoding); +// console.error('bytes written to buffer: %d (should be 4)', size); + assert.equal(size, 4); + assert.deepEqual(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00])); +}); + +var f = new Buffer('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D) +assert.equal(f.length, 4); +assert.deepEqual(f, new Buffer('3DD84DDC', 'hex')); + + +var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; +var g = new Buffer(arrayIsh); +assert.deepEqual(g, new Buffer([0, 1, 2, 3])); +var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4}; +g = new Buffer(strArrayIsh); +assert.deepEqual(g, new Buffer([0, 1, 2, 3])); + + +// +// Test toString('base64') +// +assert.equal('TWFu', (new Buffer('Man')).toString('base64')); + +// test that regular and URL-safe base64 both work +var expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff]; +assert.deepEqual(Buffer('//++/++/++//', 'base64'), Buffer(expected)); +assert.deepEqual(Buffer('__--_--_--__', 'base64'), Buffer(expected)); + +// big example +var quote = 'Man is distinguished, not only by his reason, but by this ' + + 'singular passion from other animals, which is a lust ' + + 'of the mind, that by a perseverance of delight in the continued ' + + 'and indefatigable generation of knowledge, exceeds the short ' + + 'vehemence of any carnal pleasure.'; +var expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24s' + + 'IGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltY' + + 'WxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZX' + + 'JzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmR' + + 'lZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo' + + 'ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4='; +assert.equal(expected, (new Buffer(quote)).toString('base64')); + + +b = new Buffer(1024); +var bytesWritten = b.write(expected, 0, 'base64'); +assert.equal(quote.length, bytesWritten); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder ignores whitespace +var expectedWhite = expected.slice(0, 60) + ' \n' + + expected.slice(60, 120) + ' \n' + + expected.slice(120, 180) + ' \n' + + expected.slice(180, 240) + ' \n' + + expected.slice(240, 300) + '\n' + + expected.slice(300, 360) + '\n'; +b = new Buffer(1024); +bytesWritten = b.write(expectedWhite, 0, 'base64'); +assert.equal(quote.length, bytesWritten); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder on the constructor works +// even in the presence of whitespace. +b = new Buffer(expectedWhite, 'base64'); +assert.equal(quote.length, b.length); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder ignores illegal chars +var expectedIllegal = expected.slice(0, 60) + ' \x80' + + expected.slice(60, 120) + ' \xff' + + expected.slice(120, 180) + ' \x00' + + expected.slice(180, 240) + ' \x98' + + expected.slice(240, 300) + '\x03' + + expected.slice(300, 360); +b = new Buffer(expectedIllegal, 'base64'); +assert.equal(quote.length, b.length); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + + +assert.equal(new Buffer('', 'base64').toString(), ''); +assert.equal(new Buffer('K', 'base64').toString(), ''); + +// multiple-of-4 with padding +assert.equal(new Buffer('Kg==', 'base64').toString(), '*'); +assert.equal(new Buffer('Kio=', 'base64').toString(), '**'); +assert.equal(new Buffer('Kioq', 'base64').toString(), '***'); +assert.equal(new Buffer('KioqKg==', 'base64').toString(), '****'); +assert.equal(new Buffer('KioqKio=', 'base64').toString(), '*****'); +assert.equal(new Buffer('KioqKioq', 'base64').toString(), '******'); +assert.equal(new Buffer('KioqKioqKg==', 'base64').toString(), '*******'); +assert.equal(new Buffer('KioqKioqKio=', 'base64').toString(), '********'); +assert.equal(new Buffer('KioqKioqKioq', 'base64').toString(), '*********'); +assert.equal(new Buffer('KioqKioqKioqKg==', 'base64').toString(), + '**********'); +assert.equal(new Buffer('KioqKioqKioqKio=', 'base64').toString(), + '***********'); +assert.equal(new Buffer('KioqKioqKioqKioq', 'base64').toString(), + '************'); +assert.equal(new Buffer('KioqKioqKioqKioqKg==', 'base64').toString(), + '*************'); +assert.equal(new Buffer('KioqKioqKioqKioqKio=', 'base64').toString(), + '**************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioq', 'base64').toString(), + '***************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKg==', 'base64').toString(), + '****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKio=', 'base64').toString(), + '*****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioq', 'base64').toString(), + '******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(), + '*******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(), + '********************'); + +// no padding, not a multiple of 4 +assert.equal(new Buffer('Kg', 'base64').toString(), '*'); +assert.equal(new Buffer('Kio', 'base64').toString(), '**'); +assert.equal(new Buffer('KioqKg', 'base64').toString(), '****'); +assert.equal(new Buffer('KioqKio', 'base64').toString(), '*****'); +assert.equal(new Buffer('KioqKioqKg', 'base64').toString(), '*******'); +assert.equal(new Buffer('KioqKioqKio', 'base64').toString(), '********'); +assert.equal(new Buffer('KioqKioqKioqKg', 'base64').toString(), '**********'); +assert.equal(new Buffer('KioqKioqKioqKio', 'base64').toString(), '***********'); +assert.equal(new Buffer('KioqKioqKioqKioqKg', 'base64').toString(), + '*************'); +assert.equal(new Buffer('KioqKioqKioqKioqKio', 'base64').toString(), + '**************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKg', 'base64').toString(), + '****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKio', 'base64').toString(), + '*****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(), + '*******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(), + '********************'); + +// handle padding graciously, multiple-of-4 or not +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', + 'base64').length, 32); +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', + 'base64').length, 32); +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', + 'base64').length, 32); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', + 'base64').length, 31); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', + 'base64').length, 31); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', + 'base64').length, 31); + +// This string encodes single '.' character in UTF-16 +var dot = new Buffer('//4uAA==', 'base64'); +assert.equal(dot[0], 0xff); +assert.equal(dot[1], 0xfe); +assert.equal(dot[2], 0x2e); +assert.equal(dot[3], 0x00); +assert.equal(dot.toString('base64'), '//4uAA=='); + +// Writing base64 at a position > 0 should not mangle the result. +// +// https://github.com/joyent/node/issues/402 +var segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh']; +var buf = new Buffer(64); +var pos = 0; + +for (var i = 0; i < segments.length; ++i) { + pos += b.write(segments[i], pos, 'base64'); +} +assert.equal(b.toString('binary', 0, pos), 'Madness?! This is node.js!'); + +// Creating buffers larger than pool size. +var l = Buffer.poolSize + 5; +var s = ''; +for (i = 0; i < l; i++) { + s += 'h'; +} + +var b = new Buffer(s); + +for (i = 0; i < l; i++) { + assert.equal('h'.charCodeAt(0), b[i]); +} + +var sb = b.toString(); +assert.equal(sb.length, s.length); +assert.equal(sb, s); + + +// Single argument slice +b = new Buffer('abcde'); +assert.equal('bcde', b.slice(1).toString()); + +// slice(0,0).length === 0 +assert.equal(0, Buffer('hello').slice(0, 0).length); + +// test hex toString +// console.log('Create hex string from buffer'); +var hexb = new Buffer(256); +for (var i = 0; i < 256; i++) { + hexb[i] = i; +} +var hexStr = hexb.toString('hex'); +assert.equal(hexStr, + '000102030405060708090a0b0c0d0e0f' + + '101112131415161718191a1b1c1d1e1f' + + '202122232425262728292a2b2c2d2e2f' + + '303132333435363738393a3b3c3d3e3f' + + '404142434445464748494a4b4c4d4e4f' + + '505152535455565758595a5b5c5d5e5f' + + '606162636465666768696a6b6c6d6e6f' + + '707172737475767778797a7b7c7d7e7f' + + '808182838485868788898a8b8c8d8e8f' + + '909192939495969798999a9b9c9d9e9f' + + 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' + + 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' + + 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' + + 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' + + 'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' + + 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'); + +// console.log('Create buffer from hex string'); +var hexb2 = new Buffer(hexStr, 'hex'); +for (var i = 0; i < 256; i++) { + assert.equal(hexb2[i], hexb[i]); +} + +// test an invalid slice end. +// console.log('Try to slice off the end of the buffer'); +var b = new Buffer([1, 2, 3, 4, 5]); +var b2 = b.toString('hex', 1, 10000); +var b3 = b.toString('hex', 1, 5); +var b4 = b.toString('hex', 1); +assert.equal(b2, b3); +assert.equal(b2, b4); + + +function buildBuffer(data) { + if (Array.isArray(data)) { + var buffer = new Buffer(data.length); + data.forEach(function(v, k) { + buffer[k] = v; + }); + return buffer; + } + return null; +} + +var x = buildBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]); + +// console.log(x.inspect()); +assert.equal('', x.inspect()); + +var z = x.slice(4); +// console.log(z.inspect()); +// console.log(z.length); +assert.equal(5, z.length); +assert.equal(0x6f, z[0]); +assert.equal(0xa3, z[1]); +assert.equal(0x62, z[2]); +assert.equal(0x61, z[3]); +assert.equal(0x72, z[4]); + +var z = x.slice(0); +// console.log(z.inspect()); +// console.log(z.length); +assert.equal(z.length, x.length); + +var z = x.slice(0, 4); +// console.log(z.inspect()); +// console.log(z.length); +assert.equal(4, z.length); +assert.equal(0x81, z[0]); +assert.equal(0xa3, z[1]); + +var z = x.slice(0, 9); +// console.log(z.inspect()); +// console.log(z.length); +assert.equal(9, z.length); + +var z = x.slice(1, 4); +// console.log(z.inspect()); +// console.log(z.length); +assert.equal(3, z.length); +assert.equal(0xa3, z[0]); + +var z = x.slice(2, 4); +// console.log(z.inspect()); +// console.log(z.length); +assert.equal(2, z.length); +assert.equal(0x66, z[0]); +assert.equal(0x6f, z[1]); + +assert.equal(0, Buffer('hello').slice(0, 0).length); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + var b = new Buffer(10); + b.write('あいうえお', encoding); + assert.equal(b.toString(encoding), 'あいうえお'); +}); + +// Binary encoding should write only one byte per character. +var b = Buffer([0xde, 0xad, 0xbe, 0xef]); +var s = String.fromCharCode(0xffff); +b.write(s, 0, 'binary'); +assert.equal(0xff, b[0]); +assert.equal(0xad, b[1]); +assert.equal(0xbe, b[2]); +assert.equal(0xef, b[3]); +s = String.fromCharCode(0xaaee); +b.write(s, 0, 'binary'); +assert.equal(0xee, b[0]); +assert.equal(0xad, b[1]); +assert.equal(0xbe, b[2]); +assert.equal(0xef, b[3]); + +// #1210 Test UTF-8 string includes null character +var buf = new Buffer('\0'); +assert.equal(buf.length, 1); +buf = new Buffer('\0\0'); +assert.equal(buf.length, 2); + +buf = new Buffer(2); +var written = buf.write(''); // 0byte +assert.equal(written, 0); +written = buf.write('\0'); // 1byte (v8 adds null terminator) +assert.equal(written, 1); +written = buf.write('a\0'); // 1byte * 2 +assert.equal(written, 2); +written = buf.write('あ'); // 3bytes +assert.equal(written, 0); +written = buf.write('\0あ'); // 1byte + 3bytes +assert.equal(written, 1); +written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes +assert.equal(written, 2); + +buf = new Buffer(10); +written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator) +assert.equal(written, 9); +written = buf.write('あいう\0'); // 3bytes * 3 + 1byte +assert.equal(written, 10); + +// #243 Test write() with maxLength +var buf = new Buffer(4); +buf.fill(0xFF); +var written = buf.write('abcd', 1, 2, 'utf8'); +// console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0xFF); + +buf.fill(0xFF); +written = buf.write('abcd', 1, 4); +// console.log(buf); +assert.equal(written, 3); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0x63); + +buf.fill(0xFF); +written = buf.write('abcd', 'utf8', 1, 2); // legacy style +// console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0xFF); + +buf.fill(0xFF); +written = buf.write('abcdef', 1, 2, 'hex'); +// console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0xAB); +assert.equal(buf[2], 0xCD); +assert.equal(buf[3], 0xFF); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + buf.fill(0xFF); + written = buf.write('abcd', 0, 2, encoding); +// console.log(buf); + assert.equal(written, 2); + assert.equal(buf[0], 0x61); + assert.equal(buf[1], 0x00); + assert.equal(buf[2], 0xFF); + assert.equal(buf[3], 0xFF); +}); + +// test offset returns are correct +var b = new Buffer(16); +assert.equal(4, b.writeUInt32LE(0, 0)); +assert.equal(6, b.writeUInt16LE(0, 4)); +assert.equal(7, b.writeUInt8(0, 6)); +assert.equal(8, b.writeInt8(0, 7)); +assert.equal(16, b.writeDoubleLE(0, 8)); + +// test unmatched surrogates not producing invalid utf8 output +// ef bf bd = utf-8 representation of unicode replacement character +// see https://codereview.chromium.org/121173009/ +buf = new Buffer('ab\ud800cd', 'utf8'); +assert.equal(buf[0], 0x61); +assert.equal(buf[1], 0x62); +assert.equal(buf[2], 0xef); +assert.equal(buf[3], 0xbf); +assert.equal(buf[4], 0xbd); +assert.equal(buf[5], 0x63); +assert.equal(buf[6], 0x64); + +// test for buffer overrun +buf = new Buffer([0, 0, 0, 0, 0]); // length: 5 +var sub = buf.slice(0, 4); // length: 4 +written = sub.write('12345', 'binary'); +assert.equal(written, 4); +assert.equal(buf[4], 0); + +// Check for fractional length args, junk length args, etc. +// https://github.com/joyent/node/issues/1758 + +// Call .fill() first, stops valgrind warning about uninitialized memory reads. +Buffer(3.3).fill().toString(); // throws bad argument error in commit 43cb4ec +assert.equal(Buffer(-1).length, 0); +assert.equal(Buffer(NaN).length, 0); +assert.equal(Buffer(3.3).length, 3); +assert.equal(Buffer({length: 3.3}).length, 3); +assert.equal(Buffer({length: 'BAM'}).length, 0); + +// Make sure that strings are not coerced to numbers. +assert.equal(Buffer('99').length, 2); +assert.equal(Buffer('13.37').length, 5); + +// Ensure that the length argument is respected. +'ascii utf8 hex base64 binary'.split(' ').forEach(function(enc) { + assert.equal(Buffer(1).write('aaaaaa', 0, 1, enc), 1); +}); + +// Regression test, guard against buffer overrun in the base64 decoder. +var a = Buffer(3); +var b = Buffer('xxx'); +a.write('aaaaaaaa', 'base64'); +assert.equal(b.toString(), 'xxx'); + +// issue GH-3416 +Buffer(Buffer(0), 0, 0); + +[ 'hex', + 'utf8', + 'utf-8', + 'ascii', + 'binary', + 'base64', + 'ucs2', + 'ucs-2', + 'utf16le', + 'utf-16le' ].forEach(function(enc) { + assert.equal(Buffer.isEncoding(enc), true); + }); + +[ 'utf9', + 'utf-7', + 'Unicode-FTW', + 'new gnu gun' ].forEach(function(enc) { + assert.equal(Buffer.isEncoding(enc), false); + }); + + +// GH-5110 +(function() { + var buffer = new Buffer('test'), + string = JSON.stringify(buffer); + + assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); + + assert.deepEqual(buffer, JSON.parse(string, function(key, value) { + return value && value.type === 'Buffer' + ? new Buffer(value.data) + : value; + })); +})(); + +// issue GH-7849 +(function() { + var buf = new Buffer('test'); + var json = JSON.stringify(buf); + var obj = JSON.parse(json); + var copy = new Buffer(obj); + + assert(buf.equals(copy)); +})(); + +// issue GH-4331 +assert.throws(function() { + new Buffer(0xFFFFFFFF); +}, RangeError); +assert.throws(function() { + new Buffer(0xFFFFFFFFF); +}, RangeError); + + +// attempt to overflow buffers, similar to previous bug in array buffers +assert.throws(function() { + var buf = new Buffer(8); + buf.readFloatLE(0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0.0, 0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.readFloatLE(0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0.0, 0xffffffff); +}, RangeError); + + +// ensure negative values can't get past offset +assert.throws(function() { + var buf = new Buffer(8); + buf.readFloatLE(-1); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0.0, -1); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.readFloatLE(-1); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0.0, -1); +}, RangeError); + +// offset checks +var buf = new Buffer(0); + +assert.throws(function() { buf.readUInt8(0); }, RangeError); +assert.throws(function() { buf.readInt8(0); }, RangeError); + +var buf = new Buffer([0xFF]); + +assert.equal(buf.readUInt8(0), 255); +assert.equal(buf.readInt8(0), -1); + +[16, 32].forEach(function(bits) { + var buf = new Buffer(bits / 8 - 1); + + assert.throws(function() { buf['readUInt' + bits + 'BE'](0); }, + RangeError, + 'readUInt' + bits + 'BE'); + + assert.throws(function() { buf['readUInt' + bits + 'LE'](0); }, + RangeError, + 'readUInt' + bits + 'LE'); + + assert.throws(function() { buf['readInt' + bits + 'BE'](0); }, + RangeError, + 'readInt' + bits + 'BE()'); + + assert.throws(function() { buf['readInt' + bits + 'LE'](0); }, + RangeError, + 'readInt' + bits + 'LE()'); +}); + +[16, 32].forEach(function(bits) { + var buf = new Buffer([0xFF, 0xFF, 0xFF, 0xFF]); + + assert.equal(buf['readUInt' + bits + 'BE'](0), + (0xFFFFFFFF >>> (32 - bits))); + + assert.equal(buf['readUInt' + bits + 'LE'](0), + (0xFFFFFFFF >>> (32 - bits))); + + assert.equal(buf['readInt' + bits + 'BE'](0), + (0xFFFFFFFF >> (32 - bits))); + + assert.equal(buf['readInt' + bits + 'LE'](0), + (0xFFFFFFFF >> (32 - bits))); +}); + +// test for common read(U)IntLE/BE +(function() { + var buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); + + assert.equal(buf.readUIntLE(0, 1), 0x01); + assert.equal(buf.readUIntBE(0, 1), 0x01); + assert.equal(buf.readUIntLE(0, 3), 0x030201); + assert.equal(buf.readUIntBE(0, 3), 0x010203); + assert.equal(buf.readUIntLE(0, 5), 0x0504030201); + assert.equal(buf.readUIntBE(0, 5), 0x0102030405); + assert.equal(buf.readUIntLE(0, 6), 0x060504030201); + assert.equal(buf.readUIntBE(0, 6), 0x010203040506); + assert.equal(buf.readIntLE(0, 1), 0x01); + assert.equal(buf.readIntBE(0, 1), 0x01); + assert.equal(buf.readIntLE(0, 3), 0x030201); + assert.equal(buf.readIntBE(0, 3), 0x010203); + assert.equal(buf.readIntLE(0, 5), 0x0504030201); + assert.equal(buf.readIntBE(0, 5), 0x0102030405); + assert.equal(buf.readIntLE(0, 6), 0x060504030201); + assert.equal(buf.readIntBE(0, 6), 0x010203040506); +})(); + +// test for common write(U)IntLE/BE +(function() { + var buf = new Buffer(3); + buf.writeUIntLE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); + assert.equal(buf.readUIntLE(0, 3), 0x123456); + + buf = new Buffer(3); + buf.writeUIntBE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); + assert.equal(buf.readUIntBE(0, 3), 0x123456); + + buf = new Buffer(3); + buf.writeIntLE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); + assert.equal(buf.readIntLE(0, 3), 0x123456); + + buf = new Buffer(3); + buf.writeIntBE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); + assert.equal(buf.readIntBE(0, 3), 0x123456); + + buf = new Buffer(3); + buf.writeIntLE(-0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]); + assert.equal(buf.readIntLE(0, 3), -0x123456); + + buf = new Buffer(3); + buf.writeIntBE(-0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]); + assert.equal(buf.readIntBE(0, 3), -0x123456); + + buf = new Buffer(5); + buf.writeUIntLE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); + assert.equal(buf.readUIntLE(0, 5), 0x1234567890); + + buf = new Buffer(5); + buf.writeUIntBE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); + assert.equal(buf.readUIntBE(0, 5), 0x1234567890); + + buf = new Buffer(5); + buf.writeIntLE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); + assert.equal(buf.readIntLE(0, 5), 0x1234567890); + + buf = new Buffer(5); + buf.writeIntBE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); + assert.equal(buf.readIntBE(0, 5), 0x1234567890); + + buf = new Buffer(5); + buf.writeIntLE(-0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]); + assert.equal(buf.readIntLE(0, 5), -0x1234567890); + + buf = new Buffer(5); + buf.writeIntBE(-0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]); + assert.equal(buf.readIntBE(0, 5), -0x1234567890); +})(); + +// test Buffer slice +(function() { + var buf = new Buffer('0123456789'); + assert.equal(buf.slice(-10, 10), '0123456789'); + assert.equal(buf.slice(-20, 10), '0123456789'); + assert.equal(buf.slice(-20, -10), ''); + assert.equal(buf.slice(0, -1), '012345678'); + assert.equal(buf.slice(2, -2), '234567'); + assert.equal(buf.slice(0, 65536), '0123456789'); + assert.equal(buf.slice(65536, 0), ''); + for (var i = 0, s = buf.toString(); i < buf.length; ++i) { + assert.equal(buf.slice(-i), s.slice(-i)); + assert.equal(buf.slice(0, -i), s.slice(0, -i)); + } + // try to slice a zero length Buffer + // see https://github.com/joyent/node/issues/5881 + SlowBuffer(0).slice(0, 1); +})(); + +// Regression test for #5482: should throw but not assert in C++ land. +assert.throws(function() { + Buffer('', 'buffer'); +}, TypeError); + +// Regression test for #6111. Constructing a buffer from another buffer +// should a) work, and b) not corrupt the source buffer. +(function() { + var a = [0]; + for (var i = 0; i < 7; ++i) a = a.concat(a); + a = a.map(function(_, i) { return i; }); + var b = Buffer(a); + var c = Buffer(b); + assert.equal(b.length, a.length); + assert.equal(c.length, a.length); + for (var i = 0, k = a.length; i < k; ++i) { + assert.equal(a[i], i); + assert.equal(b[i], i); + assert.equal(c[i], i); + } +})(); + + +assert.throws(function() { + new Buffer((-1 >>> 0) + 1); +}, RangeError); + +assert.throws(function() { + new SlowBuffer((-1 >>> 0) + 1); +}, RangeError); + +if (common.hasCrypto) { + // Test truncation after decode + // var crypto = require('crypto'); + + var b1 = new Buffer('YW55=======', 'base64'); + var b2 = new Buffer('YW55', 'base64'); + + assert.equal( + 1 /*crypto.createHash('sha1').update(b1).digest('hex')*/, + 1 /*crypto.createHash('sha1').update(b2).digest('hex')*/ + ); +} else { +// console.log('1..0 # Skipped: missing crypto'); +} + +// Test Compare +var b = new Buffer(1).fill('a'); +var c = new Buffer(1).fill('c'); +var d = new Buffer(2).fill('aa'); + +assert.equal(b.compare(c), -1); +assert.equal(c.compare(d), 1); +assert.equal(d.compare(b), 1); +assert.equal(b.compare(d), -1); +assert.equal(b.compare(b), 0); + +assert.equal(Buffer.compare(b, c), -1); +assert.equal(Buffer.compare(c, d), 1); +assert.equal(Buffer.compare(d, b), 1); +assert.equal(Buffer.compare(b, d), -1); +assert.equal(Buffer.compare(c, c), 0); + + +assert.throws(function() { + var b = new Buffer(1); + Buffer.compare(b, 'abc'); +}); + +assert.throws(function() { + var b = new Buffer(1); + Buffer.compare('abc', b); +}); + +assert.throws(function() { + var b = new Buffer(1); + b.compare('abc'); +}); + +// Test Equals +var b = new Buffer(5).fill('abcdf'); +var c = new Buffer(5).fill('abcdf'); +var d = new Buffer(5).fill('abcde'); +var e = new Buffer(6).fill('abcdef'); + +assert.ok(b.equals(c)); +assert.ok(!c.equals(d)); +assert.ok(!d.equals(e)); +assert.ok(d.equals(d)); + +assert.throws(function() { + var b = new Buffer(1); + b.equals('abc'); +}); + +// Regression test for https://github.com/nodejs/io.js/issues/649. +assert.throws(function() { Buffer(1422561062959).toString('utf8'); }); + +var ps = Buffer.poolSize; +Buffer.poolSize = 0; +assert.equal(Buffer(1).parent, undefined); +Buffer.poolSize = ps; + +// Test Buffer.copy() segfault +assert.throws(function() { + Buffer(10).copy(); +}); + +assert.throws(function() { + new Buffer(); +}, /must start with number, buffer, array or string/); + +assert.throws(function() { + new Buffer(null); +}, /must start with number, buffer, array or string/); + diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/slice.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/slice.js new file mode 100644 index 0000000..25c111c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/slice.js @@ -0,0 +1,37 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('modifying buffer created by .slice() modifies original memory', function (t) { + if (!B.TYPED_ARRAY_SUPPORT) return t.end() + + var buf1 = new B(26) + for (var i = 0; i < 26; i++) { + buf1[i] = i + 97 // 97 is ASCII a + } + + var buf2 = buf1.slice(0, 3) + t.equal(buf2.toString('ascii', 0, buf2.length), 'abc') + + buf2[0] = '!'.charCodeAt(0) + t.equal(buf1.toString('ascii', 0, buf2.length), '!bc') + + t.end() +}) + +test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) { + if (!B.TYPED_ARRAY_SUPPORT) return t.end() + + var buf1 = new B(26) + for (var i = 0; i < 26; i++) { + buf1[i] = i + 97 // 97 is ASCII a + } + + var buf2 = buf1.slice(0, 3) + t.equal(buf2.toString('ascii', 0, buf2.length), 'abc') + + buf1[0] = '!'.charCodeAt(0) + t.equal(buf2.toString('ascii', 0, buf2.length), '!bc') + + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/static.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/static.js new file mode 100644 index 0000000..4de900b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/static.js @@ -0,0 +1,17 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('Buffer.isEncoding', function (t) { + t.equal(B.isEncoding('HEX'), true) + t.equal(B.isEncoding('hex'), true) + t.equal(B.isEncoding('bad'), false) + t.end() +}) + +test('Buffer.isBuffer', function (t) { + t.equal(B.isBuffer(new B('hey', 'utf8')), true) + t.equal(B.isBuffer(new B([1, 2, 3], 'utf8')), true) + t.equal(B.isBuffer('hey'), false) + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/to-string.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/to-string.js new file mode 100644 index 0000000..2950d4d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/to-string.js @@ -0,0 +1,233 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('utf8 buffer to base64', function (t) { + t.equal( + new B('Ձאab', 'utf8').toString('base64'), + '1YHXkGFi' + ) + t.end() +}) + +test('utf8 buffer to hex', function (t) { + t.equal( + new B('Ձאab', 'utf8').toString('hex'), + 'd581d7906162' + ) + t.end() +}) + +test('utf8 to utf8', function (t) { + t.equal( + new B('öäüõÖÄÜÕ', 'utf8').toString('utf8'), + 'öäüõÖÄÜÕ' + ) + t.end() +}) + +test('utf16le to utf16', function (t) { + t.equal( + new B(new B('abcd', 'utf8').toString('utf16le'), 'utf16le').toString('utf8'), + 'abcd' + ) + t.end() +}) + +test('utf16le to hex', function (t) { + t.equal( + new B('abcd', 'utf16le').toString('hex'), + '6100620063006400' + ) + t.end() +}) + +test('ascii buffer to base64', function (t) { + t.equal( + new B('123456!@#$%^', 'ascii').toString('base64'), + 'MTIzNDU2IUAjJCVe' + ) + t.end() +}) + +test('ascii buffer to hex', function (t) { + t.equal( + new B('123456!@#$%^', 'ascii').toString('hex'), + '31323334353621402324255e' + ) + t.end() +}) + +test('base64 buffer to utf8', function (t) { + t.equal( + new B('1YHXkGFi', 'base64').toString('utf8'), + 'Ձאab' + ) + t.end() +}) + +test('hex buffer to utf8', function (t) { + t.equal( + new B('d581d7906162', 'hex').toString('utf8'), + 'Ձאab' + ) + t.end() +}) + +test('base64 buffer to ascii', function (t) { + t.equal( + new B('MTIzNDU2IUAjJCVe', 'base64').toString('ascii'), + '123456!@#$%^' + ) + t.end() +}) + +test('hex buffer to ascii', function (t) { + t.equal( + new B('31323334353621402324255e', 'hex').toString('ascii'), + '123456!@#$%^' + ) + t.end() +}) + +test('base64 buffer to binary', function (t) { + t.equal( + new B('MTIzNDU2IUAjJCVe', 'base64').toString('binary'), + '123456!@#$%^' + ) + t.end() +}) + +test('hex buffer to binary', function (t) { + t.equal( + new B('31323334353621402324255e', 'hex').toString('binary'), + '123456!@#$%^' + ) + t.end() +}) + +test('utf8 to binary', function (t) { + /* jshint -W100 */ + t.equal( + new B('öäüõÖÄÜÕ', 'utf8').toString('binary'), + 'öäüõÖÄÜÕ' + ) + /* jshint +W100 */ + t.end() +}) + +test('utf8 replacement chars (1 byte sequence)', function (t) { + t.equal( + new B([ 0x80 ]).toString(), + '\uFFFD' + ) + t.equal( + new B([ 0x7F ]).toString(), + '\u007F' + ) + t.end() +}) + +test('utf8 replacement chars (2 byte sequences)', function (t) { + t.equal( + new B([ 0xC7 ]).toString(), + '\uFFFD' + ) + t.equal( + new B([ 0xC7, 0xB1 ]).toString(), + '\u01F1' + ) + t.equal( + new B([ 0xC0, 0xB1 ]).toString(), + '\uFFFD\uFFFD' + ) + t.equal( + new B([ 0xC1, 0xB1 ]).toString(), + '\uFFFD\uFFFD' + ) + t.end() +}) + +test('utf8 replacement chars (3 byte sequences)', function (t) { + t.equal( + new B([ 0xE0 ]).toString(), + '\uFFFD' + ) + t.equal( + new B([ 0xE0, 0xAC ]).toString(), + '\uFFFD\uFFFD' + ) + t.equal( + new B([ 0xE0, 0xAC, 0xB9 ]).toString(), + '\u0B39' + ) + t.end() +}) + +test('utf8 replacement chars (4 byte sequences)', function (t) { + t.equal( + new B([ 0xF4 ]).toString(), + '\uFFFD' + ) + t.equal( + new B([ 0xF4, 0x8F ]).toString(), + '\uFFFD\uFFFD' + ) + t.equal( + new B([ 0xF4, 0x8F, 0x80 ]).toString(), + '\uFFFD\uFFFD\uFFFD' + ) + t.equal( + new B([ 0xF4, 0x8F, 0x80, 0x84 ]).toString(), + '\uDBFC\uDC04' + ) + t.equal( + new B([ 0xFF ]).toString(), + '\uFFFD' + ) + t.equal( + new B([ 0xFF, 0x8F, 0x80, 0x84 ]).toString(), + '\uFFFD\uFFFD\uFFFD\uFFFD' + ) + t.end() +}) + +test('utf8 replacement chars on 256 random bytes', function (t) { + t.equal( + new B([ 152, 130, 206, 23, 243, 238, 197, 44, 27, 86, 208, 36, 163, 184, 164, 21, 94, 242, 178, 46, 25, 26, 253, 178, 72, 147, 207, 112, 236, 68, 179, 190, 29, 83, 239, 147, 125, 55, 143, 19, 157, 68, 157, 58, 212, 224, 150, 39, 128, 24, 94, 225, 120, 121, 75, 192, 112, 19, 184, 142, 203, 36, 43, 85, 26, 147, 227, 139, 242, 186, 57, 78, 11, 102, 136, 117, 180, 210, 241, 92, 3, 215, 54, 167, 249, 1, 44, 225, 146, 86, 2, 42, 68, 21, 47, 238, 204, 153, 216, 252, 183, 66, 222, 255, 15, 202, 16, 51, 134, 1, 17, 19, 209, 76, 238, 38, 76, 19, 7, 103, 249, 5, 107, 137, 64, 62, 170, 57, 16, 85, 179, 193, 97, 86, 166, 196, 36, 148, 138, 193, 210, 69, 187, 38, 242, 97, 195, 219, 252, 244, 38, 1, 197, 18, 31, 246, 53, 47, 134, 52, 105, 72, 43, 239, 128, 203, 73, 93, 199, 75, 222, 220, 166, 34, 63, 236, 11, 212, 76, 243, 171, 110, 78, 39, 205, 204, 6, 177, 233, 212, 243, 0, 33, 41, 122, 118, 92, 252, 0, 157, 108, 120, 70, 137, 100, 223, 243, 171, 232, 66, 126, 111, 142, 33, 3, 39, 117, 27, 107, 54, 1, 217, 227, 132, 13, 166, 3, 73, 53, 127, 225, 236, 134, 219, 98, 214, 125, 148, 24, 64, 142, 111, 231, 194, 42, 150, 185, 10, 182, 163, 244, 19, 4, 59, 135, 16 ]).toString(), + '\uFFFD\uFFFD\uFFFD\u0017\uFFFD\uFFFD\uFFFD\u002C\u001B\u0056\uFFFD\u0024\uFFFD\uFFFD\uFFFD\u0015\u005E\uFFFD\uFFFD\u002E\u0019\u001A\uFFFD\uFFFD\u0048\uFFFD\uFFFD\u0070\uFFFD\u0044\uFFFD\uFFFD\u001D\u0053\uFFFD\uFFFD\u007D\u0037\uFFFD\u0013\uFFFD\u0044\uFFFD\u003A\uFFFD\uFFFD\uFFFD\u0027\uFFFD\u0018\u005E\uFFFD\u0078\u0079\u004B\uFFFD\u0070\u0013\uFFFD\uFFFD\uFFFD\u0024\u002B\u0055\u001A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0039\u004E\u000B\u0066\uFFFD\u0075\uFFFD\uFFFD\uFFFD\u005C\u0003\uFFFD\u0036\uFFFD\uFFFD\u0001\u002C\uFFFD\uFFFD\u0056\u0002\u002A\u0044\u0015\u002F\uFFFD\u0319\uFFFD\uFFFD\uFFFD\u0042\uFFFD\uFFFD\u000F\uFFFD\u0010\u0033\uFFFD\u0001\u0011\u0013\uFFFD\u004C\uFFFD\u0026\u004C\u0013\u0007\u0067\uFFFD\u0005\u006B\uFFFD\u0040\u003E\uFFFD\u0039\u0010\u0055\uFFFD\uFFFD\u0061\u0056\uFFFD\uFFFD\u0024\uFFFD\uFFFD\uFFFD\uFFFD\u0045\uFFFD\u0026\uFFFD\u0061\uFFFD\uFFFD\uFFFD\uFFFD\u0026\u0001\uFFFD\u0012\u001F\uFFFD\u0035\u002F\uFFFD\u0034\u0069\u0048\u002B\uFFFD\uFFFD\uFFFD\u0049\u005D\uFFFD\u004B\uFFFD\u0726\u0022\u003F\uFFFD\u000B\uFFFD\u004C\uFFFD\uFFFD\u006E\u004E\u0027\uFFFD\uFFFD\u0006\uFFFD\uFFFD\uFFFD\uFFFD\u0000\u0021\u0029\u007A\u0076\u005C\uFFFD\u0000\uFFFD\u006C\u0078\u0046\uFFFD\u0064\uFFFD\uFFFD\uFFFD\uFFFD\u0042\u007E\u006F\uFFFD\u0021\u0003\u0027\u0075\u001B\u006B\u0036\u0001\uFFFD\uFFFD\uFFFD\u000D\uFFFD\u0003\u0049\u0035\u007F\uFFFD\uFFFD\uFFFD\uFFFD\u0062\uFFFD\u007D\uFFFD\u0018\u0040\uFFFD\u006F\uFFFD\uFFFD\u002A\uFFFD\uFFFD\u000A\uFFFD\uFFFD\uFFFD\u0013\u0004\u003B\uFFFD\u0010' + ) + t.end() +}) + +test('utf8 replacement chars for anything in the surrogate pair range', function (t) { + t.equal( + new B([ 0xED, 0x9F, 0xBF ]).toString(), + '\uD7FF' + ) + t.equal( + new B([ 0xED, 0xA0, 0x80 ]).toString(), + '\uFFFD\uFFFD\uFFFD' + ) + t.equal( + new B([ 0xED, 0xBE, 0x8B ]).toString(), + '\uFFFD\uFFFD\uFFFD' + ) + t.equal( + new B([ 0xED, 0xBF, 0xBF ]).toString(), + '\uFFFD\uFFFD\uFFFD' + ) + t.equal( + new B([ 0xEE, 0x80, 0x80 ]).toString(), + '\uE000' + ) + t.end() +}) + +test('utf8 don\'t replace the replacement char', function (t) { + t.equal( + new B('\uFFFD').toString(), + '\uFFFD' + ) + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/write.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/write.js new file mode 100644 index 0000000..5841806 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/write.js @@ -0,0 +1,131 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') +var isnan = require('is-nan') + +test('buffer.write string should get parsed as number', function (t) { + var b = new B(64) + b.writeUInt16LE('1003', 0) + t.equal(b.readUInt16LE(0), 1003) + t.end() +}) + +test('buffer.writeUInt8 a fractional number will get Math.floored', function (t) { + // Some extra work is necessary to make this test pass with the Object implementation + + var b = new B(1) + b.writeInt8(5.5, 0) + t.equal(b[0], 5) + t.end() +}) + +test('writeUint8 with a negative number throws', function (t) { + var buf = new B(1) + + t.throws(function () { + buf.writeUInt8(-3, 0) + }) + + t.end() +}) + +test('hex of write{Uint,Int}{8,16,32}{LE,BE}', function (t) { + t.plan(2 * (2 * 2 * 2 + 2)) + var hex = [ + '03', '0300', '0003', '03000000', '00000003', + 'fd', 'fdff', 'fffd', 'fdffffff', 'fffffffd' + ] + var reads = [ 3, 3, 3, 3, 3, -3, -3, -3, -3, -3 ] + var xs = ['UInt', 'Int'] + var ys = [8, 16, 32] + for (var i = 0; i < xs.length; i++) { + var x = xs[i] + for (var j = 0; j < ys.length; j++) { + var y = ys[j] + var endianesses = (y === 8) ? [''] : ['LE', 'BE'] + for (var k = 0; k < endianesses.length; k++) { + var z = endianesses[k] + + var v1 = new B(y / 8) + var writefn = 'write' + x + y + z + var val = (x === 'Int') ? -3 : 3 + v1[writefn](val, 0) + t.equal( + v1.toString('hex'), + hex.shift() + ) + var readfn = 'read' + x + y + z + t.equal( + v1[readfn](0), + reads.shift() + ) + } + } + } + t.end() +}) + +test('hex of write{Uint,Int}{8,16,32}{LE,BE} with overflow', function (t) { + if (!B.TYPED_ARRAY_SUPPORT) { + t.pass('object impl: skipping overflow test') + t.end() + return + } + + t.plan(3 * (2 * 2 * 2 + 2)) + var hex = [ + '', '03', '00', '030000', '000000', + '', 'fd', 'ff', 'fdffff', 'ffffff' + ] + var reads = [ + undefined, 3, 0, NaN, 0, + undefined, 253, -256, 16777213, -256 + ] + var xs = ['UInt', 'Int'] + var ys = [8, 16, 32] + for (var i = 0; i < xs.length; i++) { + var x = xs[i] + for (var j = 0; j < ys.length; j++) { + var y = ys[j] + var endianesses = (y === 8) ? [''] : ['LE', 'BE'] + for (var k = 0; k < endianesses.length; k++) { + var z = endianesses[k] + + var v1 = new B(y / 8 - 1) + var next = new B(4) + next.writeUInt32BE(0, 0) + var writefn = 'write' + x + y + z + var val = (x === 'Int') ? -3 : 3 + v1[writefn](val, 0, true) + t.equal( + v1.toString('hex'), + hex.shift() + ) + // check that nothing leaked to next buffer. + t.equal(next.readUInt32BE(0), 0) + // check that no bytes are read from next buffer. + next.writeInt32BE(~0, 0) + var readfn = 'read' + x + y + z + var r = reads.shift() + if (isnan(r)) t.pass('equal') + else t.equal(v1[readfn](0, true), r) + } + } + } + t.end() +}) +test('large values do not improperly roll over (ref #80)', function (t) { + var nums = [-25589992, -633756690, -898146932] + var out = new B(12) + out.fill(0) + out.writeInt32BE(nums[0], 0) + var newNum = out.readInt32BE(0) + t.equal(nums[0], newNum) + out.writeInt32BE(nums[1], 4) + newNum = out.readInt32BE(4) + t.equal(nums[1], newNum) + out.writeInt32BE(nums[2], 8) + newNum = out.readInt32BE(8) + t.equal(nums[2], newNum) + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/buffer/test/write_infinity.js b/node_modules/meteor-node-stubs/node_modules/buffer/test/write_infinity.js new file mode 100644 index 0000000..17d606a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/buffer/test/write_infinity.js @@ -0,0 +1,45 @@ +if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false +var B = require('../').Buffer +var test = require('tape') + +test('write/read Infinity as a float', function (t) { + var buf = new B(4) + t.equal(buf.writeFloatBE(Infinity, 0), 4) + t.equal(buf.readFloatBE(0), Infinity) + t.end() +}) + +test('write/read -Infinity as a float', function (t) { + var buf = new B(4) + t.equal(buf.writeFloatBE(-Infinity, 0), 4) + t.equal(buf.readFloatBE(0), -Infinity) + t.end() +}) + +test('write/read Infinity as a double', function (t) { + var buf = new B(8) + t.equal(buf.writeDoubleBE(Infinity, 0), 8) + t.equal(buf.readDoubleBE(0), Infinity) + t.end() +}) + +test('write/read -Infinity as a double', function (t) { + var buf = new B(8) + t.equal(buf.writeDoubleBE(-Infinity, 0), 8) + t.equal(buf.readDoubleBE(0), -Infinity) + t.end() +}) + +test('write/read float greater than max', function (t) { + var buf = new B(4) + t.equal(buf.writeFloatBE(4e38, 0), 4) + t.equal(buf.readFloatBE(0), Infinity) + t.end() +}) + +test('write/read float less than min', function (t) { + var buf = new B(4) + t.equal(buf.writeFloatBE(-4e40, 0), 4) + t.equal(buf.readFloatBE(0), -Infinity) + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/.npmignore b/node_modules/meteor-node-stubs/node_modules/console-browserify/.npmignore new file mode 100644 index 0000000..aa3fd4b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/.npmignore @@ -0,0 +1,14 @@ +.DS_Store +.monitor +.*.swp +.nodemonignore +releases +*.log +*.err +fleet.json +public/browserify +bin/*.json +.bin +build +compile +.lock-wscript diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/.testem.json b/node_modules/meteor-node-stubs/node_modules/console-browserify/.testem.json new file mode 100644 index 0000000..633c2ba --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/.testem.json @@ -0,0 +1,14 @@ +{ + "launchers": { + "node": { + "command": "npm test" + } + }, + "src_files": [ + "./**/*.js" + ], + "before_tests": "npm run build", + "on_exit": "rm test/static/bundle.js", + "test_page": "test/static/index.html", + "launch_in_dev": ["node", "phantomjs"] +} diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/.travis.yml b/node_modules/meteor-node-stubs/node_modules/console-browserify/.travis.yml new file mode 100644 index 0000000..ed178f6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.8 + - 0.9 diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/LICENCE b/node_modules/meteor-node-stubs/node_modules/console-browserify/LICENCE new file mode 100644 index 0000000..a23e08a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/LICENCE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/README.md b/node_modules/meteor-node-stubs/node_modules/console-browserify/README.md new file mode 100644 index 0000000..572615e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/README.md @@ -0,0 +1,33 @@ +# console-browserify + +[![build status][1]][2] + +[![browser support][3]][4] + + +Emulate console for all the browsers + +## Example + +```js +var console = require("console-browserify") + +console.log("hello world!") +``` + +## Installation + +`npm install console-browserify` + +## Contributors + + - Raynos + +## MIT Licenced + + + + [1]: https://secure.travis-ci.org/Raynos/console-browserify.png + [2]: http://travis-ci.org/Raynos/console-browserify + [3]: http://ci.testling.com/Raynos/console-browserify.png + [4]: http://ci.testling.com/Raynos/console-browserify diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/index.js b/node_modules/meteor-node-stubs/node_modules/console-browserify/index.js new file mode 100644 index 0000000..af433ce --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/index.js @@ -0,0 +1,86 @@ +/*global window, global*/ +var util = require("util") +var assert = require("assert") +var now = require("date-now") + +var slice = Array.prototype.slice +var console +var times = {} + +if (typeof global !== "undefined" && global.console) { + console = global.console +} else if (typeof window !== "undefined" && window.console) { + console = window.console +} else { + console = {} +} + +var functions = [ + [log, "log"], + [info, "info"], + [warn, "warn"], + [error, "error"], + [time, "time"], + [timeEnd, "timeEnd"], + [trace, "trace"], + [dir, "dir"], + [consoleAssert, "assert"] +] + +for (var i = 0; i < functions.length; i++) { + var tuple = functions[i] + var f = tuple[0] + var name = tuple[1] + + if (!console[name]) { + console[name] = f + } +} + +module.exports = console + +function log() {} + +function info() { + console.log.apply(console, arguments) +} + +function warn() { + console.log.apply(console, arguments) +} + +function error() { + console.warn.apply(console, arguments) +} + +function time(label) { + times[label] = now() +} + +function timeEnd(label) { + var time = times[label] + if (!time) { + throw new Error("No such label: " + label) + } + + var duration = now() - time + console.log(label + ": " + duration + "ms") +} + +function trace() { + var err = new Error() + err.name = "Trace" + err.message = util.format.apply(null, arguments) + console.error(err.stack) +} + +function dir(object) { + console.log(util.inspect(object) + "\n") +} + +function consoleAssert(expression) { + if (!expression) { + var arr = slice.call(arguments, 1) + assert.ok(false, util.format.apply(null, arr)) + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.npmignore b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.npmignore new file mode 100644 index 0000000..aa3fd4b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.npmignore @@ -0,0 +1,14 @@ +.DS_Store +.monitor +.*.swp +.nodemonignore +releases +*.log +*.err +fleet.json +public/browserify +bin/*.json +.bin +build +compile +.lock-wscript diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.testem.json b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.testem.json new file mode 100644 index 0000000..633c2ba --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.testem.json @@ -0,0 +1,14 @@ +{ + "launchers": { + "node": { + "command": "npm test" + } + }, + "src_files": [ + "./**/*.js" + ], + "before_tests": "npm run build", + "on_exit": "rm test/static/bundle.js", + "test_page": "test/static/index.html", + "launch_in_dev": ["node", "phantomjs"] +} diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.travis.yml b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.travis.yml new file mode 100644 index 0000000..ed178f6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.8 + - 0.9 diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/LICENCE b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/LICENCE new file mode 100644 index 0000000..822d880 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/LICENCE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Colingo. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/README.md b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/README.md new file mode 100644 index 0000000..22d2675 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/README.md @@ -0,0 +1,45 @@ +# date-now + +[![build status][1]][2] + +[![browser support][3]][4] + +A requirable version of Date.now() + +Use-case is to be able to mock out Date.now() using require interception. + +## Example + +```js +var now = require("date-now") + +var ts = now() +var ts2 = Date.now() +assert.equal(ts, ts2) +``` + +## example of seed + +``` +var now = require("date-now/seed")(timeStampFromServer) + +// ts is in "sync" with the seed value from the server +// useful if your users have their local time being a few minutes +// out of your server time. +var ts = now() +``` + +## Installation + +`npm install date-now` + +## Contributors + + - Raynos + +## MIT Licenced + + [1]: https://secure.travis-ci.org/Colingo/date-now.png + [2]: http://travis-ci.org/Colingo/date-now + [3]: http://ci.testling.com/Colingo/date-now.png + [4]: http://ci.testling.com/Colingo/date-now diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/index.js b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/index.js new file mode 100644 index 0000000..d5f143a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/index.js @@ -0,0 +1,5 @@ +module.exports = now + +function now() { + return new Date().getTime() +} diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/package.json b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/package.json new file mode 100644 index 0000000..d733342 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/package.json @@ -0,0 +1,75 @@ +{ + "name": "date-now", + "version": "0.1.4", + "description": "A requirable version of Date.now()", + "keywords": [], + "author": { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Colingo/date-now.git" + }, + "main": "index", + "homepage": "https://github.com/Colingo/date-now", + "contributors": [ + { + "name": "Artem Shoobovych" + } + ], + "bugs": { + "url": "https://github.com/Colingo/date-now/issues", + "email": "raynos2@gmail.com" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~0.2.2", + "browserify": "https://github.com/raynos/node-browserify/tarball/master", + "testem": "~0.2.52" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://github.com/Colingo/date-now/raw/master/LICENSE" + } + ], + "scripts": { + "test": "node ./test", + "build": "browserify test/index.js -o test/static/bundle.js", + "testem": "testem" + }, + "testling": { + "files": "test/*.js", + "browsers": { + "ie": [ + "8", + "9", + "10" + ], + "firefox": [ + "16", + "17", + "nightly" + ], + "chrome": [ + "22", + "23", + "canary" + ], + "opera": [ + "12", + "next" + ], + "safari": [ + "5.1" + ] + } + }, + "readme": "# date-now\n\n[![build status][1]][2]\n\n[![browser support][3]][4]\n\nA requirable version of Date.now()\n\nUse-case is to be able to mock out Date.now() using require interception.\n\n## Example\n\n```js\nvar now = require(\"date-now\")\n\nvar ts = now()\nvar ts2 = Date.now()\nassert.equal(ts, ts2)\n```\n\n## example of seed\n\n```\nvar now = require(\"date-now/seed\")(timeStampFromServer)\n\n// ts is in \"sync\" with the seed value from the server\n// useful if your users have their local time being a few minutes\n// out of your server time.\nvar ts = now()\n```\n\n## Installation\n\n`npm install date-now`\n\n## Contributors\n\n - Raynos\n\n## MIT Licenced\n\n [1]: https://secure.travis-ci.org/Colingo/date-now.png\n [2]: http://travis-ci.org/Colingo/date-now\n [3]: http://ci.testling.com/Colingo/date-now.png\n [4]: http://ci.testling.com/Colingo/date-now\n", + "readmeFilename": "README.md", + "_id": "date-now@0.1.4", + "_shasum": "eaf439fd4d4848ad74e5cc7dbef200672b9e345b", + "_resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", + "_from": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/seed.js b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/seed.js new file mode 100644 index 0000000..b9727c5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/seed.js @@ -0,0 +1,16 @@ +var now = require("./index") + +module.exports = seeded + +/* Returns a Date.now() like function that's in sync with + the seed value +*/ +function seeded(seed) { + var current = now() + + return time + + function time() { + return seed + (now() - current) + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/test/index.js b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/test/index.js new file mode 100644 index 0000000..270584c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/test/index.js @@ -0,0 +1,28 @@ +var test = require("tape") +var setTimeout = require("timers").setTimeout + +var now = require("../index") +var seeded = require("../seed") + +test("date", function (assert) { + var ts = now() + var ts2 = Date.now() + assert.equal(ts, ts2) + assert.end() +}) + +test("seeded", function (assert) { + var time = seeded(40) + var ts = time() + + within(assert, time(), 40, 5) + setTimeout(function () { + within(assert, time(), 90, 10) + assert.end() + }, 50) +}) + +function within(assert, a, b, offset) { + assert.ok(a + offset > b) + assert.ok(a - offset < b) +} diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/test/static/index.html b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/test/static/index.html new file mode 100644 index 0000000..3d5384d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/node_modules/date-now/test/static/index.html @@ -0,0 +1,10 @@ + + + + TAPE Example + + + + + + diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/console-browserify/package.json new file mode 100644 index 0000000..d58043c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/package.json @@ -0,0 +1,74 @@ +{ + "name": "console-browserify", + "version": "1.1.0", + "description": "Emulate console for all the browsers", + "keywords": [], + "author": { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Raynos/console-browserify.git" + }, + "main": "index", + "homepage": "https://github.com/Raynos/console-browserify", + "contributors": [ + { + "name": "Raynos" + } + ], + "bugs": { + "url": "https://github.com/Raynos/console-browserify/issues", + "email": "raynos2@gmail.com" + }, + "dependencies": { + "date-now": "^0.1.4" + }, + "devDependencies": { + "tape": "^2.12.3", + "jsonify": "0.0.0", + "tap-spec": "^0.1.8", + "run-browser": "^1.3.0", + "tap-dot": "^0.2.1" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://github.com/Raynos/console-browserify/raw/master/LICENSE" + } + ], + "scripts": { + "test": "node ./test/index.js | tap-spec", + "dot": "node ./test/index.js | tap-dot", + "start": "node ./index.js", + "cover": "istanbul cover --report none --print detail ./test/index.js", + "view-cover": "istanbul report html && google-chrome ./coverage/index.html", + "browser": "run-browser test/index.js", + "phantom": "run-browser test/index.js -b | tap-spec", + "build": "browserify test/index.js -o test/static/bundle.js", + "testem": "testem" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "readme": "# console-browserify\n\n[![build status][1]][2]\n\n[![browser support][3]][4]\n\n\nEmulate console for all the browsers\n\n## Example\n\n```js\nvar console = require(\"console-browserify\")\n\nconsole.log(\"hello world!\")\n```\n\n## Installation\n\n`npm install console-browserify`\n\n## Contributors\n\n - Raynos\n\n## MIT Licenced\n\n\n\n [1]: https://secure.travis-ci.org/Raynos/console-browserify.png\n [2]: http://travis-ci.org/Raynos/console-browserify\n [3]: http://ci.testling.com/Raynos/console-browserify.png\n [4]: http://ci.testling.com/Raynos/console-browserify\n", + "readmeFilename": "README.md", + "_id": "console-browserify@1.1.0", + "_shasum": "f0241c45730a9fc6323b206dbf38edc741d0bb10", + "_resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", + "_from": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/test/index.js b/node_modules/meteor-node-stubs/node_modules/console-browserify/test/index.js new file mode 100644 index 0000000..26dfaad --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/test/index.js @@ -0,0 +1,67 @@ +var console = require("../index") +var test = require("tape") + +if (typeof window !== "undefined" && !window.JSON) { + window.JSON = require("jsonify") +} + +test("console has expected methods", function (assert) { + assert.ok(console.log) + assert.ok(console.info) + assert.ok(console.warn) + assert.ok(console.dir) + assert.ok(console.time, "time") + assert.ok(console.timeEnd, "timeEnd") + assert.ok(console.trace, "trace") + assert.ok(console.assert) + + assert.end() +}) + +test("invoke console.log", function (assert) { + console.log("test-log") + + assert.end() +}) + +test("invoke console.info", function (assert) { + console.info("test-info") + + assert.end() +}) + +test("invoke console.warn", function (assert) { + console.warn("test-warn") + + assert.end() +}) + +test("invoke console.time", function (assert) { + console.time("label") + + assert.end() +}) + +test("invoke console.trace", function (assert) { + console.trace("test-trace") + + assert.end() +}) + +test("invoke console.assert", function (assert) { + console.assert(true) + + assert.end() +}) + +test("invoke console.dir", function (assert) { + console.dir("test-dir") + + assert.end() +}) + +test("invoke console.timeEnd", function (assert) { + console.timeEnd("label") + + assert.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/test/static/index.html b/node_modules/meteor-node-stubs/node_modules/console-browserify/test/static/index.html new file mode 100644 index 0000000..dd55012 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/test/static/index.html @@ -0,0 +1,12 @@ + + + + + TAPE Example + + + + + + + diff --git a/node_modules/meteor-node-stubs/node_modules/console-browserify/test/static/test-adapter.js b/node_modules/meteor-node-stubs/node_modules/console-browserify/test/static/test-adapter.js new file mode 100644 index 0000000..8b4c12d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/console-browserify/test/static/test-adapter.js @@ -0,0 +1,53 @@ +(function () { + var Testem = window.Testem + var regex = /^((?:not )?ok) (\d+) (.+)$/ + + Testem.useCustomAdapter(tapAdapter) + + function tapAdapter(socket){ + var results = { + failed: 0 + , passed: 0 + , total: 0 + , tests: [] + } + + socket.emit('tests-start') + + Testem.handleConsoleMessage = function(msg){ + var m = msg.match(regex) + if (m) { + var passed = m[1] === 'ok' + var test = { + passed: passed ? 1 : 0, + failed: passed ? 0 : 1, + total: 1, + id: m[2], + name: m[3], + items: [] + } + + if (passed) { + results.passed++ + } else { + console.error("failure", m) + + results.failed++ + } + + results.total++ + + // console.log("emitted test", test) + socket.emit('test-result', test) + results.tests.push(test) + } else if (msg === '# ok' || msg.match(/^# tests \d+/)){ + // console.log("emitted all test") + socket.emit('all-test-results', results) + } + + // return false if you want to prevent the console message from + // going to the console + // return false + } + } +}()) diff --git a/node_modules/meteor-node-stubs/node_modules/constants-browserify/README.md b/node_modules/meteor-node-stubs/node_modules/constants-browserify/README.md new file mode 100644 index 0000000..9dd5a46 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/constants-browserify/README.md @@ -0,0 +1,54 @@ + +# constants-browserify + +Node's `constants` module for the browser. + +[![downloads](https://img.shields.io/npm/dm/constants-browserify.svg)](https://www.npmjs.org/package/constants-browserify) + +## Usage + +To use with browserify cli: + +```bash +$ browserify -r constants:constants-browserify script.js +``` + +To use with browserify api: + +```js +browserify() + .require('constants-browserify', { expose: 'constants' }) + .add(__dirname + '/script.js') + .bundle() + // ... +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install constants-browserify +``` + +## License + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS 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. diff --git a/node_modules/meteor-node-stubs/node_modules/constants-browserify/build.sh b/node_modules/meteor-node-stubs/node_modules/constants-browserify/build.sh new file mode 100644 index 0000000..60012d6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/constants-browserify/build.sh @@ -0,0 +1 @@ +node -pe 'JSON.stringify(require("constants"), null, " ")' > constants.json diff --git a/node_modules/meteor-node-stubs/node_modules/constants-browserify/constants.json b/node_modules/meteor-node-stubs/node_modules/constants-browserify/constants.json new file mode 100644 index 0000000..9a69b85 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/constants-browserify/constants.json @@ -0,0 +1,209 @@ +{ + "O_RDONLY": 0, + "O_WRONLY": 1, + "O_RDWR": 2, + "S_IFMT": 61440, + "S_IFREG": 32768, + "S_IFDIR": 16384, + "S_IFCHR": 8192, + "S_IFBLK": 24576, + "S_IFIFO": 4096, + "S_IFLNK": 40960, + "S_IFSOCK": 49152, + "O_CREAT": 512, + "O_EXCL": 2048, + "O_NOCTTY": 131072, + "O_TRUNC": 1024, + "O_APPEND": 8, + "O_DIRECTORY": 1048576, + "O_NOFOLLOW": 256, + "O_SYNC": 128, + "O_SYMLINK": 2097152, + "O_NONBLOCK": 4, + "S_IRWXU": 448, + "S_IRUSR": 256, + "S_IWUSR": 128, + "S_IXUSR": 64, + "S_IRWXG": 56, + "S_IRGRP": 32, + "S_IWGRP": 16, + "S_IXGRP": 8, + "S_IRWXO": 7, + "S_IROTH": 4, + "S_IWOTH": 2, + "S_IXOTH": 1, + "E2BIG": 7, + "EACCES": 13, + "EADDRINUSE": 48, + "EADDRNOTAVAIL": 49, + "EAFNOSUPPORT": 47, + "EAGAIN": 35, + "EALREADY": 37, + "EBADF": 9, + "EBADMSG": 94, + "EBUSY": 16, + "ECANCELED": 89, + "ECHILD": 10, + "ECONNABORTED": 53, + "ECONNREFUSED": 61, + "ECONNRESET": 54, + "EDEADLK": 11, + "EDESTADDRREQ": 39, + "EDOM": 33, + "EDQUOT": 69, + "EEXIST": 17, + "EFAULT": 14, + "EFBIG": 27, + "EHOSTUNREACH": 65, + "EIDRM": 90, + "EILSEQ": 92, + "EINPROGRESS": 36, + "EINTR": 4, + "EINVAL": 22, + "EIO": 5, + "EISCONN": 56, + "EISDIR": 21, + "ELOOP": 62, + "EMFILE": 24, + "EMLINK": 31, + "EMSGSIZE": 40, + "EMULTIHOP": 95, + "ENAMETOOLONG": 63, + "ENETDOWN": 50, + "ENETRESET": 52, + "ENETUNREACH": 51, + "ENFILE": 23, + "ENOBUFS": 55, + "ENODATA": 96, + "ENODEV": 19, + "ENOENT": 2, + "ENOEXEC": 8, + "ENOLCK": 77, + "ENOLINK": 97, + "ENOMEM": 12, + "ENOMSG": 91, + "ENOPROTOOPT": 42, + "ENOSPC": 28, + "ENOSR": 98, + "ENOSTR": 99, + "ENOSYS": 78, + "ENOTCONN": 57, + "ENOTDIR": 20, + "ENOTEMPTY": 66, + "ENOTSOCK": 38, + "ENOTSUP": 45, + "ENOTTY": 25, + "ENXIO": 6, + "EOPNOTSUPP": 102, + "EOVERFLOW": 84, + "EPERM": 1, + "EPIPE": 32, + "EPROTO": 100, + "EPROTONOSUPPORT": 43, + "EPROTOTYPE": 41, + "ERANGE": 34, + "EROFS": 30, + "ESPIPE": 29, + "ESRCH": 3, + "ESTALE": 70, + "ETIME": 101, + "ETIMEDOUT": 60, + "ETXTBSY": 26, + "EWOULDBLOCK": 35, + "EXDEV": 18, + "SIGHUP": 1, + "SIGINT": 2, + "SIGQUIT": 3, + "SIGILL": 4, + "SIGTRAP": 5, + "SIGABRT": 6, + "SIGIOT": 6, + "SIGBUS": 10, + "SIGFPE": 8, + "SIGKILL": 9, + "SIGUSR1": 30, + "SIGSEGV": 11, + "SIGUSR2": 31, + "SIGPIPE": 13, + "SIGALRM": 14, + "SIGTERM": 15, + "SIGCHLD": 20, + "SIGCONT": 19, + "SIGSTOP": 17, + "SIGTSTP": 18, + "SIGTTIN": 21, + "SIGTTOU": 22, + "SIGURG": 16, + "SIGXCPU": 24, + "SIGXFSZ": 25, + "SIGVTALRM": 26, + "SIGPROF": 27, + "SIGWINCH": 28, + "SIGIO": 23, + "SIGSYS": 12, + "SSL_OP_ALL": 2147486719, + "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION": 262144, + "SSL_OP_CIPHER_SERVER_PREFERENCE": 4194304, + "SSL_OP_CISCO_ANYCONNECT": 32768, + "SSL_OP_COOKIE_EXCHANGE": 8192, + "SSL_OP_CRYPTOPRO_TLSEXT_BUG": 2147483648, + "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS": 2048, + "SSL_OP_EPHEMERAL_RSA": 0, + "SSL_OP_LEGACY_SERVER_CONNECT": 4, + "SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER": 32, + "SSL_OP_MICROSOFT_SESS_ID_BUG": 1, + "SSL_OP_MSIE_SSLV2_RSA_PADDING": 0, + "SSL_OP_NETSCAPE_CA_DN_BUG": 536870912, + "SSL_OP_NETSCAPE_CHALLENGE_BUG": 2, + "SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG": 1073741824, + "SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG": 8, + "SSL_OP_NO_COMPRESSION": 131072, + "SSL_OP_NO_QUERY_MTU": 4096, + "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION": 65536, + "SSL_OP_NO_SSLv2": 16777216, + "SSL_OP_NO_SSLv3": 33554432, + "SSL_OP_NO_TICKET": 16384, + "SSL_OP_NO_TLSv1": 67108864, + "SSL_OP_NO_TLSv1_1": 268435456, + "SSL_OP_NO_TLSv1_2": 134217728, + "SSL_OP_PKCS1_CHECK_1": 0, + "SSL_OP_PKCS1_CHECK_2": 0, + "SSL_OP_SINGLE_DH_USE": 1048576, + "SSL_OP_SINGLE_ECDH_USE": 524288, + "SSL_OP_SSLEAY_080_CLIENT_DH_BUG": 128, + "SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG": 0, + "SSL_OP_TLS_BLOCK_PADDING_BUG": 512, + "SSL_OP_TLS_D5_BUG": 256, + "SSL_OP_TLS_ROLLBACK_BUG": 8388608, + "ENGINE_METHOD_DSA": 2, + "ENGINE_METHOD_DH": 4, + "ENGINE_METHOD_RAND": 8, + "ENGINE_METHOD_ECDH": 16, + "ENGINE_METHOD_ECDSA": 32, + "ENGINE_METHOD_CIPHERS": 64, + "ENGINE_METHOD_DIGESTS": 128, + "ENGINE_METHOD_STORE": 256, + "ENGINE_METHOD_PKEY_METHS": 512, + "ENGINE_METHOD_PKEY_ASN1_METHS": 1024, + "ENGINE_METHOD_ALL": 65535, + "ENGINE_METHOD_NONE": 0, + "DH_CHECK_P_NOT_SAFE_PRIME": 2, + "DH_CHECK_P_NOT_PRIME": 1, + "DH_UNABLE_TO_CHECK_GENERATOR": 4, + "DH_NOT_SUITABLE_GENERATOR": 8, + "NPN_ENABLED": 1, + "RSA_PKCS1_PADDING": 1, + "RSA_SSLV23_PADDING": 2, + "RSA_NO_PADDING": 3, + "RSA_PKCS1_OAEP_PADDING": 4, + "RSA_X931_PADDING": 5, + "RSA_PKCS1_PSS_PADDING": 6, + "POINT_CONVERSION_COMPRESSED": 2, + "POINT_CONVERSION_UNCOMPRESSED": 4, + "POINT_CONVERSION_HYBRID": 6, + "F_OK": 0, + "R_OK": 4, + "W_OK": 2, + "X_OK": 1, + "UV_UDP_REUSEADDR": 4 +} diff --git a/node_modules/meteor-node-stubs/node_modules/constants-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/constants-browserify/package.json new file mode 100644 index 0000000..88bfdf9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/constants-browserify/package.json @@ -0,0 +1,43 @@ +{ + "name": "constants-browserify", + "description": "node's constants module for the browser", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/constants-browserify.git" + }, + "homepage": "https://github.com/juliangruber/constants-browserify", + "main": "constants.json", + "dependencies": {}, + "keywords": [ + "constants", + "node", + "browser", + "browserify" + ], + "author": { + "name": "Julian Gruber", + "email": "julian@juliangruber.com", + "url": "http://juliangruber.com" + }, + "scripts": { + "test": "node test.js" + }, + "contributors": [ + { + "name": "James J. Womack", + "email": "james@womack.io", + "url": "http://netflix.com" + } + ], + "license": "MIT", + "readme": "\n# constants-browserify\n\nNode's `constants` module for the browser.\n\n[![downloads](https://img.shields.io/npm/dm/constants-browserify.svg)](https://www.npmjs.org/package/constants-browserify)\n\n## Usage\n\nTo use with browserify cli:\n\n```bash\n$ browserify -r constants:constants-browserify script.js\n```\n\nTo use with browserify api:\n\n```js\nbrowserify()\n .require('constants-browserify', { expose: 'constants' })\n .add(__dirname + '/script.js')\n .bundle()\n // ...\n```\n\n## Installation\n\nWith [npm](http://npmjs.org) do\n\n```bash\n$ npm install constants-browserify\n```\n\n## License\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/constants-browserify/issues" + }, + "_id": "constants-browserify@1.0.0", + "_shasum": "c20b96d8c617748aaf1c16021760cd27fcb8cb75", + "_resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", + "_from": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/constants-browserify/test.js b/node_modules/meteor-node-stubs/node_modules/constants-browserify/test.js new file mode 100644 index 0000000..58cc301 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/constants-browserify/test.js @@ -0,0 +1,18 @@ +'use strict'; + +var Assert = require('assert') +var Constants = require('./') + +try { + var nodeConstants = require('constants') + + Assert.deepEqual(nodeConstants, Constants, 'The constants file was not equal') +} + +catch (e) { + console.error(e) + console.error('\nTests failed!') + process.exit(1) +} + +console.info('Tests passed!') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.travis.yml new file mode 100644 index 0000000..1fe31b8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.travis.yml @@ -0,0 +1,31 @@ +sudo: false +language: node_js +matrix: + include: + - node_js: '0.10' + env: TEST_SUITE=unit + - node_js: '0.11' + env: TEST_SUITE=unit + - node_js: '0.12' + env: TEST_SUITE=unit + - node_js: '4' + env: TEST_SUITE=unit + - node_js: '4' + env: TEST_SUITE=standard + - node_js: '4' + env: TEST_SUITE=browser BROWSER_NAME=ie BROWSER_VERSION="10..latest" + - node_js: '4' + env: TEST_SUITE=browser BROWSER_NAME=chrome BROWSER_VERSION="44..beta" + - node_js: '4' + env: TEST_SUITE=browser BROWSER_NAME=firefox BROWSER_VERSION="40..latest" + - node_js: '4' + env: TEST_SUITE=browser BROWSER_NAME=iphone BROWSER_VERSION="8.0..latest" + - node_js: '4' + env: TEST_SUITE=browser BROWSER_NAME=safari BROWSER_VERSION="5..latest" + - node_js: '4' + env: TEST_SUITE=browser BROWSER_NAME=android BROWSER_VERSION="4.0..latest" +script: "npm run-script $TEST_SUITE" +env: + global: + - secure: YHNUDQmx/WiW3gmDcRCfb6KLDeio7Mr5tqPY2kHPdZlBSytsQjNk75ytM4U6Cu8Uk8iEIoj/aFlxiVMpJNA8J4QSUyW/YkbVaIz0+1oywoV0Ht8aRBfZ1jvXfX6789+1Q9c4xaMkYYbJpXSh9JcirsiwmqWd4+IDd7hcESodsDQ= + - secure: Nhj5yejKZxUbtHGZta+GjYWqXGaOZB7ainTkOuGcpXM+OwwjeDpYlTBrwS90Q7hqens7KXVzQM09aDbadpsDCsOo1nyaEigMtomAorZ1UC1CpEoVz1ZuikF9bEhb+/7M9pzuL1fX+Ke9Dx4mPPeb8sf/2SrAu1RqXkSwZV/duAc= diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.zuul.yml new file mode 100644 index 0000000..96d9cfb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/.zuul.yml @@ -0,0 +1 @@ +ui: tape diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/LICENSE new file mode 100644 index 0000000..8abb57d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/LICENSE @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2013 Dominic Tarr + +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software and +associated documentation files (the "Software"), to +deal in the Software without restriction, including +without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom +the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/README.md new file mode 100644 index 0000000..9b0c03b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/README.md @@ -0,0 +1,49 @@ +# crypto-browserify + +A port of node's `crypto` module to the browser. + +[![Build Status](https://travis-ci.org/crypto-browserify/crypto-browserify.svg?branch=master)](https://travis-ci.org/crypto-browserify/crypto-browserify) +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) +[![Sauce Test Status](https://saucelabs.com/browser-matrix/crypto-browserify.svg)](https://saucelabs.com/u/crypto-browserify) + +The goal of this module is to reimplement node's crypto module, +in pure javascript so that it can run in the browser. + +Here is the subset that is currently implemented: + +* createHash (sha1, sha224, sha256, sha384, sha512, md5, rmd160) +* createHmac (sha1, sha224, sha256, sha384, sha512, md5, rmd160) +* pbkdf2 +* pbkdf2Sync +* randomBytes +* pseudoRandomBytes +* createCipher (aes) +* createDecipher (aes) +* createDiffieHellman +* createSign (rsa, ecdsa) +* createVerify (rsa, ecdsa) +* createECDH (secp256k1) +* publicEncrypt/privateDecrypt (rsa) + +## todo + +these features from node's `crypto` are still unimplemented. + +* createCredentials + +## contributions + +If you are interested in writing a feature, please implement as a new module, +which will be incorporated into crypto-browserify as a dependency. + +All deps must be compatible with node's crypto +(generate example inputs and outputs with node, +and save base64 strings inside JSON, so that tests can run in the browser. +see [sha.js](https://github.com/dominictarr/sha.js) + +Crypto is _extra serious_ so please do not hesitate to review the code, +and post comments if you do. + +## License + +MIT diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/bundle.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/bundle.js new file mode 100644 index 0000000..02698cc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/bundle.js @@ -0,0 +1,637 @@ +var require = function (file, cwd) { + var resolved = require.resolve(file, cwd || '/'); + var mod = require.modules[resolved]; + if (!mod) throw new Error( + 'Failed to resolve module ' + file + ', tried ' + resolved + ); + var res = mod._cached ? mod._cached : mod(); + return res; +} + +require.paths = []; +require.modules = {}; +require.extensions = [".js",".coffee"]; + +require._core = { + 'assert': true, + 'events': true, + 'fs': true, + 'path': true, + 'vm': true +}; + +require.resolve = (function () { + return function (x, cwd) { + if (!cwd) cwd = '/'; + + if (require._core[x]) return x; + var path = require.modules.path(); + cwd = path.resolve('/', cwd); + var y = cwd || '/'; + + if (x.match(/^(?:\.\.?\/|\/)/)) { + var m = loadAsFileSync(path.resolve(y, x)) + || loadAsDirectorySync(path.resolve(y, x)); + if (m) return m; + } + + var n = loadNodeModulesSync(x, y); + if (n) return n; + + throw new Error("Cannot find module '" + x + "'"); + + function loadAsFileSync (x) { + if (require.modules[x]) { + return x; + } + + for (var i = 0; i < require.extensions.length; i++) { + var ext = require.extensions[i]; + if (require.modules[x + ext]) return x + ext; + } + } + + function loadAsDirectorySync (x) { + x = x.replace(/\/+$/, ''); + var pkgfile = x + '/package.json'; + if (require.modules[pkgfile]) { + var pkg = require.modules[pkgfile](); + var b = pkg.browserify; + if (typeof b === 'object' && b.main) { + var m = loadAsFileSync(path.resolve(x, b.main)); + if (m) return m; + } + else if (typeof b === 'string') { + var m = loadAsFileSync(path.resolve(x, b)); + if (m) return m; + } + else if (pkg.main) { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + } + } + + return loadAsFileSync(x + '/index'); + } + + function loadNodeModulesSync (x, start) { + var dirs = nodeModulesPathsSync(start); + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + var m = loadAsFileSync(dir + '/' + x); + if (m) return m; + var n = loadAsDirectorySync(dir + '/' + x); + if (n) return n; + } + + var m = loadAsFileSync(x); + if (m) return m; + } + + function nodeModulesPathsSync (start) { + var parts; + if (start === '/') parts = [ '' ]; + else parts = path.normalize(start).split('/'); + + var dirs = []; + for (var i = parts.length - 1; i >= 0; i--) { + if (parts[i] === 'node_modules') continue; + var dir = parts.slice(0, i + 1).join('/') + '/node_modules'; + dirs.push(dir); + } + + return dirs; + } + }; +})(); + +require.alias = function (from, to) { + var path = require.modules.path(); + var res = null; + try { + res = require.resolve(from + '/package.json', '/'); + } + catch (err) { + res = require.resolve(from, '/'); + } + var basedir = path.dirname(res); + + var keys = (Object.keys || function (obj) { + var res = []; + for (var key in obj) res.push(key) + return res; + })(require.modules); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key.slice(0, basedir.length + 1) === basedir + '/') { + var f = key.slice(basedir.length); + require.modules[to + f] = require.modules[basedir + f]; + } + else if (key === basedir) { + require.modules[to] = require.modules[basedir]; + } + } +}; + +require.define = function (filename, fn) { + var dirname = require._core[filename] + ? '' + : require.modules.path().dirname(filename) + ; + + var require_ = function (file) { + return require(file, dirname) + }; + require_.resolve = function (name) { + return require.resolve(name, dirname); + }; + require_.modules = require.modules; + require_.define = require.define; + var module_ = { exports : {} }; + + require.modules[filename] = function () { + require.modules[filename]._cached = module_.exports; + fn.call( + module_.exports, + require_, + module_, + module_.exports, + dirname, + filename + ); + require.modules[filename]._cached = module_.exports; + return module_.exports; + }; +}; + +if (typeof process === 'undefined') process = {}; + +if (!process.nextTick) process.nextTick = (function () { + var queue = []; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; + + if (canPost) { + window.addEventListener('message', function (ev) { + if (ev.source === window && ev.data === 'browserify-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); + } + + return function (fn) { + if (canPost) { + queue.push(fn); + window.postMessage('browserify-tick', '*'); + } + else setTimeout(fn, 0); + }; +})(); + +if (!process.title) process.title = 'browser'; + +if (!process.binding) process.binding = function (name) { + if (name === 'evals') return require('vm') + else throw new Error('No such module') +}; + +if (!process.cwd) process.cwd = function () { return '.' }; + +if (!process.env) process.env = {}; +if (!process.argv) process.argv = []; + +require.define("path", function (require, module, exports, __dirname, __filename) { +function filter (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + if (fn(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length; i >= 0; i--) { + var last = parts[i]; + if (last == '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Regex to split a filename into [*, dir, basename, ext] +// posix version +var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { +var resolvedPath = '', + resolvedAbsolute = false; + +for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) + ? arguments[i] + : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string' || !path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; +} + +// At this point the path should be resolved to a full absolute path, but +// handle relative paths to be safe (might happen when process.cwd() fails) + +// Normalize the path +resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { +var isAbsolute = path.charAt(0) === '/', + trailingSlash = path.slice(-1) === '/'; + +// Normalize the path +path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + return p && typeof p === 'string'; + }).join('/')); +}; + + +exports.dirname = function(path) { + var dir = splitPathRe.exec(path)[1] || ''; + var isWindows = false; + if (!dir) { + // No dirname + return '.'; + } else if (dir.length === 1 || + (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) { + // It is just a slash or a drive letter with a slash + return dir; + } else { + // It is a full dirname, strip trailing slash + return dir.substring(0, dir.length - 1); + } +}; + + +exports.basename = function(path, ext) { + var f = splitPathRe.exec(path)[2] || ''; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPathRe.exec(path)[3] || ''; +}; + +}); + +require.define("crypto", function (require, module, exports, __dirname, __filename) { +module.exports = require("crypto-browserify") +}); + +require.define("/node_modules/crypto-browserify/package.json", function (require, module, exports, __dirname, __filename) { +module.exports = {} +}); + +require.define("/node_modules/crypto-browserify/index.js", function (require, module, exports, __dirname, __filename) { +var sha = require('./sha') + +var algorithms = { + sha1: { + hex: sha.hex_sha1, + binary: sha.b64_sha1, + ascii: sha.str_sha1 + } +} + +function error () { + var m = [].slice.call(arguments).join(' ') + throw new Error([ + m, + 'we accept pull requests', + 'http://github.com/dominictarr/crypto-browserify' + ].join('\n')) +} + +exports.createHash = function (alg) { + alg = alg || 'sha1' + if(!algorithms[alg]) + error('algorithm:', alg, 'is not yet supported') + var s = '' + _alg = algorithms[alg] + return { + update: function (data) { + s += data + return this + }, + digest: function (enc) { + enc = enc || 'binary' + var fn + if(!(fn = _alg[enc])) + error('encoding:', enc , 'is not yet supported for algorithm', alg) + var r = fn(s) + s = null //not meant to use the hash after you've called digest. + return r + } + } +} +// the least I can do is make error messages for the rest of the node.js/crypto api. +;['createCredentials' +, 'createHmac' +, 'createCypher' +, 'createCypheriv' +, 'createDecipher' +, 'createDecipheriv' +, 'createSign' +, 'createVerify' +, 'createDeffieHellman', +, 'pbkdf2', +, 'randomBytes' ].forEach(function (name) { + exports[name] = function () { + error('sorry,', name, 'is not implemented yet') + } +}) + +}); + +require.define("/node_modules/crypto-browserify/sha.js", function (require, module, exports, __dirname, __filename) { +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +exports.hex_sha1 = hex_sha1; +exports.b64_sha1 = b64_sha1; +exports.str_sha1 = str_sha1; +exports.hex_hmac_sha1 = hex_hmac_sha1; +exports.b64_hmac_sha1 = b64_hmac_sha1; +exports.str_hmac_sha1 = str_hmac_sha1; + +/* + * Configurable variables. You may need to tweak these to be compatible with + * the server-side, but the defaults work in most cases. + */ +var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ +var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ +var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ + +/* + * These are the functions you'll usually want to call + * They take string arguments and return either hex or base-64 encoded strings + */ +function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));} +function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));} +function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));} +function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));} +function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));} +function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));} + +/* + * Perform a simple self-test to see if the VM is working + */ +function sha1_vm_test() +{ + return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d"; +} + +/* + * Calculate the SHA-1 of an array of big-endian words, and a bit length + */ +function core_sha1(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << (24 - len % 32); + x[((len + 64 >> 9) << 4) + 15] = len; + + var w = Array(80); + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + var e = -1009589776; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + var olde = e; + + for(var j = 0; j < 80; j++) + { + if(j < 16) w[j] = x[i + j]; + else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); + var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), + safe_add(safe_add(e, w[j]), sha1_kt(j))); + e = d; + d = c; + c = rol(b, 30); + b = a; + a = t; + } + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + e = safe_add(e, olde); + } + return Array(a, b, c, d, e); + +} + +/* + * Perform the appropriate triplet combination function for the current + * iteration + */ +function sha1_ft(t, b, c, d) +{ + if(t < 20) return (b & c) | ((~b) & d); + if(t < 40) return b ^ c ^ d; + if(t < 60) return (b & c) | (b & d) | (c & d); + return b ^ c ^ d; +} + +/* + * Determine the appropriate additive constant for the current iteration + */ +function sha1_kt(t) +{ + return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : + (t < 60) ? -1894007588 : -899497514; +} + +/* + * Calculate the HMAC-SHA1 of a key and some data + */ +function core_hmac_sha1(key, data) +{ + var bkey = str2binb(key); + if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz); + + var ipad = Array(16), opad = Array(16); + for(var i = 0; i < 16; i++) + { + ipad[i] = bkey[i] ^ 0x36363636; + opad[i] = bkey[i] ^ 0x5C5C5C5C; + } + + var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz); + return core_sha1(opad.concat(hash), 512 + 160); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +/* + * Convert an 8-bit or 16-bit string to an array of big-endian words + * In 8-bit function, characters >255 have their hi-byte silently ignored. + */ +function str2binb(str) +{ + var bin = Array(); + var mask = (1 << chrsz) - 1; + for(var i = 0; i < str.length * chrsz; i += chrsz) + bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32); + return bin; +} + +/* + * Convert an array of big-endian words to a string + */ +function binb2str(bin) +{ + var str = ""; + var mask = (1 << chrsz) - 1; + for(var i = 0; i < bin.length * 32; i += chrsz) + str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask); + return str; +} + +/* + * Convert an array of big-endian words to a hex string. + */ +function binb2hex(binarray) +{ + var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; + var str = ""; + for(var i = 0; i < binarray.length * 4; i++) + { + str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) + + hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF); + } + return str; +} + +/* + * Convert an array of big-endian words to a base-64 string + */ +function binb2b64(binarray) +{ + var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var str = ""; + for(var i = 0; i < binarray.length * 4; i += 3) + { + var triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16) + | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 ) + | ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF); + for(var j = 0; j < 4; j++) + { + if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; + else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); + } + } + return str; +} + + +}); + +require.define("/test.js", function (require, module, exports, __dirname, __filename) { + var crypto = require('crypto') +var abc = crypto.createHash('sha1').update('abc').digest('hex') +console.log(abc) +//require('hello').inlineCall().call2() + +}); +require("/test.js"); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/index.html b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/index.html new file mode 100644 index 0000000..9d55c6d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/index.html @@ -0,0 +1,12 @@ + + + + +
+  require('crypto').createHash('sha1').update('abc').digest('hex') == ''
+  
+ + + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/test.js new file mode 100644 index 0000000..0b76c01 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/example/test.js @@ -0,0 +1,4 @@ +var crypto = require('crypto') +var abc = crypto.createHash('sha1').update('abc').digest('hex') +console.log(abc) +// require('hello').inlineCall().call2() diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/index.js new file mode 100644 index 0000000..ea632aa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/index.js @@ -0,0 +1,77 @@ +'use strict' + +exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes') +exports.createHash = exports.Hash = require('create-hash') +exports.createHmac = exports.Hmac = require('create-hmac') + +var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(Object.keys(require('browserify-sign/algos'))) +exports.getHashes = function () { + return hashes +} + +var p = require('pbkdf2') +exports.pbkdf2 = p.pbkdf2 +exports.pbkdf2Sync = p.pbkdf2Sync + +var aes = require('browserify-cipher') +;[ + 'Cipher', + 'createCipher', + 'Cipheriv', + 'createCipheriv', + 'Decipher', + 'createDecipher', + 'Decipheriv', + 'createDecipheriv', + 'getCiphers', + 'listCiphers' +].forEach(function (key) { + exports[key] = aes[key] +}) + +var dh = require('diffie-hellman') +;[ + 'DiffieHellmanGroup', + 'createDiffieHellmanGroup', + 'getDiffieHellman', + 'createDiffieHellman', + 'DiffieHellman' +].forEach(function (key) { + exports[key] = dh[key] +}) + +var sign = require('browserify-sign') +;[ + 'createSign', + 'Sign', + 'createVerify', + 'Verify' +].forEach(function (key) { + exports[key] = sign[key] +}) + +exports.createECDH = require('create-ecdh') + +var publicEncrypt = require('public-encrypt') + +;[ + 'publicEncrypt', + 'privateEncrypt', + 'publicDecrypt', + 'privateDecrypt' +].forEach(function (key) { + exports[key] = publicEncrypt[key] +}) + +// the least I can do is make error messages for the rest of the node.js/crypto api. +;[ + 'createCredentials' +].forEach(function (name) { + exports[name] = function () { + throw new Error([ + 'sorry, ' + name + ' is not implemented yet', + 'we accept pull requests', + 'https://github.com/crypto-browserify/crypto-browserify' + ].join('\n')) + } +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/browser.js new file mode 100644 index 0000000..e009f93 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/browser.js @@ -0,0 +1,73 @@ +var ebtk = require('evp_bytestokey') +var aes = require('browserify-aes/browser') +var DES = require('browserify-des') +var desModes = require('browserify-des/modes') +var aesModes = require('browserify-aes/modes') +function createCipher (suite, password) { + var keyLen, ivLen + suite = suite.toLowerCase() + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, keyLen, ivLen) + return createCipheriv(suite, keys.key, keys.iv) +} +function createDecipher (suite, password) { + var keyLen, ivLen + suite = suite.toLowerCase() + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, keyLen, ivLen) + return createDecipheriv(suite, keys.key, keys.iv) +} + +function createCipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) { + return aes.createCipheriv(suite, key, iv) + } else if (desModes[suite]) { + return new DES({ + key: key, + iv: iv, + mode: suite + }) + } else { + throw new TypeError('invalid suite type') + } +} +function createDecipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) { + return aes.createDecipheriv(suite, key, iv) + } else if (desModes[suite]) { + return new DES({ + key: key, + iv: iv, + mode: suite, + decrypt: true + }) + } else { + throw new TypeError('invalid suite type') + } +} +exports.createCipher = exports.Cipher = createCipher +exports.createCipheriv = exports.Cipheriv = createCipheriv +exports.createDecipher = exports.Decipher = createDecipher +exports.createDecipheriv = exports.Decipheriv = createDecipheriv +function getCiphers () { + return Object.keys(desModes).concat(aes.getCiphers()) +} +exports.listCiphers = exports.getCiphers = getCiphers diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/index.js new file mode 100644 index 0000000..58fa883 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/index.js @@ -0,0 +1,7 @@ +var crypto = require('crypto') + +exports.createCipher = exports.Cipher = crypto.createCipher +exports.createCipheriv = exports.Cipheriv = crypto.createCipheriv +exports.createDecipher = exports.Decipher = crypto.createDecipher +exports.createDecipheriv = exports.Decipheriv = crypto.createDecipheriv +exports.listCiphers = exports.getCiphers = crypto.getCiphers diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.eslintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.eslintrc new file mode 100644 index 0000000..bed248a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.eslintrc @@ -0,0 +1,132 @@ +{ + "ecmaFeatures": { + "modules": true, + "experimentalObjectRestSpread": true + }, + + "env": { + "browser": false, + "es6": true, + "node": true + }, + + "plugins": [ + "standard" + ], + + "globals": { + "document": false, + "navigator": false, + "window": false + }, + + "rules": { + "accessor-pairs": 2, + "arrow-spacing": [2, { "before": true, "after": true }], + "block-spacing": [2, "always"], + "brace-style": [2, "1tbs", { "allowSingleLine": true }], + "comma-dangle": [2, "never"], + "comma-spacing": [2, { "before": false, "after": true }], + "comma-style": [2, "last"], + "constructor-super": 2, + "curly": [2, "multi-line"], + "dot-location": [2, "property"], + "eol-last": 2, + "eqeqeq": [2, "allow-null"], + "generator-star-spacing": [2, { "before": true, "after": true }], + "handle-callback-err": [2, "^(err|error)$" ], + "indent": [2, 2, { "SwitchCase": 1 }], + "key-spacing": [2, { "beforeColon": false, "afterColon": true }], + "new-cap": [2, { "newIsCap": true, "capIsNew": false }], + "new-parens": 2, + "no-array-constructor": 2, + "no-caller": 2, + "no-class-assign": 2, + "no-cond-assign": 2, + "no-const-assign": 2, + "no-control-regex": 2, + "no-debugger": 2, + "no-delete-var": 2, + "no-dupe-args": 2, + "no-dupe-class-members": 2, + "no-dupe-keys": 2, + "no-duplicate-case": 2, + "no-empty-character-class": 2, + "no-empty-label": 2, + "no-eval": 2, + "no-ex-assign": 2, + "no-extend-native": 2, + "no-extra-bind": 2, + "no-extra-boolean-cast": 2, + "no-extra-parens": [2, "functions"], + "no-fallthrough": 2, + "no-floating-decimal": 2, + "no-func-assign": 2, + "no-implied-eval": 2, + "no-inner-declarations": [2, "functions"], + "no-invalid-regexp": 2, + "no-irregular-whitespace": 2, + "no-iterator": 2, + "no-label-var": 2, + "no-labels": 2, + "no-lone-blocks": 2, + "no-mixed-spaces-and-tabs": 2, + "no-multi-spaces": 2, + "no-multi-str": 2, + "no-multiple-empty-lines": [2, { "max": 1 }], + "no-native-reassign": 2, + "no-negated-in-lhs": 2, + "no-new": 2, + "no-new-func": 2, + "no-new-object": 2, + "no-new-require": 2, + "no-new-wrappers": 2, + "no-obj-calls": 2, + "no-octal": 2, + "no-octal-escape": 2, + "no-proto": 2, + "no-redeclare": 2, + "no-regex-spaces": 2, + "no-return-assign": 2, + "no-self-compare": 2, + "no-sequences": 2, + "no-shadow-restricted-names": 2, + "no-spaced-func": 2, + "no-sparse-arrays": 2, + "no-this-before-super": 2, + "no-throw-literal": 2, + "no-trailing-spaces": 2, + "no-undef": 2, + "no-undef-init": 2, + "no-unexpected-multiline": 2, + "no-unneeded-ternary": [2, { "defaultAssignment": false }], + "no-unreachable": 2, + "no-unused-vars": [2, { "vars": "all", "args": "none" }], + "no-useless-call": 2, + "no-with": 2, + "one-var": [2, { "initialized": "never" }], + "operator-linebreak": [2, "after", { "overrides": { "?": "before", ":": "before" } }], + "padded-blocks": [2, "never"], + "quotes": [2, "single", "avoid-escape"], + "radix": 2, + "semi": [2, "never"], + "semi-spacing": [2, { "before": false, "after": true }], + "space-after-keywords": [2, "always"], + "space-before-blocks": [2, "always"], + "space-before-function-paren": [2, "always"], + "space-before-keywords": [2, "always"], + "space-in-parens": [2, "never"], + "space-infix-ops": 2, + "space-return-throw-case": 2, + "space-unary-ops": [2, { "words": true, "nonwords": false }], + "spaced-comment": [2, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }], + "use-isnan": 2, + "valid-typeof": 2, + "wrap-iife": [2, "any"], + "yoda": [2, "never"], + + "standard/object-curly-even-spacing": [2, "either"], + "standard/array-bracket-even-spacing": [2, "either"], + "standard/computed-property-even-spacing": [2, "even"] + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.npmignore new file mode 100644 index 0000000..65e3ba2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.npmignore @@ -0,0 +1 @@ +test/ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/LICENSE new file mode 100644 index 0000000..924b38b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 browserify-aes contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/aes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/aes.js new file mode 100644 index 0000000..4829057 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/aes.js @@ -0,0 +1,177 @@ +// based on the aes implimentation in triple sec +// https://github.com/keybase/triplesec + +// which is in turn based on the one from crypto-js +// https://code.google.com/p/crypto-js/ + +var uint_max = Math.pow(2, 32) +function fixup_uint32 (x) { + var ret, x_pos + ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x + return ret +} +function scrub_vec (v) { + for (var i = 0; i < v.length; v++) { + v[i] = 0 + } + return false +} + +function Global () { + this.SBOX = [] + this.INV_SBOX = [] + this.SUB_MIX = [[], [], [], []] + this.INV_SUB_MIX = [[], [], [], []] + this.init() + this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] +} + +Global.prototype.init = function () { + var d, i, sx, t, x, x2, x4, x8, xi, _i + d = (function () { + var _i, _results + _results = [] + for (i = _i = 0; _i < 256; i = ++_i) { + if (i < 128) { + _results.push(i << 1) + } else { + _results.push((i << 1) ^ 0x11b) + } + } + return _results + })() + x = 0 + xi = 0 + for (i = _i = 0; _i < 256; i = ++_i) { + sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 + this.SBOX[x] = sx + this.INV_SBOX[sx] = x + x2 = d[x] + x4 = d[x2] + x8 = d[x4] + t = (d[sx] * 0x101) ^ (sx * 0x1010100) + this.SUB_MIX[0][x] = (t << 24) | (t >>> 8) + this.SUB_MIX[1][x] = (t << 16) | (t >>> 16) + this.SUB_MIX[2][x] = (t << 8) | (t >>> 24) + this.SUB_MIX[3][x] = t + t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) + this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) + this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) + this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) + this.INV_SUB_MIX[3][sx] = t + if (x === 0) { + x = xi = 1 + } else { + x = x2 ^ d[d[d[x8 ^ x2]]] + xi ^= d[d[xi]] + } + } + return true +} + +var G = new Global() + +AES.blockSize = 4 * 4 + +AES.prototype.blockSize = AES.blockSize + +AES.keySize = 256 / 8 + +AES.prototype.keySize = AES.keySize + +function bufferToArray (buf) { + var len = buf.length / 4 + var out = new Array(len) + var i = -1 + while (++i < len) { + out[i] = buf.readUInt32BE(i * 4) + } + return out +} +function AES (key) { + this._key = bufferToArray(key) + this._doReset() +} + +AES.prototype._doReset = function () { + var invKsRow, keySize, keyWords, ksRow, ksRows, t + keyWords = this._key + keySize = keyWords.length + this._nRounds = keySize + 6 + ksRows = (this._nRounds + 1) * 4 + this._keySchedule = [] + for (ksRow = 0; ksRow < ksRows; ksRow++) { + this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t) + } + this._invKeySchedule = [] + for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { + ksRow = ksRows - invKsRow + t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)] + this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]] + } + return true +} + +AES.prototype.encryptBlock = function (M) { + M = bufferToArray(new Buffer(M)) + var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} + +AES.prototype.decryptBlock = function (M) { + M = bufferToArray(new Buffer(M)) + var temp = [M[3], M[1]] + M[1] = temp[0] + M[3] = temp[1] + var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[3], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[1], 12) + return buf +} + +AES.prototype.scrub = function () { + scrub_vec(this._keySchedule) + scrub_vec(this._invKeySchedule) + scrub_vec(this._key) +} + +AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) { + var ksRow, s0, s1, s2, s3, t0, t1, t2, t3 + + s0 = M[0] ^ keySchedule[0] + s1 = M[1] ^ keySchedule[1] + s2 = M[2] ^ keySchedule[2] + s3 = M[3] ^ keySchedule[3] + ksRow = 4 + for (var round = 1; round < this._nRounds; round++) { + t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++] + t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++] + t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + s2 = t2 + s3 = t3 + } + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] + t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] + t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + return [ + fixup_uint32(t0), + fixup_uint32(t1), + fixup_uint32(t2), + fixup_uint32(t3) + ] +} + +exports.AES = AES diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/authCipher.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/authCipher.js new file mode 100644 index 0000000..1107a01 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/authCipher.js @@ -0,0 +1,97 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var GHASH = require('./ghash') +var xor = require('buffer-xor') +inherits(StreamCipher, Transform) +module.exports = StreamCipher + +function StreamCipher (mode, key, iv, decrypt) { + if (!(this instanceof StreamCipher)) { + return new StreamCipher(mode, key, iv) + } + Transform.call(this) + this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])]) + iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])]) + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + this._cache = new Buffer('') + this._secCache = new Buffer('') + this._decrypt = decrypt + this._alen = 0 + this._len = 0 + iv.copy(this._prev) + this._mode = mode + var h = new Buffer(4) + h.fill(0) + this._ghash = new GHASH(this._cipher.encryptBlock(h)) + this._authTag = null + this._called = false +} +StreamCipher.prototype._update = function (chunk) { + if (!this._called && this._alen) { + var rump = 16 - (this._alen % 16) + if (rump < 16) { + rump = new Buffer(rump) + rump.fill(0) + this._ghash.update(rump) + } + } + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) + } else { + this._ghash.update(out) + } + this._len += chunk.length + return out +} +StreamCipher.prototype._final = function () { + if (this._decrypt && !this._authTag) { + throw new Error('Unsupported state or unable to authenticate data') + } + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) + if (this._decrypt) { + if (xorTest(tag, this._authTag)) { + throw new Error('Unsupported state or unable to authenticate data') + } + } else { + this._authTag = tag + } + this._cipher.scrub() +} +StreamCipher.prototype.getAuthTag = function getAuthTag () { + if (!this._decrypt && Buffer.isBuffer(this._authTag)) { + return this._authTag + } else { + throw new Error('Attempting to get auth tag in unsupported state') + } +} +StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { + if (this._decrypt) { + this._authTag = tag + } else { + throw new Error('Attempting to set auth tag in unsupported state') + } +} +StreamCipher.prototype.setAAD = function setAAD (buf) { + if (!this._called) { + this._ghash.update(buf) + this._alen += buf.length + } else { + throw new Error('Attempting to set AAD in unsupported state') + } +} +function xorTest (a, b) { + var out = 0 + if (a.length !== b.length) { + out++ + } + var len = Math.min(a.length, b.length) + var i = -1 + while (++i < len) { + out += (a[i] ^ b[i]) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/browser.js new file mode 100644 index 0000000..a058a84 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/browser.js @@ -0,0 +1,11 @@ +var ciphers = require('./encrypter') +exports.createCipher = exports.Cipher = ciphers.createCipher +exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv +var deciphers = require('./decrypter') +exports.createDecipher = exports.Decipher = deciphers.createDecipher +exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv +var modes = require('./modes') +function getCiphers () { + return Object.keys(modes) +} +exports.listCiphers = exports.getCiphers = getCiphers diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/decrypter.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/decrypter.js new file mode 100644 index 0000000..b7b8bb0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/decrypter.js @@ -0,0 +1,137 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var modes = require('./modes') +var StreamCipher = require('./streamCipher') +var AuthCipher = require('./authCipher') +var ebtk = require('evp_bytestokey') + +inherits(Decipher, Transform) +function Decipher (mode, key, iv) { + if (!(this instanceof Decipher)) { + return new Decipher(mode, key, iv) + } + Transform.call(this) + this._cache = new Splitter() + this._last = void 0 + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + iv.copy(this._prev) + this._mode = mode + this._autopadding = true +} +Decipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get(this._autopadding))) { + thing = this._mode.decrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} +Decipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)) + } else if (chunk) { + throw new Error('data not multiple of block length') + } +} +Decipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} +function Splitter () { + if (!(this instanceof Splitter)) { + return new Splitter() + } + this.cache = new Buffer('') +} +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function (autoPadding) { + var out + if (autoPadding) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } + return null +} +Splitter.prototype.flush = function () { + if (this.cache.length) { + return this.cache + } +} +function unpad (last) { + var padded = last[15] + var i = -1 + while (++i < padded) { + if (last[(i + (16 - padded))] !== padded) { + throw new Error('unable to decrypt data') + } + } + if (padded === 16) { + return + } + return last.slice(0, 16 - padded) +} + +var modelist = { + ECB: require('./modes/ecb'), + CBC: require('./modes/cbc'), + CFB: require('./modes/cfb'), + CFB8: require('./modes/cfb8'), + CFB1: require('./modes/cfb1'), + OFB: require('./modes/ofb'), + CTR: require('./modes/ctr'), + GCM: require('./modes/ctr') +} + +function createDecipheriv (suite, password, iv) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + if (typeof iv === 'string') { + iv = new Buffer(iv) + } + if (typeof password === 'string') { + password = new Buffer(password) + } + if (password.length !== config.key / 8) { + throw new TypeError('invalid key length ' + password.length) + } + if (iv.length !== config.iv) { + throw new TypeError('invalid iv length ' + iv.length) + } + if (config.type === 'stream') { + return new StreamCipher(modelist[config.mode], password, iv, true) + } else if (config.type === 'auth') { + return new AuthCipher(modelist[config.mode], password, iv, true) + } + return new Decipher(modelist[config.mode], password, iv) +} + +function createDecipher (suite, password) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, config.key, config.iv) + return createDecipheriv(suite, keys.key, keys.iv) +} +exports.createDecipher = createDecipher +exports.createDecipheriv = createDecipheriv diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/encrypter.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/encrypter.js new file mode 100644 index 0000000..3d3f561 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/encrypter.js @@ -0,0 +1,122 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var modes = require('./modes') +var ebtk = require('evp_bytestokey') +var StreamCipher = require('./streamCipher') +var AuthCipher = require('./authCipher') +inherits(Cipher, Transform) +function Cipher (mode, key, iv) { + if (!(this instanceof Cipher)) { + return new Cipher(mode, key, iv) + } + Transform.call(this) + this._cache = new Splitter() + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + iv.copy(this._prev) + this._mode = mode + this._autopadding = true +} +Cipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get())) { + thing = this._mode.encrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} +Cipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + chunk = this._mode.encrypt(this, chunk) + this._cipher.scrub() + return chunk + } else if (chunk.toString('hex') !== '10101010101010101010101010101010') { + this._cipher.scrub() + throw new Error('data not multiple of block length') + } +} +Cipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + if (!(this instanceof Splitter)) { + return new Splitter() + } + this.cache = new Buffer('') +} +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function () { + if (this.cache.length > 15) { + var out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + return null +} +Splitter.prototype.flush = function () { + var len = 16 - this.cache.length + var padBuff = new Buffer(len) + + var i = -1 + while (++i < len) { + padBuff.writeUInt8(len, i) + } + var out = Buffer.concat([this.cache, padBuff]) + return out +} +var modelist = { + ECB: require('./modes/ecb'), + CBC: require('./modes/cbc'), + CFB: require('./modes/cfb'), + CFB8: require('./modes/cfb8'), + CFB1: require('./modes/cfb1'), + OFB: require('./modes/ofb'), + CTR: require('./modes/ctr'), + GCM: require('./modes/ctr') +} + +function createCipheriv (suite, password, iv) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + if (typeof iv === 'string') { + iv = new Buffer(iv) + } + if (typeof password === 'string') { + password = new Buffer(password) + } + if (password.length !== config.key / 8) { + throw new TypeError('invalid key length ' + password.length) + } + if (iv.length !== config.iv) { + throw new TypeError('invalid iv length ' + iv.length) + } + if (config.type === 'stream') { + return new StreamCipher(modelist[config.mode], password, iv) + } else if (config.type === 'auth') { + return new AuthCipher(modelist[config.mode], password, iv) + } + return new Cipher(modelist[config.mode], password, iv) +} +function createCipher (suite, password) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, config.key, config.iv) + return createCipheriv(suite, keys.key, keys.iv) +} + +exports.createCipheriv = createCipheriv +exports.createCipher = createCipher diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/ghash.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/ghash.js new file mode 100644 index 0000000..0ca143c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/ghash.js @@ -0,0 +1,98 @@ +var zeros = new Buffer(16) +zeros.fill(0) +module.exports = GHASH +function GHASH (key) { + this.h = key + this.state = new Buffer(16) + this.state.fill(0) + this.cache = new Buffer('') +} +// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html +// by Juho Vähä-Herttua +GHASH.prototype.ghash = function (block) { + var i = -1 + while (++i < block.length) { + this.state[i] ^= block[i] + } + this._multiply() +} + +GHASH.prototype._multiply = function () { + var Vi = toArray(this.h) + var Zi = [0, 0, 0, 0] + var j, xi, lsb_Vi + var i = -1 + while (++i < 128) { + xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0 + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi = xor(Zi, Vi) + } + + // Store the value of LSB(V_i) + lsb_Vi = (Vi[3] & 1) !== 0 + + // V_i+1 = V_i >> 1 + for (j = 3; j > 0; j--) { + Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) + } + Vi[0] = Vi[0] >>> 1 + + // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R + if (lsb_Vi) { + Vi[0] = Vi[0] ^ (0xe1 << 24) + } + } + this.state = fromArray(Zi) +} +GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + this.ghash(chunk) + } +} +GHASH.prototype.final = function (abl, bl) { + if (this.cache.length) { + this.ghash(Buffer.concat([this.cache, zeros], 16)) + } + this.ghash(fromArray([ + 0, abl, + 0, bl + ])) + return this.state +} + +function toArray (buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] +} +function fromArray (out) { + out = out.map(fixup_uint32) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} +var uint_max = Math.pow(2, 32) +function fixup_uint32 (x) { + var ret, x_pos + ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x + return ret +} +function xor (a, b) { + return [ + a[0] ^ b[0], + a[1] ^ b[1], + a[2] ^ b[2], + a[3] ^ b[3] + ] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/index.js new file mode 100644 index 0000000..58fa883 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/index.js @@ -0,0 +1,7 @@ +var crypto = require('crypto') + +exports.createCipher = exports.Cipher = crypto.createCipher +exports.createCipheriv = exports.Cipheriv = crypto.createCipheriv +exports.createDecipher = exports.Decipher = crypto.createDecipher +exports.createDecipheriv = exports.Decipheriv = crypto.createDecipheriv +exports.listCiphers = exports.getCiphers = crypto.getCiphers diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes.js new file mode 100644 index 0000000..c070086 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes.js @@ -0,0 +1,171 @@ +exports['aes-128-ecb'] = { + cipher: 'AES', + key: 128, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-192-ecb'] = { + cipher: 'AES', + key: 192, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-256-ecb'] = { + cipher: 'AES', + key: 256, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-128-cbc'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes-192-cbc'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes-256-cbc'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes128'] = exports['aes-128-cbc'] +exports['aes192'] = exports['aes-192-cbc'] +exports['aes256'] = exports['aes-256-cbc'] +exports['aes-128-cfb'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-192-cfb'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-256-cfb'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-128-cfb8'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-192-cfb8'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-256-cfb8'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-128-cfb1'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-192-cfb1'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-256-cfb1'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-128-ofb'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-192-ofb'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-256-ofb'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-128-ctr'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-192-ctr'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-256-ctr'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-128-gcm'] = { + cipher: 'AES', + key: 128, + iv: 12, + mode: 'GCM', + type: 'auth' +} +exports['aes-192-gcm'] = { + cipher: 'AES', + key: 192, + iv: 12, + mode: 'GCM', + type: 'auth' +} +exports['aes-256-gcm'] = { + cipher: 'AES', + key: 256, + iv: 12, + mode: 'GCM', + type: 'auth' +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cbc.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cbc.js new file mode 100644 index 0000000..b133e40 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cbc.js @@ -0,0 +1,17 @@ +var xor = require('buffer-xor') + +exports.encrypt = function (self, block) { + var data = xor(block, self._prev) + + self._prev = self._cipher.encryptBlock(data) + return self._prev +} + +exports.decrypt = function (self, block) { + var pad = self._prev + + self._prev = block + var out = self._cipher.decryptBlock(block) + + return xor(out, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb.js new file mode 100644 index 0000000..0bfe4fa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb.js @@ -0,0 +1,31 @@ +var xor = require('buffer-xor') + +exports.encrypt = function (self, data, decrypt) { + var out = new Buffer('') + var len + + while (data.length) { + if (self._cache.length === 0) { + self._cache = self._cipher.encryptBlock(self._prev) + self._prev = new Buffer('') + } + + if (self._cache.length <= data.length) { + len = self._cache.length + out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) + data = data.slice(len) + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]) + break + } + } + + return out +} +function encryptStart (self, data, decrypt) { + var len = data.length + var out = xor(data, self._cache) + self._cache = self._cache.slice(len) + self._prev = Buffer.concat([self._prev, decrypt ? data : out]) + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb1.js new file mode 100644 index 0000000..335542e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb1.js @@ -0,0 +1,34 @@ +function encryptByte (self, byteParam, decrypt) { + var pad + var i = -1 + var len = 8 + var out = 0 + var bit, value + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev) + bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 + value = pad[0] ^ bit + out += ((value & 0x80) >> (i % 8)) + self._prev = shiftIn(self._prev, decrypt ? bit : value) + } + return out +} +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = new Buffer(len) + var i = -1 + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + return out +} +function shiftIn (buffer, value) { + var len = buffer.length + var i = -1 + var out = new Buffer(buffer.length) + buffer = Buffer.concat([buffer, new Buffer([value])]) + while (++i < len) { + out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb8.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb8.js new file mode 100644 index 0000000..c967a95 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/cfb8.js @@ -0,0 +1,15 @@ +function encryptByte (self, byteParam, decrypt) { + var pad = self._cipher.encryptBlock(self._prev) + var out = pad[0] ^ byteParam + self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])]) + return out +} +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = new Buffer(len) + var i = -1 + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ctr.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ctr.js new file mode 100644 index 0000000..0ef2278 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ctr.js @@ -0,0 +1,31 @@ +var xor = require('buffer-xor') + +function incr32 (iv) { + var len = iv.length + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } +} + +function getBlock (self) { + var out = self._cipher.encryptBlock(self._prev) + incr32(self._prev) + return out +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ecb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ecb.js new file mode 100644 index 0000000..4dd97e7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ecb.js @@ -0,0 +1,6 @@ +exports.encrypt = function (self, block) { + return self._cipher.encryptBlock(block) +} +exports.decrypt = function (self, block) { + return self._cipher.decryptBlock(block) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ofb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ofb.js new file mode 100644 index 0000000..bd87558 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/modes/ofb.js @@ -0,0 +1,16 @@ +var xor = require('buffer-xor') + +function getBlock (self) { + self._prev = self._cipher.encryptBlock(self._prev) + return self._prev +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml new file mode 100644 index 0000000..d9f695b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +before_install: + - "npm install npm -g" +node_js: + - "0.12" +env: + - TEST_SUITE=standard + - TEST_SUITE=unit +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE new file mode 100644 index 0000000..bba5218 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Daniel Cousens + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/README.md new file mode 100644 index 0000000..007f058 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/README.md @@ -0,0 +1,41 @@ +# buffer-xor + +[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-xor.png)](http://travis-ci.org/crypto-browserify/buffer-xor) +[![NPM](http://img.shields.io/npm/v/buffer-xor.svg)](https://www.npmjs.org/package/buffer-xor) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +A simple module for bitwise-xor on buffers. + + +## Examples + +``` javascript +var xor = require("buffer-xor") +var a = new Buffer('00ff0f', 'hex') +var b = new Buffer('f0f0', 'hex') + +console.log(xor(a, b)) +// => +``` + + +Or for those seeking those few extra cycles, perform the operation in place: + +``` javascript +var xorInplace = require("buffer-xor/inplace") +var a = new Buffer('00ff0f', 'hex') +var b = new Buffer('f0f0', 'hex') + +console.log(xorInplace(a, b)) +// => +// NOTE: xorInplace will return the shorter slice of its parameters + +// See that a has been mutated +console.log(a) +// => +``` + + +## License [MIT](LICENSE) + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/index.js new file mode 100644 index 0000000..85ee6f6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/index.js @@ -0,0 +1,10 @@ +module.exports = function xor (a, b) { + var length = Math.min(a.length, b.length) + var buffer = new Buffer(length) + + for (var i = 0; i < length; ++i) { + buffer[i] = a[i] ^ b[i] + } + + return buffer +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/inline.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/inline.js new file mode 100644 index 0000000..8797570 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/inline.js @@ -0,0 +1 @@ +module.exports = require('./inplace') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js new file mode 100644 index 0000000..d71c172 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js @@ -0,0 +1,9 @@ +module.exports = function xorInplace (a, b) { + var length = Math.min(a.length, b.length) + + for (var i = 0; i < length; ++i) { + a[i] = a[i] ^ b[i] + } + + return a.slice(0, length) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/package.json new file mode 100644 index 0000000..31c573c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/package.json @@ -0,0 +1,45 @@ +{ + "name": "buffer-xor", + "version": "1.0.3", + "description": "A simple module for bitwise-xor on buffers", + "main": "index.js", + "scripts": { + "standard": "standard", + "test": "npm run-script unit", + "unit": "mocha" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/buffer-xor.git" + }, + "bugs": { + "url": "https://github.com/crypto-browserify/buffer-xor/issues" + }, + "homepage": "https://github.com/crypto-browserify/buffer-xor", + "keywords": [ + "bits", + "bitwise", + "buffer", + "buffer-xor", + "crypto", + "inline", + "math", + "memory", + "performance", + "xor" + ], + "author": { + "name": "Daniel Cousens" + }, + "license": "MIT", + "devDependencies": { + "mocha": "*", + "standard": "*" + }, + "readme": "# buffer-xor\n\n[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-xor.png)](http://travis-ci.org/crypto-browserify/buffer-xor)\n[![NPM](http://img.shields.io/npm/v/buffer-xor.svg)](https://www.npmjs.org/package/buffer-xor)\n\n[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n\nA simple module for bitwise-xor on buffers.\n\n\n## Examples\n\n``` javascript\nvar xor = require(\"buffer-xor\")\nvar a = new Buffer('00ff0f', 'hex')\nvar b = new Buffer('f0f0', 'hex')\n\nconsole.log(xor(a, b))\n// => \n```\n\n\nOr for those seeking those few extra cycles, perform the operation in place:\n\n``` javascript\nvar xorInplace = require(\"buffer-xor/inplace\")\nvar a = new Buffer('00ff0f', 'hex')\nvar b = new Buffer('f0f0', 'hex')\n\nconsole.log(xorInplace(a, b))\n// => \n// NOTE: xorInplace will return the shorter slice of its parameters\n\n// See that a has been mutated\nconsole.log(a)\n// => \n```\n\n\n## License [MIT](LICENSE)\n\n", + "readmeFilename": "README.md", + "_id": "buffer-xor@1.0.3", + "_shasum": "26e61ed1422fb70dd42e6e36729ed51d855fe8d9", + "_resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "_from": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json new file mode 100644 index 0000000..6f3431e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json @@ -0,0 +1,23 @@ +[ + { + "a": "000f", + "b": "f0ff", + "expected": "f0f0" + }, + { + "a": "000f0f", + "b": "f0ff", + "mutated": "f0f00f", + "expected": "f0f0" + }, + { + "a": "000f", + "b": "f0ffff", + "expected": "f0f0" + }, + { + "a": "000000", + "b": "000000", + "expected": "000000" + } +] diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js new file mode 100644 index 0000000..06eacab --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js @@ -0,0 +1,38 @@ +/* global describe, it */ + +var assert = require('assert') +var xor = require('../') +var xorInplace = require('../inplace') +var fixtures = require('./fixtures') + +describe('xor', function () { + fixtures.forEach(function (f) { + it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () { + var a = new Buffer(f.a, 'hex') + var b = new Buffer(f.b, 'hex') + var actual = xor(a, b) + + assert.equal(actual.toString('hex'), f.expected) + + // a/b unchanged + assert.equal(a.toString('hex'), f.a) + assert.equal(b.toString('hex'), f.b) + }) + }) +}) + +describe('xor/inplace', function () { + fixtures.forEach(function (f) { + it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () { + var a = new Buffer(f.a, 'hex') + var b = new Buffer(f.b, 'hex') + var actual = xorInplace(a, b) + + assert.equal(actual.toString('hex'), f.expected) + + // a mutated, b unchanged + assert.equal(a.toString('hex'), f.mutated || f.expected) + assert.equal(b.toString('hex'), f.b) + }) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc new file mode 100644 index 0000000..a755cdb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": ["standard"] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/index.js new file mode 100644 index 0000000..34fcae2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/index.js @@ -0,0 +1,90 @@ +var Transform = require('stream').Transform +var inherits = require('inherits') +var StringDecoder = require('string_decoder').StringDecoder +module.exports = CipherBase +inherits(CipherBase, Transform) +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + this._decoder = null + this._encoding = null +} +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = new Buffer(data, inputEnc) + } + var outData = this._update(data) + if (this.hashMode) { + return this + } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} + +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this._final()) + } catch (e) { + err = e + } finally { + done(err) + } +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this._final() || new Buffer('') + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, final) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + if (this._encoding !== enc) { + throw new Error('can\'t switch encodings') + } + var out = this._decoder.write(value) + if (final) { + out += this._decoder.end() + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/package.json new file mode 100644 index 0000000..1e71e16 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/package.json @@ -0,0 +1,39 @@ +{ + "name": "cipher-base", + "version": "1.0.2", + "description": "abstract base class for crypto-streams", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/cipher-base.git" + }, + "keywords": [ + "cipher", + "stream" + ], + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/cipher-base/issues" + }, + "homepage": "https://github.com/crypto-browserify/cipher-base#readme", + "dependencies": { + "inherits": "^2.0.1" + }, + "devDependencies": { + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "cipher-base\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base)\n\nAbstract base class to inherit from if you want to create streams implementing\nthe same api as node crypto streams.\n\nRequires you to implement 2 methods `_final` and `_update`. `_update` takes a\nbuffer and should return a buffer, `_final` takes no arguments and should return\na buffer.\n\n\nThe constructor takes one argument and that is a string which if present switches\nit into hash mode, i.e. the object you get from crypto.createHash or\ncrypto.createSign, this switches the name of the final method to be the string\nyou passed instead of `final` and returns `this` from update.\n", + "readmeFilename": "readme.md", + "_id": "cipher-base@1.0.2", + "_shasum": "54ac1d1ebdf6a1bcd3559e6f369d72697f2cab8f", + "_resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz", + "_from": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/readme.md new file mode 100644 index 0000000..db9a781 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/readme.md @@ -0,0 +1,17 @@ +cipher-base +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) + +Abstract base class to inherit from if you want to create streams implementing +the same api as node crypto streams. + +Requires you to implement 2 methods `_final` and `_update`. `_update` takes a +buffer and should return a buffer, `_final` takes no arguments and should return +a buffer. + + +The constructor takes one argument and that is a string which if present switches +it into hash mode, i.e. the object you get from crypto.createHash or +crypto.createSign, this switches the name of the final method to be the string +you passed instead of `final` and returns `this` from update. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/test.js new file mode 100644 index 0000000..57d144a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/node_modules/cipher-base/test.js @@ -0,0 +1,108 @@ +var test = require('tape') +var CipherBase = require('./') +var inherits = require('inherits') + +test('basic version', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + return input + } + Cipher.prototype._final = function () { + // noop + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8', 'base64') + cipher.final('base64') + var string = (new Buffer(update, 'base64')).toString() + t.equals(utf8, string) + t.end() +}) +test('hash mode', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8').finalName('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('hash mode as stream', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + cipher.on('error', function (e) { + t.notOk(e) + }) + var utf8 = 'abc123abcd' + cipher.end(utf8, 'utf8') + var update = cipher.read().toString('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('encodings', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + return input + } + Cipher.prototype._final = function () { + // noop + } + t.test('mix and match encoding', function (t) { + t.plan(2) + + var cipher = new Cipher() + cipher.update('foo', 'utf8', 'utf8') + t.throws(function () { + cipher.update('foo', 'utf8', 'base64') + }) + cipher = new Cipher() + cipher.update('foo', 'utf8', 'base64') + t.doesNotThrow(function () { + cipher.update('foo', 'utf8') + cipher.final('base64') + }) + }) + t.test('handle long uft8 plaintexts', function (t) { + t.plan(1) + var txt = 'ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん' + + var cipher = new Cipher() + var decipher = new Cipher() + var enc = decipher.update(cipher.update(txt, 'utf8', 'base64'), 'base64', 'utf8') + enc += decipher.update(cipher.final('base64'), 'base64', 'utf8') + enc += decipher.final('utf8') + + t.equals(txt, enc) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/package.json new file mode 100644 index 0000000..5e83424 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/package.json @@ -0,0 +1,46 @@ +{ + "name": "browserify-aes", + "version": "1.0.6", + "description": "aes, for browserify", + "browser": "browser.js", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "standard && node test/index.js|tspec" + }, + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/browserify-aes.git" + }, + "keywords": [ + "aes", + "crypto", + "browserify" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/browserify-aes/issues" + }, + "homepage": "https://github.com/crypto-browserify/browserify-aes", + "dependencies": { + "buffer-xor": "^1.0.2", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "inherits": "^2.0.1" + }, + "devDependencies": { + "standard": "^3.7.3", + "tap-spec": "^1.0.0", + "tape": "^3.0.0" + }, + "readme": "browserify-aes\n====\n\n[![Build Status](https://travis-ci.org/crypto-browserify/browserify-aes.svg)](https://travis-ci.org/crypto-browserify/browserify-aes)\n\nNode style aes for use in the browser. Implements:\n\n - createCipher\n - createCipheriv\n - createDecipher\n - createDecipheriv\n - getCiphers\n\nIn node.js, the `crypto` implementation is used, in browsers it falls back to a pure JavaScript implementation.\n\nMuch of this library has been taken from the aes implementation in [triplesec](https://github.com/keybase/triplesec), a partial derivation of [crypto-js](https://code.google.com/p/crypto-js/).\n\n`EVP_BytesToKey` is a straight up port of the same function from OpenSSL as there is literally no documenation on it beyond it using 'undocumented extensions' for longer keys.\n", + "readmeFilename": "readme.md", + "_id": "browserify-aes@1.0.6", + "_shasum": "5e7725dbdef1fd5930d4ebab48567ce451c48a0a", + "_resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz", + "_from": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/populateFixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/populateFixtures.js new file mode 100644 index 0000000..ac31eb3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/populateFixtures.js @@ -0,0 +1,25 @@ +var modes = require('./modes') +var fixtures = require('./test/fixtures.json') +var crypto = require('crypto') +var types = ['aes-128-cfb1', 'aes-192-cfb1', 'aes-256-cfb1'] +var ebtk = require('./EVP_BytesToKey') +var fs = require('fs') + +fixtures.forEach(function (fixture) { + types.forEach(function (cipher) { + var suite = crypto.createCipher(cipher, new Buffer(fixture.password)) + var buf = new Buffer('') + buf = Buffer.concat([buf, suite.update(new Buffer(fixture.text))]) + buf = Buffer.concat([buf, suite.final()]) + fixture.results.ciphers[cipher] = buf.toString('hex') + if (modes[cipher].mode === 'ECB') { + return + } + var suite2 = crypto.createCipheriv(cipher, ebtk(crypto, fixture.password, modes[cipher].key).key, new Buffer(fixture.iv, 'hex')) + var buf2 = new Buffer('') + buf2 = Buffer.concat([buf2, suite2.update(new Buffer(fixture.text))]) + buf2 = Buffer.concat([buf2, suite2.final()]) + fixture.results.cipherivs[cipher] = buf2.toString('hex') + }) +}) +fs.writeFileSync('./test/fixturesNew.json', JSON.stringify(fixtures, false, 4)) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/readme.md new file mode 100644 index 0000000..1d7b085 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/readme.md @@ -0,0 +1,18 @@ +browserify-aes +==== + +[![Build Status](https://travis-ci.org/crypto-browserify/browserify-aes.svg)](https://travis-ci.org/crypto-browserify/browserify-aes) + +Node style aes for use in the browser. Implements: + + - createCipher + - createCipheriv + - createDecipher + - createDecipheriv + - getCiphers + +In node.js, the `crypto` implementation is used, in browsers it falls back to a pure JavaScript implementation. + +Much of this library has been taken from the aes implementation in [triplesec](https://github.com/keybase/triplesec), a partial derivation of [crypto-js](https://code.google.com/p/crypto-js/). + +`EVP_BytesToKey` is a straight up port of the same function from OpenSSL as there is literally no documenation on it beyond it using 'undocumented extensions' for longer keys. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/streamCipher.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/streamCipher.js new file mode 100644 index 0000000..a55c762 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-aes/streamCipher.js @@ -0,0 +1,25 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') + +inherits(StreamCipher, Transform) +module.exports = StreamCipher +function StreamCipher (mode, key, iv, decrypt) { + if (!(this instanceof StreamCipher)) { + return new StreamCipher(mode, key, iv) + } + Transform.call(this) + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + this._cache = new Buffer('') + this._secCache = new Buffer('') + this._decrypt = decrypt + iv.copy(this._prev) + this._mode = mode +} +StreamCipher.prototype._update = function (chunk) { + return this._mode.encrypt(this, chunk, this._decrypt) +} +StreamCipher.prototype._final = function () { + this._cipher.scrub() +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/index.js new file mode 100644 index 0000000..2889bb7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/index.js @@ -0,0 +1,43 @@ +var CipherBase = require('cipher-base') +var des = require('des.js') +var inherits = require('inherits') + +var modes = { + 'des-ede3-cbc': des.CBC.instantiate(des.EDE), + 'des-ede3': des.EDE, + 'des-ede-cbc': des.CBC.instantiate(des.EDE), + 'des-ede': des.EDE, + 'des-cbc': des.CBC.instantiate(des.DES), + 'des-ecb': des.DES +} +modes.des = modes['des-cbc'] +modes.des3 = modes['des-ede3-cbc'] +module.exports = DES +inherits(DES, CipherBase) +function DES (opts) { + CipherBase.call(this) + var modeName = opts.mode.toLowerCase() + var mode = modes[modeName] + var type + if (opts.decrypt) { + type = 'decrypt' + } else { + type = 'encrypt' + } + var key = opts.key + if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { + key = Buffer.concat([key, key.slice(0, 8)]) + } + var iv = opts.iv + this._des = mode.create({ + key: key, + iv: iv, + type: type + }) +} +DES.prototype._update = function (data) { + return new Buffer(this._des.update(data)) +} +DES.prototype._final = function () { + return new Buffer(this._des.final()) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/modes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/modes.js new file mode 100644 index 0000000..72f308d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/modes.js @@ -0,0 +1,24 @@ +exports['des-ecb'] = { + key: 8, + iv: 0 +} +exports['des-cbc'] = exports.des = { + key: 8, + iv: 8 +} +exports['des-ede3-cbc'] = exports.des3 = { + key: 24, + iv: 8 +} +exports['des-ede3'] = { + key: 24, + iv: 0 +} +exports['des-ede-cbc'] = { + key: 16, + iv: 8 +} +exports['des-ede'] = { + key: 16, + iv: 0 +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/.eslintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/.eslintrc new file mode 100644 index 0000000..a755cdb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": ["standard"] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/index.js new file mode 100644 index 0000000..34fcae2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/index.js @@ -0,0 +1,90 @@ +var Transform = require('stream').Transform +var inherits = require('inherits') +var StringDecoder = require('string_decoder').StringDecoder +module.exports = CipherBase +inherits(CipherBase, Transform) +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + this._decoder = null + this._encoding = null +} +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = new Buffer(data, inputEnc) + } + var outData = this._update(data) + if (this.hashMode) { + return this + } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} + +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this._final()) + } catch (e) { + err = e + } finally { + done(err) + } +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this._final() || new Buffer('') + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, final) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + if (this._encoding !== enc) { + throw new Error('can\'t switch encodings') + } + var out = this._decoder.write(value) + if (final) { + out += this._decoder.end() + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/package.json new file mode 100644 index 0000000..1e71e16 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/package.json @@ -0,0 +1,39 @@ +{ + "name": "cipher-base", + "version": "1.0.2", + "description": "abstract base class for crypto-streams", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/cipher-base.git" + }, + "keywords": [ + "cipher", + "stream" + ], + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/cipher-base/issues" + }, + "homepage": "https://github.com/crypto-browserify/cipher-base#readme", + "dependencies": { + "inherits": "^2.0.1" + }, + "devDependencies": { + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "cipher-base\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base)\n\nAbstract base class to inherit from if you want to create streams implementing\nthe same api as node crypto streams.\n\nRequires you to implement 2 methods `_final` and `_update`. `_update` takes a\nbuffer and should return a buffer, `_final` takes no arguments and should return\na buffer.\n\n\nThe constructor takes one argument and that is a string which if present switches\nit into hash mode, i.e. the object you get from crypto.createHash or\ncrypto.createSign, this switches the name of the final method to be the string\nyou passed instead of `final` and returns `this` from update.\n", + "readmeFilename": "readme.md", + "_id": "cipher-base@1.0.2", + "_shasum": "54ac1d1ebdf6a1bcd3559e6f369d72697f2cab8f", + "_resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz", + "_from": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/readme.md new file mode 100644 index 0000000..db9a781 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/readme.md @@ -0,0 +1,17 @@ +cipher-base +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) + +Abstract base class to inherit from if you want to create streams implementing +the same api as node crypto streams. + +Requires you to implement 2 methods `_final` and `_update`. `_update` takes a +buffer and should return a buffer, `_final` takes no arguments and should return +a buffer. + + +The constructor takes one argument and that is a string which if present switches +it into hash mode, i.e. the object you get from crypto.createHash or +crypto.createSign, this switches the name of the final method to be the string +you passed instead of `final` and returns `this` from update. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/test.js new file mode 100644 index 0000000..57d144a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/cipher-base/test.js @@ -0,0 +1,108 @@ +var test = require('tape') +var CipherBase = require('./') +var inherits = require('inherits') + +test('basic version', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + return input + } + Cipher.prototype._final = function () { + // noop + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8', 'base64') + cipher.final('base64') + var string = (new Buffer(update, 'base64')).toString() + t.equals(utf8, string) + t.end() +}) +test('hash mode', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8').finalName('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('hash mode as stream', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + cipher.on('error', function (e) { + t.notOk(e) + }) + var utf8 = 'abc123abcd' + cipher.end(utf8, 'utf8') + var update = cipher.read().toString('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('encodings', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + return input + } + Cipher.prototype._final = function () { + // noop + } + t.test('mix and match encoding', function (t) { + t.plan(2) + + var cipher = new Cipher() + cipher.update('foo', 'utf8', 'utf8') + t.throws(function () { + cipher.update('foo', 'utf8', 'base64') + }) + cipher = new Cipher() + cipher.update('foo', 'utf8', 'base64') + t.doesNotThrow(function () { + cipher.update('foo', 'utf8') + cipher.final('base64') + }) + }) + t.test('handle long uft8 plaintexts', function (t) { + t.plan(1) + var txt = 'ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん' + + var cipher = new Cipher() + var decipher = new Cipher() + var enc = decipher.update(cipher.update(txt, 'utf8', 'base64'), 'base64', 'utf8') + enc += decipher.update(cipher.final('base64'), 'base64', 'utf8') + enc += decipher.final('utf8') + + t.equals(txt, enc) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.jscsrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.jscsrc new file mode 100644 index 0000000..dbaae20 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.jscsrc @@ -0,0 +1,46 @@ +{ + "disallowKeywordsOnNewLine": [ "else" ], + "disallowMixedSpacesAndTabs": true, + "disallowMultipleLineStrings": true, + "disallowMultipleVarDecl": true, + "disallowNewlineBeforeBlockStatements": true, + "disallowQuotedKeysInObjects": true, + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": true, + "disallowSpaceBeforePostfixUnaryOperators": true, + "disallowSpacesInCallExpression": true, + "disallowTrailingComma": true, + "disallowTrailingWhitespace": true, + "disallowYodaConditions": true, + + "requireCommaBeforeLineBreak": true, + "requireOperatorBeforeLineBreak": true, + "requireSpaceAfterBinaryOperators": true, + "requireSpaceAfterKeywords": [ "if", "for", "while", "else", "try", "catch" ], + "requireSpaceAfterLineComment": true, + "requireSpaceBeforeBinaryOperators": true, + "requireSpaceBeforeBlockStatements": true, + "requireSpaceBeforeKeywords": [ "else", "catch" ], + "requireSpaceBeforeObjectValues": true, + "requireSpaceBetweenArguments": true, + "requireSpacesInAnonymousFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "requireSpacesInFunctionDeclaration": { + "beforeOpeningCurlyBrace": true + }, + "requireSpacesInFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "requireSpacesInConditionalExpression": true, + "requireSpacesInForStatement": true, + "requireSpacesInsideArrayBrackets": "all", + "requireSpacesInsideObjectBrackets": "all", + "requireDotNotation": true, + + "maximumLineLength": 80, + "validateIndentation": 2, + "validateLineBreaks": "LF", + "validateParameterSeparator": ", ", + "validateQuoteMarks": "'" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.jshintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.jshintrc new file mode 100644 index 0000000..7e97390 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.jshintrc @@ -0,0 +1,89 @@ +{ + // JSHint Default Configuration File (as on JSHint website) + // See http://jshint.com/docs/ for more details + + "maxerr" : 50, // {int} Maximum error before stopping + + // Enforcing + "bitwise" : false, // true: Prohibit bitwise operators (&, |, ^, etc.) + "camelcase" : false, // true: Identifiers must be in camelCase + "curly" : false, // true: Require {} for every new block or scope + "eqeqeq" : true, // true: Require triple equals (===) for comparison + "forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty() + "freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc. + "immed" : false, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` + "indent" : 2, // {int} Number of spaces to use for indentation + "latedef" : true, // true: Require variables/functions to be defined before being used + "newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()` + "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` + "noempty" : false, // true: Prohibit use of empty blocks + "nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters. + "nonew" : false, // true: Prohibit use of constructors for side-effects (without assignment) + "plusplus" : false, // true: Prohibit use of `++` & `--` + "quotmark" : "single", // Quotation mark consistency: + // false : do nothing (default) + // true : ensure whatever is used is consistent + // "single" : require single quotes + // "double" : require double quotes + "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) + "unused" : true, // true: Require all defined variables be used + "strict" : true, // true: Requires all functions run in ES5 Strict Mode + "maxparams" : false, // {int} Max number of formal params allowed per function + "maxdepth" : 3, // {int} Max depth of nested blocks (within functions) + "maxstatements" : false, // {int} Max number statements per function + "maxcomplexity" : false, // {int} Max cyclomatic complexity per function + "maxlen" : false, // {int} Max number of characters per line + + // Relaxing + "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) + "boss" : false, // true: Tolerate assignments where comparisons would be expected + "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. + "eqnull" : false, // true: Tolerate use of `== null` + "es5" : false, // true: Allow ES5 syntax (ex: getters and setters) + "esnext" : false, // true: Allow ES.next (ES6) syntax (ex: `const`) + "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) + // (ex: `for each`, multiple try/catch, function expression…) + "evil" : false, // true: Tolerate use of `eval` and `new Function()` + "expr" : false, // true: Tolerate `ExpressionStatement` as Programs + "funcscope" : false, // true: Tolerate defining variables inside control statements + "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict') + "iterator" : false, // true: Tolerate using the `__iterator__` property + "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block + "laxbreak" : false, // true: Tolerate possibly unsafe line breakings + "laxcomma" : false, // true: Tolerate comma-first style coding + "loopfunc" : false, // true: Tolerate functions being defined in loops + "multistr" : false, // true: Tolerate multi-line strings + "noyield" : false, // true: Tolerate generator functions with no yield statement in them. + "notypeof" : false, // true: Tolerate invalid typeof operator values + "proto" : false, // true: Tolerate using the `__proto__` property + "scripturl" : false, // true: Tolerate script-targeted URLs + "shadow" : true, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` + "sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation + "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` + "validthis" : false, // true: Tolerate using this in a non-constructor function + + // Environments + "browser" : true, // Web Browser (window, document, etc) + "browserify" : true, // Browserify (node.js code in the browser) + "couch" : false, // CouchDB + "devel" : true, // Development/debugging (alert, confirm, etc) + "dojo" : false, // Dojo Toolkit + "jasmine" : false, // Jasmine + "jquery" : false, // jQuery + "mocha" : true, // Mocha + "mootools" : false, // MooTools + "node" : true, // Node.js + "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) + "prototypejs" : false, // Prototype and Scriptaculous + "qunit" : false, // QUnit + "rhino" : false, // Rhino + "shelljs" : false, // ShellJS + "worker" : false, // Web Workers + "wsh" : false, // Windows Scripting Host + "yui" : false, // Yahoo User Interface + + // Custom Globals + "globals" : { + "module": true + } // additional predefined global variables +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.npmignore new file mode 100644 index 0000000..1ca9571 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/README.md new file mode 100644 index 0000000..976de33 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/README.md @@ -0,0 +1,26 @@ +# DES.js + +## LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2015. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des.js new file mode 100644 index 0000000..2fd04a6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des.js @@ -0,0 +1,7 @@ +'use strict'; + +exports.utils = require('./des/utils'); +exports.Cipher = require('./des/cipher'); +exports.DES = require('./des/des'); +exports.CBC = require('./des/cbc'); +exports.EDE = require('./des/ede'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/cbc.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/cbc.js new file mode 100644 index 0000000..208ea31 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/cbc.js @@ -0,0 +1,65 @@ +'use strict'; + +var assert = require('minimalistic-assert'); +var inherits = require('inherits'); + +var proto = {}; + +function CBCState(iv) { + assert.equal(iv.length, 8, 'Invalid IV length'); + + this.iv = new Array(8); + for (var i = 0; i < this.iv.length; i++) + this.iv[i] = iv[i]; +} + +function instantiate(Base) { + function CBC(options) { + Base.call(this, options); + this._cbcInit(); + } + inherits(CBC, Base); + + var keys = Object.keys(proto); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + CBC.prototype[key] = proto[key]; + } + + CBC.create = function create(options) { + return new CBC(options); + }; + + return CBC; +} + +exports.instantiate = instantiate; + +proto._cbcInit = function _cbcInit() { + var state = new CBCState(this.options.iv); + this._cbcState = state; +}; + +proto._update = function _update(inp, inOff, out, outOff) { + var state = this._cbcState; + var superProto = this.constructor.super_.prototype; + + var iv = state.iv; + if (this.type === 'encrypt') { + for (var i = 0; i < this.blockSize; i++) + iv[i] ^= inp[inOff + i]; + + superProto._update.call(this, iv, 0, out, outOff); + + for (var i = 0; i < this.blockSize; i++) + iv[i] = out[outOff + i]; + } else { + superProto._update.call(this, inp, inOff, out, outOff); + + for (var i = 0; i < this.blockSize; i++) + out[outOff + i] ^= iv[i]; + + for (var i = 0; i < this.blockSize; i++) + iv[i] = inp[inOff + i]; + } +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/cipher.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/cipher.js new file mode 100644 index 0000000..d0090b4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/cipher.js @@ -0,0 +1,141 @@ +'use strict'; + +var assert = require('minimalistic-assert'); + +function Cipher(options) { + this.options = options; + + this.type = this.options.type; + this.blockSize = 8; + this._init(); + + this.buffer = new Array(this.blockSize); + this.bufferOff = 0; +} +module.exports = Cipher; + +Cipher.prototype._init = function _init() { + // Might be overrided +}; + +Cipher.prototype.update = function update(data) { + if (data.length === 0) + return []; + + if (this.type === 'decrypt') + return this._updateDecrypt(data); + else + return this._updateEncrypt(data); +}; + +Cipher.prototype._buffer = function _buffer(data, off) { + // Append data to buffer + var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); + for (var i = 0; i < min; i++) + this.buffer[this.bufferOff + i] = data[off + i]; + this.bufferOff += min; + + // Shift next + return min; +}; + +Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { + this._update(this.buffer, 0, out, off); + this.bufferOff = 0; + return this.blockSize; +}; + +Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { + var inputOff = 0; + var outputOff = 0; + + var count = ((this.bufferOff + data.length) / this.blockSize) | 0; + var out = new Array(count * this.blockSize); + + if (this.bufferOff !== 0) { + inputOff += this._buffer(data, inputOff); + + if (this.bufferOff === this.buffer.length) + outputOff += this._flushBuffer(out, outputOff); + } + + // Write blocks + var max = data.length - ((data.length - inputOff) % this.blockSize); + for (; inputOff < max; inputOff += this.blockSize) { + this._update(data, inputOff, out, outputOff); + outputOff += this.blockSize; + } + + // Queue rest + for (; inputOff < data.length; inputOff++, this.bufferOff++) + this.buffer[this.bufferOff] = data[inputOff]; + + return out; +}; + +Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { + var inputOff = 0; + var outputOff = 0; + + var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; + var out = new Array(count * this.blockSize); + + // TODO(indutny): optimize it, this is far from optimal + for (; count > 0; count--) { + inputOff += this._buffer(data, inputOff); + outputOff += this._flushBuffer(out, outputOff); + } + + // Buffer rest of the input + inputOff += this._buffer(data, inputOff); + + return out; +}; + +Cipher.prototype.final = function final(buffer) { + var first; + if (buffer) + first = this.update(buffer); + + var last; + if (this.type === 'encrypt') + last = this._finalEncrypt(); + else + last = this._finalDecrypt(); + + if (first) + return first.concat(last); + else + return last; +}; + +Cipher.prototype._pad = function _pad(buffer, off) { + if (off === 0) + return false; + + while (off < buffer.length) + buffer[off++] = 0; + + return true; +}; + +Cipher.prototype._finalEncrypt = function _finalEncrypt() { + if (!this._pad(this.buffer, this.bufferOff)) + return []; + + var out = new Array(this.blockSize); + this._update(this.buffer, 0, out, 0); + return out; +}; + +Cipher.prototype._unpad = function _unpad(buffer) { + return buffer; +}; + +Cipher.prototype._finalDecrypt = function _finalDecrypt() { + assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); + var out = new Array(this.blockSize); + this._flushBuffer(out, 0); + + return this._unpad(out); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/des.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/des.js new file mode 100644 index 0000000..b64a6d1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/des.js @@ -0,0 +1,143 @@ +'use strict'; + +var assert = require('minimalistic-assert'); +var inherits = require('inherits'); + +var des = require('../des'); +var utils = des.utils; +var Cipher = des.Cipher; + +function DESState() { + this.tmp = new Array(2); + this.keys = null; +} + +function DES(options) { + Cipher.call(this, options); + + var state = new DESState(); + this._desState = state; + + this.deriveKeys(state, options.key); +} +inherits(DES, Cipher); +module.exports = DES; + +DES.create = function create(options) { + return new DES(options); +}; + +var shiftTable = [ + 1, 1, 2, 2, 2, 2, 2, 2, + 1, 2, 2, 2, 2, 2, 2, 1 +]; + +DES.prototype.deriveKeys = function deriveKeys(state, key) { + state.keys = new Array(16 * 2); + + assert.equal(key.length, this.blockSize, 'Invalid key length'); + + var kL = utils.readUInt32BE(key, 0); + var kR = utils.readUInt32BE(key, 4); + + utils.pc1(kL, kR, state.tmp, 0); + kL = state.tmp[0]; + kR = state.tmp[1]; + for (var i = 0; i < state.keys.length; i += 2) { + var shift = shiftTable[i >>> 1]; + kL = utils.r28shl(kL, shift); + kR = utils.r28shl(kR, shift); + utils.pc2(kL, kR, state.keys, i); + } +}; + +DES.prototype._update = function _update(inp, inOff, out, outOff) { + var state = this._desState; + + var l = utils.readUInt32BE(inp, inOff); + var r = utils.readUInt32BE(inp, inOff + 4); + + // Initial Permutation + utils.ip(l, r, state.tmp, 0); + l = state.tmp[0]; + r = state.tmp[1]; + + if (this.type === 'encrypt') + this._encrypt(state, l, r, state.tmp, 0); + else + this._decrypt(state, l, r, state.tmp, 0); + + l = state.tmp[0]; + r = state.tmp[1]; + + utils.writeUInt32BE(out, l, outOff); + utils.writeUInt32BE(out, r, outOff + 4); +}; + +DES.prototype._pad = function _pad(buffer, off) { + var value = buffer.length - off; + for (var i = off; i < buffer.length; i++) + buffer[i] = value; + + return true; +}; + +DES.prototype._unpad = function _unpad(buffer) { + var pad = buffer[buffer.length - 1]; + for (var i = buffer.length - pad; i < buffer.length; i++) + assert.equal(buffer[i], pad); + + return buffer.slice(0, buffer.length - pad); +}; + +DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { + var l = lStart; + var r = rStart; + + // Apply f() x16 times + for (var i = 0; i < state.keys.length; i += 2) { + var keyL = state.keys[i]; + var keyR = state.keys[i + 1]; + + // f(r, k) + utils.expand(r, state.tmp, 0); + + keyL ^= state.tmp[0]; + keyR ^= state.tmp[1]; + var s = utils.substitute(keyL, keyR); + var f = utils.permute(s); + + var t = r; + r = (l ^ f) >>> 0; + l = t; + } + + // Reverse Initial Permutation + utils.rip(r, l, out, off); +}; + +DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { + var l = rStart; + var r = lStart; + + // Apply f() x16 times + for (var i = state.keys.length - 2; i >= 0; i -= 2) { + var keyL = state.keys[i]; + var keyR = state.keys[i + 1]; + + // f(r, k) + utils.expand(l, state.tmp, 0); + + keyL ^= state.tmp[0]; + keyR ^= state.tmp[1]; + var s = utils.substitute(keyL, keyR); + var f = utils.permute(s); + + var t = l; + l = (r ^ f) >>> 0; + r = t; + } + + // Reverse Initial Permutation + utils.rip(l, r, out, off); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/ede.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/ede.js new file mode 100644 index 0000000..cefc4a5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/ede.js @@ -0,0 +1,55 @@ +'use strict'; + +var assert = require('minimalistic-assert'); +var inherits = require('inherits'); + +var des = require('../des'); +var Cipher = des.Cipher; +var DES = des.DES; + +function EDEState(type, key) { + assert.equal(key.length, 24, 'Invalid key length'); + + var k1 = key.slice(0, 8); + var k2 = key.slice(8, 16); + var k3 = key.slice(16, 24); + + if (type === 'encrypt') { + this.ciphers = [ + DES.create({ type: 'encrypt', key: k1 }), + DES.create({ type: 'decrypt', key: k2 }), + DES.create({ type: 'encrypt', key: k3 }) + ]; + } else { + this.ciphers = [ + DES.create({ type: 'decrypt', key: k3 }), + DES.create({ type: 'encrypt', key: k2 }), + DES.create({ type: 'decrypt', key: k1 }) + ]; + } +} + +function EDE(options) { + Cipher.call(this, options); + + var state = new EDEState(this.type, this.options.key); + this._edeState = state; +} +inherits(EDE, Cipher); + +module.exports = EDE; + +EDE.create = function create(options) { + return new EDE(options); +}; + +EDE.prototype._update = function _update(inp, inOff, out, outOff) { + var state = this._edeState; + + state.ciphers[0]._update(inp, inOff, out, outOff); + state.ciphers[1]._update(out, outOff, out, outOff); + state.ciphers[2]._update(out, outOff, out, outOff); +}; + +EDE.prototype._pad = DES.prototype._pad; +EDE.prototype._unpad = DES.prototype._unpad; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/utils.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/utils.js new file mode 100644 index 0000000..08a5ccd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/lib/des/utils.js @@ -0,0 +1,256 @@ +'use strict'; + +exports.readUInt32BE = function readUInt32BE(bytes, off) { + var res = (bytes[0 + off] << 24) | + (bytes[1 + off] << 16) | + (bytes[2 + off] << 8) | + bytes[3 + off]; + return res >>> 0; +}; + +exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { + bytes[0 + off] = value >>> 24; + bytes[1 + off] = (value >>> 16) & 0xff; + bytes[2 + off] = (value >>> 8) & 0xff; + bytes[3 + off] = value & 0xff; +}; + +exports.ip = function ip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >>> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + } + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inL >>> (j + i)) & 1; + } + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.rip = function rip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + for (var i = 0; i < 4; i++) { + for (var j = 24; j >= 0; j -= 8) { + outL <<= 1; + outL |= (inR >>> (j + i)) & 1; + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + for (var i = 4; i < 8; i++) { + for (var j = 24; j >= 0; j -= 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + outR <<= 1; + outR |= (inL >>> (j + i)) & 1; + } + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.pc1 = function pc1(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + // 7, 15, 23, 31, 39, 47, 55, 63 + // 6, 14, 22, 30, 39, 47, 55, 63 + // 5, 13, 21, 29, 39, 47, 55, 63 + // 4, 12, 20, 28 + for (var i = 7; i >= 5; i--) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + + // 1, 9, 17, 25, 33, 41, 49, 57 + // 2, 10, 18, 26, 34, 42, 50, 58 + // 3, 11, 19, 27, 35, 43, 51, 59 + // 36, 44, 52, 60 + for (var i = 1; i <= 3; i++) { + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.r28shl = function r28shl(num, shift) { + return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); +}; + +var pc2table = [ + // inL => outL + 14, 11, 17, 4, 27, 23, 25, 0, + 13, 22, 7, 18, 5, 9, 16, 24, + 2, 20, 12, 21, 1, 8, 15, 26, + + // inR => outR + 15, 4, 25, 19, 9, 1, 26, 16, + 5, 11, 23, 8, 12, 7, 17, 0, + 22, 3, 10, 14, 6, 20, 27, 24 +]; + +exports.pc2 = function pc2(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + var len = pc2table.length >>> 1; + for (var i = 0; i < len; i++) { + outL <<= 1; + outL |= (inL >>> pc2table[i]) & 0x1; + } + for (var i = len; i < pc2table.length; i++) { + outR <<= 1; + outR |= (inR >>> pc2table[i]) & 0x1; + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.expand = function expand(r, out, off) { + var outL = 0; + var outR = 0; + + outL = ((r & 1) << 5) | (r >>> 27); + for (var i = 23; i >= 15; i -= 4) { + outL <<= 6; + outL |= (r >>> i) & 0x3f; + } + for (var i = 11; i >= 3; i -= 4) { + outR |= (r >>> i) & 0x3f; + outR <<= 6; + } + outR |= ((r & 0x1f) << 1) | (r >>> 31); + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +var sTable = [ + 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, + 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, + 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, + 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, + + 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, + 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, + 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, + 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, + + 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, + 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, + 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, + 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, + + 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, + 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, + 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, + 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, + + 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, + 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, + 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, + 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, + + 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, + 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, + 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, + 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, + + 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, + 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, + 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, + 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, + + 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, + 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, + 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, + 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 +]; + +exports.substitute = function substitute(inL, inR) { + var out = 0; + for (var i = 0; i < 4; i++) { + var b = (inL >>> (18 - i * 6)) & 0x3f; + var sb = sTable[i * 0x40 + b]; + + out <<= 4; + out |= sb; + } + for (var i = 0; i < 4; i++) { + var b = (inR >>> (18 - i * 6)) & 0x3f; + var sb = sTable[4 * 0x40 + i * 0x40 + b]; + + out <<= 4; + out |= sb; + } + return out >>> 0; +}; + +var permuteTable = [ + 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, + 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7 +]; + +exports.permute = function permute(num) { + var out = 0; + for (var i = 0; i < permuteTable.length; i++) { + out <<= 1; + out |= (num >>> permuteTable[i]) & 0x1; + } + return out >>> 0; +}; + +exports.padSplit = function padSplit(num, size, group) { + var str = num.toString(2); + while (str.length < size) + str = '0' + str; + + var out = []; + for (var i = 0; i < size; i += group) + out.push(str.slice(i, i + group)); + return out.join(' '); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/index.js new file mode 100644 index 0000000..70b4ea5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/index.js @@ -0,0 +1,11 @@ +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/package.json new file mode 100644 index 0000000..bd3bd47 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/package.json @@ -0,0 +1,25 @@ +{ + "name": "minimalistic-assert", + "version": "1.0.0", + "description": "minimalistic-assert ===", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/calvinmetcalf/minimalistic-assert.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/calvinmetcalf/minimalistic-assert/issues" + }, + "homepage": "https://github.com/calvinmetcalf/minimalistic-assert", + "readme": "minimalistic-assert\n===\n\nvery minimalistic assert module.\n", + "readmeFilename": "readme.md", + "_id": "minimalistic-assert@1.0.0", + "_shasum": "702be2dda6b37f4836bcb3f5db56641b64a1d3d3", + "_resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz", + "_from": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/readme.md new file mode 100644 index 0000000..2ca0d25 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/node_modules/minimalistic-assert/readme.md @@ -0,0 +1,4 @@ +minimalistic-assert +=== + +very minimalistic assert module. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/package.json new file mode 100644 index 0000000..edff986 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/package.json @@ -0,0 +1,43 @@ +{ + "name": "des.js", + "version": "1.0.0", + "description": "DES implementation", + "main": "lib/des.js", + "scripts": { + "test": "mocha --reporter=spec test/*-test.js && jscs lib/*.js lib/**/*.js test/*.js && jshint lib/*.js lib/**/*.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/des.js.git" + }, + "keywords": [ + "DES", + "3DES", + "EDE", + "CBC" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/des.js/issues" + }, + "homepage": "https://github.com/indutny/des.js#readme", + "devDependencies": { + "jscs": "^2.1.1", + "jshint": "^2.8.0", + "mocha": "^2.3.0" + }, + "dependencies": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + }, + "readme": "# DES.js\n\n## LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2015.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "des.js@1.0.0", + "_shasum": "c074d2e2aa6a8a9a07dbd61f9a15c2cd83ec8ecc", + "_resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", + "_from": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/cbc-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/cbc-test.js new file mode 100644 index 0000000..d07881c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/cbc-test.js @@ -0,0 +1,73 @@ +'use strict'; + +var assert = require('assert'); +var crypto = require('crypto'); +var Buffer = require('buffer').Buffer; + +var des = require('../'); + +var fixtures = require('./fixtures'); +var bin = fixtures.bin; + +describe('DES-CBC', function() { + var CBC = des.CBC.instantiate(des.DES); + + describe('encryption/decryption', function() { + var vectors = [ + { + key: '133457799bbcdff1', + iv: '0102030405060708', + input: '0123456789abcdef' + }, + { + key: '0000000000000000', + iv: 'ffffffffffffffff', + input: '0000000000000000' + }, + { + key: 'a3a3a3a3b3b3b3b3', + iv: 'cdcdcdcdcdcdcdcd', + input: 'cccccccccccccccc' + }, + { + key: 'deadbeefabbadead', + iv: 'a0da0da0da0da0da', + input: '0102030405060708090a' + }, + { + key: 'aabbccddeeff0011', + iv: 'fefefefefefefefe', + input: '0102030405060708090a0102030405060708090a0102030405060708090a' + + '0102030405060708090a0102030405060607080a0102030405060708090a' + } + ]; + + vectors.forEach(function(vec, i) { + it('should encrypt vector ' + i, function() { + var key = new Buffer(vec.key, 'hex'); + var iv = new Buffer(vec.iv, 'hex'); + var input = new Buffer(vec.input, 'hex'); + + var enc = CBC.create({ + type: 'encrypt', + key: key, + iv: iv + }); + var out = new Buffer(enc.update(input).concat(enc.final())); + + var cipher = crypto.createCipheriv('des-cbc', key, iv); + var expected = Buffer.concat([ cipher.update(input), cipher.final() ]); + + assert.deepEqual(out, expected); + + var dec = CBC.create({ + type: 'decrypt', + key: key, + iv: iv + }); + assert.deepEqual(new Buffer(dec.update(out).concat(dec.final())), + input); + }); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/des-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/des-test.js new file mode 100644 index 0000000..b6a5ee8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/des-test.js @@ -0,0 +1,139 @@ +'use strict'; + +var assert = require('assert'); +var crypto = require('crypto'); +var Buffer = require('buffer').Buffer; + +var des = require('../'); + +var fixtures = require('./fixtures'); +var bin = fixtures.bin; + +describe('DES', function() { + describe('Key Derivation', function() { + it('should derive proper keys', function() { + var d = des.DES.create({ + type: 'encrypt', + key: [ 0x13, 0x34, 0x57, 0x79, 0x9B, 0xBC, 0xDF, 0xF1 ] + }); + + var expected = [ + '000110 110000 001011 101111', + '111111 000111 000001 110010', + '011110 011010 111011 011001', + '110110 111100 100111 100101', + '010101 011111 110010 001010', + '010000 101100 111110 011001', + '011100 101010 110111 010110', + '110110 110011 010100 011101', + '011111 001110 110000 000111', + '111010 110101 001110 101000', + '011000 111010 010100 111110', + '010100 000111 101100 101111', + '111011 001000 010010 110111', + '111101 100001 100010 111100', + '111101 111000 101000 111010', + '110000 010011 101111 111011', + '111000 001101 101111 101011', + '111011 011110 011110 000001', + '101100 011111 001101 000111', + '101110 100100 011001 001111', + '001000 010101 111111 010011', + '110111 101101 001110 000110', + '011101 010111 000111 110101', + '100101 000110 011111 101001', + '100101 111100 010111 010001', + '111110 101011 101001 000001', + '010111 110100 001110 110111', + '111100 101110 011100 111010', + '101111 111001 000110 001101', + '001111 010011 111100 001010', + '110010 110011 110110 001011', + '000011 100001 011111 110101' + ]; + + expected = expected.map(fixtures.bin); + assert.deepEqual(d._desState.keys, expected); + }); + }); + + describe('encryption/decryption', function() { + var vectors = [ + { + key: '133457799bbcdff1', + input: '0123456789abcdef' + }, + { + key: '0000000000000000', + input: '0000000000000000' + }, + { + key: 'a3a3a3a3b3b3b3b3', + input: 'cccccccccccccccc' + }, + { + key: 'deadbeefabbadead', + input: '0102030405060708090a' + }, + { + key: 'aabbccddeeff0011', + input: '0102030405060708090a0102030405060708090a0102030405060708090a' + + '0102030405060708090a0102030405060607080a0102030405060708090a' + } + ]; + + vectors.forEach(function(vec, i) { + it('should encrypt vector ' + i, function() { + var key = new Buffer(vec.key, 'hex'); + var input = new Buffer(vec.input, 'hex'); + + var enc = des.DES.create({ + type: 'encrypt', + key: key + }); + var dec = des.DES.create({ + type: 'decrypt', + key: key + }); + var out = new Buffer(enc.update(input).concat(enc.final())); + + var cipher = crypto.createCipheriv('des-ecb', key, new Buffer(0)); + var expected = Buffer.concat([ cipher.update(input), cipher.final() ]); + + assert.deepEqual(out, expected); + + assert.deepEqual(new Buffer(dec.update(out).concat(dec.final())), + input); + }); + }); + + it('should buffer during encryption/decryption', function() { + var key = new Buffer('0102030405060708', 'hex'); + var chunk = new Buffer('01020304050607', 'hex'); + var count = 257; + var expected = new Buffer( + new Array(count + 1).join('01020304050607'), 'hex'); + + var enc = des.DES.create({ + type: 'encrypt', + key: key + }); + var cipher = []; + for (var i = 0; i < count; i++) + cipher = cipher.concat(enc.update(chunk)); + cipher = cipher.concat(enc.final()); + + var dec = des.DES.create({ + type: 'decrypt', + key: key + }); + var out = []; + for (var i = 0; i < count; i++) + out = out.concat(dec.update(cipher.slice(i * 7, (i + 1) * 7))); + out = out.concat(dec.final(cipher.slice(i * 7))); + + out = new Buffer(out); + assert.deepEqual(out, expected); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/ede-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/ede-test.js new file mode 100644 index 0000000..116a76a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/ede-test.js @@ -0,0 +1,73 @@ +'use strict'; + +var assert = require('assert'); +var crypto = require('crypto'); +var Buffer = require('buffer').Buffer; + +var des = require('../'); + +var fixtures = require('./fixtures'); +var bin = fixtures.bin; + +describe('DES-EDE-CBC', function() { + var CBC = des.CBC.instantiate(des.EDE); + + describe('encryption/decryption', function() { + var vectors = [ + { + key: new Array(4).join('133457799bbcdff1'), + iv: '0102030405060708', + input: '0123456789abcdef' + }, + { + key: new Array(4).join('0000000000000000'), + iv: 'ffffffffffffffff', + input: '0000000000000000' + }, + { + key: new Array(4).join('a3a3a3a3b3b3b3b3'), + iv: 'cdcdcdcdcdcdcdcd', + input: 'cccccccccccccccc' + }, + { + key: new Array(4).join('deadbeefabbadead'), + iv: 'a0da0da0da0da0da', + input: '0102030405060708090a' + }, + { + key: 'aabbccddeeff0011' + '1111222233334444' + 'ffffeeeeddddcccc', + iv: 'fefefefefefefefe', + input: '0102030405060708090a0102030405060708090a0102030405060708090a' + + '0102030405060708090a0102030405060607080a0102030405060708090a' + } + ]; + + vectors.forEach(function(vec, i) { + it('should encrypt vector ' + i, function() { + var key = new Buffer(vec.key, 'hex'); + var iv = new Buffer(vec.iv, 'hex'); + var input = new Buffer(vec.input, 'hex'); + + var enc = CBC.create({ + type: 'encrypt', + key: key, + iv: iv + }); + var out = new Buffer(enc.update(input).concat(enc.final())); + + var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); + var expected = Buffer.concat([ cipher.update(input), cipher.final() ]); + + assert.deepEqual(out, expected); + + var dec = CBC.create({ + type: 'decrypt', + key: key, + iv: iv + }); + assert.deepEqual(new Buffer(dec.update(out).concat(dec.final())), + input); + }); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/fixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/fixtures.js new file mode 100644 index 0000000..fe8ccd8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/fixtures.js @@ -0,0 +1,5 @@ +'use strict'; + +exports.bin = function bin(str) { + return parseInt(str.replace(/[^01]/g, ''), 2); +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/utils-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/utils-test.js new file mode 100644 index 0000000..4c576de --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/node_modules/des.js/test/utils-test.js @@ -0,0 +1,169 @@ +'use strict'; + +var assert = require('assert'); + +var des = require('../'); +var utils = des.utils; + +var fixtures = require('./fixtures'); +var bin = fixtures.bin; + +describe('utils', function() { + describe('IP', function() { + it('should permute properly', function() { + var out = new Array(2); + var inp = [ + bin('00000001 00100011 01000101 01100111'), + bin('10001001 10101011 11001101 11101111') + ]; + + utils.ip(inp[0], inp[1], out, 0); + + var expected = [ + bin('11001100 00000000 11001100 11111111'), + bin('11110000 10101010 11110000 10101010') + ]; + + assert.deepEqual(out, expected); + }); + + it('should rev-permute properly', function() { + var out = new Array(2); + var inp = [ + bin('11001100 00000000 11001100 11111111'), + bin('11110000 10101010 11110000 10101010') + ]; + + utils.rip(inp[0], inp[1], out, 0); + + var expected = [ + bin('00000001 00100011 01000101 01100111'), + bin('10001001 10101011 11001101 11101111') + ]; + + assert.deepEqual(out, expected); + }); + }); + + describe('PC1', function() { + it('should permute properly', function() { + var out = new Array(2); + var inp = [ + bin('00010011 00110100 01010111 01111001'), + bin('10011011 10111100 11011111 11110001') + ]; + + utils.pc1(inp[0], inp[1], out, 0); + + var expected = [ + bin('1111000 0110011 0010101 0101111'), + bin('0101010 1011001 1001111 0001111') + ]; + + assert.deepEqual(out, expected); + }); + }); + + describe('r28shl', function() { + it('should shl properly', function() { + assert.equal(utils.r28shl(bin('1111000011001100101010101111'), 1), + bin('1110000110011001010101011111')); + + assert.equal(utils.r28shl(bin('0101010101100110011110001111'), 1), + bin('1010101011001100111100011110')); + + assert.equal(utils.r28shl(bin('1111000011001100101010101111'), 4), + bin('0000110011001010101011111111')); + + assert.equal(utils.r28shl(bin('0101010101100110011110001111'), 4), + bin('0101011001100111100011110101')); + }); + }); + + describe('PC2', function() { + it('should permute properly', function() { + var out = new Array(2); + var inp = [ + bin('1110000 1100110 0101010 1011111'), + bin('1010101 0110011 0011110 0011110') + ]; + + utils.pc2(inp[0], inp[1], out, 0); + + var expected = [ + bin('000110 110000 001011 101111'), + bin('111111 000111 000001 110010') + ]; + + assert.deepEqual(out, expected); + }); + }); + + describe('readUInt32BE', function() { + it('should read number properly', function() { + var a = [ 0xde, 0xad, 0xbe, 0xef ]; + var o = utils.readUInt32BE(a, 0); + assert.equal(o, 0xdeadbeef); + }); + }); + + describe('writeUInt32BE', function() { + it('should read number properly', function() { + var a = [ 0, 0, 0, 0 ]; + utils.writeUInt32BE(a, 0xdeadbeef, 0); + var expected = [ 0xde, 0xad, 0xbe, 0xef ]; + assert.deepEqual(a, expected); + }); + }); + + describe('expand', function() { + it('should expand', function() { + var out = [ 0, 0 ]; + utils.expand(bin('1111 0000 1010 1010 1111 0000 1010 1010'), out, 0); + var expected = [ + bin('011110 100001 010101 010101'), + bin('011110 100001 010101 010101') + ]; + assert.deepEqual(out, expected); + }); + + it('should expand with low 1', function() { + var out = [ 0, 0 ]; + utils.expand(bin('1111 0000 1010 1010 1111 0000 1010 1011'), out, 0); + var expected = [ + bin('111110 100001 010101 010101'), + bin('011110 100001 010101 010111') + ]; + assert.deepEqual(out, expected); + }); + + it('should expand with low 1', function() { + var out = [ 0, 0 ]; + utils.expand(bin('10100010 01011100 00001011 11110100'), out, 0); + var expected = [ + bin('010100 000100 001011 111000'), + bin('000001 010111 111110 101001') + ]; + assert.deepEqual(out, expected); + }); + }); + + describe('substitute', function() { + it('should substitute', function() { + var input = [ + bin('011000 010001 011110 111010'), + bin('100001 100110 010100 100111') + ]; + var output = utils.substitute(input[0], input[1]); + assert.equal(output, bin('0101 1100 1000 0010 1011 0101 1001 0111')); + }); + }); + + describe('permute', function() { + it('should permute', function() { + var output = utils.permute( + bin('0101 1100 1000 0010 1011 0101 1001 0111')); + assert.equal(output, bin('0010 0011 0100 1010 1010 1001 1011 1011')); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/package.json new file mode 100644 index 0000000..b08aa74 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/package.json @@ -0,0 +1,38 @@ +{ + "name": "browserify-des", + "version": "1.0.0", + "description": "browserify-des ===", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/browserify-des.git" + }, + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/browserify-des/issues" + }, + "homepage": "https://github.com/crypto-browserify/browserify-des#readme", + "dependencies": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1" + }, + "devDependencies": { + "standard": "^5.3.1", + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "browserify-des\n===\n\nDES for browserify\n", + "readmeFilename": "readme.md", + "_id": "browserify-des@1.0.0", + "_shasum": "daa277717470922ed2fe18594118a175439721dd", + "_resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.0.tgz", + "_from": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/readme.md new file mode 100644 index 0000000..c29c1b2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/readme.md @@ -0,0 +1,4 @@ +browserify-des +=== + +DES for browserify diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/test.js new file mode 100644 index 0000000..6324f43 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/browserify-des/test.js @@ -0,0 +1,48 @@ +var test = require('tape') +var DES = require('./') +var modes = require('./modes') +var crypto = require('crypto') + +Object.keys(modes).forEach(function (mode) { + test(mode, function (t) { + var i = 0 + while (++i < 10) { + runOnce(i) + } + function runOnce (i) { + t.test('run: ' + i, function (t) { + t.plan(2) + var key = crypto.randomBytes(modes[mode].key) + var iv = crypto.randomBytes(modes[mode].iv) + var text = crypto.randomBytes(200) + var ourEncrypt + try { + ourEncrypt = new DES({ + mode: mode, + key: key, + iv: iv + }) + } catch (e) { + t.notOk(e, e.stack) + } + var nodeEncrypt + try { + nodeEncrypt = crypto.createCipheriv(mode, key, iv) + } catch (e) { + t.notOk(e, e.stack) + } + var ourCipherText = Buffer.concat([ourEncrypt.update(text), ourEncrypt.final()]) + var nodeCipherText = Buffer.concat([nodeEncrypt.update(text), nodeEncrypt.final()]) + t.equals(nodeCipherText.toString('hex'), ourCipherText.toString('hex')) + var ourDecrypt = new DES({ + mode: mode, + key: key, + iv: iv, + decrypt: true + }) + var plainText = Buffer.concat([ourDecrypt.update(ourCipherText), ourDecrypt.final()]) + t.equals(text.toString('hex'), plainText.toString('hex')) + }) + } + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/index.js new file mode 100644 index 0000000..25fbc9c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/index.js @@ -0,0 +1,68 @@ +var md5 = require('create-hash/md5') +module.exports = EVP_BytesToKey +function EVP_BytesToKey (password, salt, keyLen, ivLen) { + if (!Buffer.isBuffer(password)) { + password = new Buffer(password, 'binary') + } + if (salt && !Buffer.isBuffer(salt)) { + salt = new Buffer(salt, 'binary') + } + keyLen = keyLen / 8 + ivLen = ivLen || 0 + var ki = 0 + var ii = 0 + var key = new Buffer(keyLen) + var iv = new Buffer(ivLen) + var addmd = 0 + var md_buf + var i + var bufs = [] + while (true) { + if (addmd++ > 0) { + bufs.push(md_buf) + } + bufs.push(password) + if (salt) { + bufs.push(salt) + } + md_buf = md5(Buffer.concat(bufs)) + bufs = [] + i = 0 + if (keyLen > 0) { + while (true) { + if (keyLen === 0) { + break + } + if (i === md_buf.length) { + break + } + key[ki++] = md_buf[i] + keyLen-- + i++ + } + } + if (ivLen > 0 && i !== md_buf.length) { + while (true) { + if (ivLen === 0) { + break + } + if (i === md_buf.length) { + break + } + iv[ii++] = md_buf[i] + ivLen-- + i++ + } + } + if (keyLen === 0 && ivLen === 0) { + break + } + } + for (i = 0; i < md_buf.length; i++) { + md_buf[i] = 0 + } + return { + key: key, + iv: iv + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/package.json new file mode 100644 index 0000000..66f2e69 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/package.json @@ -0,0 +1,40 @@ +{ + "name": "evp_bytestokey", + "version": "1.0.0", + "description": "he super secure key derivation algorithm from openssl", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/EVP_BytesToKey.git" + }, + "keywords": [ + "crypto", + "openssl" + ], + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/EVP_BytesToKey/issues" + }, + "homepage": "https://github.com/crypto-browserify/EVP_BytesToKey", + "dependencies": { + "create-hash": "^1.1.1" + }, + "devDependencies": { + "standard": "^5.3.1", + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "EVP_BytesToKey\n===\n\nThe super secure [key derivation algorithm from openssl](https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3)) (spoiler alert not actually secure, only every use it for compatibility reasons).\n\nApi:\n===\n\n```js\nvar result = EVP_BytesToKey('password', 'salt', keyLen, ivLen);\nBuffer.isBuffer(result.password); // true\nBuffer.isBuffer(result.iv); // true\n```\n", + "readmeFilename": "readme.md", + "_id": "evp_bytestokey@1.0.0", + "_shasum": "497b66ad9fef65cd7c08a6180824ba1476b66e53", + "_resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz", + "_from": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/readme.md new file mode 100644 index 0000000..86234db --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/readme.md @@ -0,0 +1,13 @@ +EVP_BytesToKey +=== + +The super secure [key derivation algorithm from openssl](https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3)) (spoiler alert not actually secure, only every use it for compatibility reasons). + +Api: +=== + +```js +var result = EVP_BytesToKey('password', 'salt', keyLen, ivLen); +Buffer.isBuffer(result.password); // true +Buffer.isBuffer(result.iv); // true +``` diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/test.js new file mode 100644 index 0000000..a638fa0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/node_modules/evp_bytestokey/test.js @@ -0,0 +1,19 @@ +var test = require('tape') +var evp = require('./') +var crypto = require('crypto') + +function runTest (password) { + test('password: ' + password, function (t) { + t.plan(1) + var keys = evp(password, false, 256, 16) + var nodeCipher = crypto.createCipher('aes-256-ctr', password) + var ourCipher = crypto.createCipheriv('aes-256-ctr', keys.key, keys.iv) + var nodeOut = nodeCipher.update('foooooo') + var ourOut = ourCipher.update('foooooo') + t.equals(nodeOut.toString('hex'), ourOut.toString('hex')) + }) +} +runTest('password') +runTest('ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん') +runTest('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞') +runTest('💩') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/package.json new file mode 100644 index 0000000..6cc08a7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/package.json @@ -0,0 +1,39 @@ +{ + "name": "browserify-cipher", + "version": "1.0.0", + "description": "ciphers for the browser", + "main": "index.js", + "dependencies": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + }, + "browser": "browser.js", + "devDependencies": { + "standard": "^5.3.1", + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "scripts": { + "test": "standard && node test.js | tspec" + }, + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/crypto-browserify/browserify-cipher.git" + }, + "readme": "browserify-cipher\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/browserify-cipher.svg)](https://travis-ci.org/crypto-browserify/browserify-cipher)\n\nProvides createCipher, createDecipher, createCipheriv, createDecipheriv and\ngetCiphers for the browserify. Includes AES and DES ciphers.\n", + "readmeFilename": "readme.md", + "bugs": { + "url": "https://github.com/crypto-browserify/browserify-cipher/issues" + }, + "homepage": "https://github.com/crypto-browserify/browserify-cipher#readme", + "_id": "browserify-cipher@1.0.0", + "_shasum": "9988244874bf5ed4e28da95666dcd66ac8fc363a", + "_resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.0.tgz", + "_from": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/readme.md new file mode 100644 index 0000000..3c0b157 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/readme.md @@ -0,0 +1,7 @@ +browserify-cipher +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/browserify-cipher.svg)](https://travis-ci.org/crypto-browserify/browserify-cipher) + +Provides createCipher, createDecipher, createCipheriv, createDecipheriv and +getCiphers for the browserify. Includes AES and DES ciphers. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/test.js new file mode 100644 index 0000000..d4beaa0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-cipher/test.js @@ -0,0 +1,55 @@ +var test = require('tape') +var crypto = require('crypto') +var desModes = require('browserify-des/modes') +var aesModes = require('browserify-aes/modes') +var ourCrypto = require('./browser') + +function runIvTest (mode, keyLen, ivLen) { + test('mode: ' + mode, function (t) { + var i = 0 + while (++i < 10) { + run(i) + } + function run (i) { + t.test('run: ' + i, function (t) { + t.plan(2) + var key = crypto.randomBytes(keyLen) + var iv = crypto.randomBytes(ivLen) + var text = crypto.randomBytes(200) + var ourEncrypt + try { + ourEncrypt = ourCrypto.createCipheriv(mode, key, iv) + } catch (e) { + t.notOk(e, e.stack) + } + var nodeEncrypt + try { + nodeEncrypt = crypto.createCipheriv(mode, key, iv) + } catch (e) { + t.notOk(e, e.stack) + } + var ourCipherText = Buffer.concat([ourEncrypt.update(text), ourEncrypt.final()]) + var authTag + if (mode.slice(-3) === 'gcm') { + authTag = ourEncrypt.getAuthTag() + } + var nodeCipherText = Buffer.concat([nodeEncrypt.update(text), nodeEncrypt.final()]) + t.equals(nodeCipherText.toString('hex'), ourCipherText.toString('hex')) + var ourDecrypt = ourCrypto.createDecipheriv(mode, key, iv) + if (mode.slice(-3) === 'gcm') { + ourDecrypt.setAuthTag(authTag) + } + var plainText = Buffer.concat([ourDecrypt.update(ourCipherText), ourDecrypt.final()]) + t.equals(text.toString('hex'), plainText.toString('hex')) + }) + } + }) +} +Object.keys(aesModes).forEach(function (modeName) { + var mode = aesModes[modeName] + runIvTest(modeName, mode.key / 8, mode.iv) +}) +Object.keys(desModes).forEach(function (modeName) { + var mode = desModes[modeName] + runIvTest(modeName, mode.key, mode.iv) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.jshintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.jshintrc new file mode 100644 index 0000000..2c5a439 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.jshintrc @@ -0,0 +1,27 @@ +{ + "asi": true, + "browser": true, + "devel": true, + "eqeqeq": true, + "eqnull": true, + "esnext": true, + "expr": true, + "globals": { + "chrome": false, + "FileList": false + }, + "globalstrict": true, + "immed": true, + "latedef": "nofunc", + "laxbreak": true, + "loopfunc": true, + "newcap": true, + "noarg": true, + "node": true, + "predef": [ + "escape", + "unescape" + ], + "strict": false, + "undef": "nofunc" +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.npmignore new file mode 100644 index 0000000..9daeafb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.travis.yml new file mode 100644 index 0000000..1f1ec66 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/.travis.yml @@ -0,0 +1,11 @@ +sudo: false +language: node_js +node_js: + - "0.10" + - "0.11" + - "0.12" + - "iojs" +env: + - TEST_SUITE=standard + - TEST_SUITE=unit +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/LICENSE new file mode 100644 index 0000000..870bcf1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2014-2015 Calvin Metcalf and browserify-sign contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/README.md new file mode 100644 index 0000000..0bcf124 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/README.md @@ -0,0 +1,4 @@ +browserify-sign [![Build Status](https://travis-ci.org/crypto-browserify/browserify-sign.svg)](https://travis-ci.org/crypto-browserify/browserify-sign) +=== + +A package to duplicate the functionality of node's crypto public key functions, much of this is based on [Fedor Indutny's](https://github.com/indutny) work on [tls.js](https://github.com/indutny/tls.js). diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/algos.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/algos.js new file mode 100644 index 0000000..1ee2db4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/algos.js @@ -0,0 +1,72 @@ +'use strict' +exports['RSA-SHA224'] = exports.sha224WithRSAEncryption = { + sign: 'rsa', + hash: 'sha224', + id: new Buffer('302d300d06096086480165030402040500041c', 'hex') +} +exports['RSA-SHA256'] = exports.sha256WithRSAEncryption = { + sign: 'rsa', + hash: 'sha256', + id: new Buffer('3031300d060960864801650304020105000420', 'hex') +} +exports['RSA-SHA384'] = exports.sha384WithRSAEncryption = { + sign: 'rsa', + hash: 'sha384', + id: new Buffer('3041300d060960864801650304020205000430', 'hex') +} +exports['RSA-SHA512'] = exports.sha512WithRSAEncryption = { + sign: 'rsa', + hash: 'sha512', + id: new Buffer('3051300d060960864801650304020305000440', 'hex') +} +exports['RSA-SHA1'] = { + sign: 'rsa', + hash: 'sha1', + id: new Buffer('3021300906052b0e03021a05000414', 'hex') +} +exports['ecdsa-with-SHA1'] = { + sign: 'ecdsa', + hash: 'sha1', + id: new Buffer('', 'hex') +} + +exports.DSA = exports['DSA-SHA1'] = exports['DSA-SHA'] = { + sign: 'dsa', + hash: 'sha1', + id: new Buffer('', 'hex') +} +exports['DSA-SHA224'] = exports['DSA-WITH-SHA224'] = { + sign: 'dsa', + hash: 'sha224', + id: new Buffer('', 'hex') +} +exports['DSA-SHA256'] = exports['DSA-WITH-SHA256'] = { + sign: 'dsa', + hash: 'sha256', + id: new Buffer('', 'hex') +} +exports['DSA-SHA384'] = exports['DSA-WITH-SHA384'] = { + sign: 'dsa', + hash: 'sha384', + id: new Buffer('', 'hex') +} +exports['DSA-SHA512'] = exports['DSA-WITH-SHA512'] = { + sign: 'dsa', + hash: 'sha512', + id: new Buffer('', 'hex') +} +exports['DSA-RIPEMD160'] = { + sign: 'dsa', + hash: 'rmd160', + id: new Buffer('', 'hex') +} +exports['RSA-RIPEMD160'] = exports.ripemd160WithRSA = { + sign: 'rsa', + hash: 'rmd160', + id: new Buffer('3021300906052b2403020105000414', 'hex') +} +exports['RSA-MD5'] = exports.md5WithRSAEncryption = { + sign: 'rsa', + hash: 'md5', + id: new Buffer('3020300c06082a864886f70d020505000410', 'hex') +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/algos.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/algos.json new file mode 100644 index 0000000..8825455 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/algos.json @@ -0,0 +1,15 @@ +{ + "sha1":"da39a3ee 5e6b4b0d 3255bfef 95601890 afd80709", + + "sha224":"d14a028c 2a3a2bc9 476102bb 288234c4 15a2b01f 828ea62a c5b3e42f", + + "sha256": "e3b0c442 98fc1c14 9afbf4c8 996fb924 27ae41e4 649b934c a495991b 7852b855", + + "sha384": "38b060a7 51ac9638 4cd9327e b1b1e36a 21fdb711 14be0743 4c0cc7bf 63f6e1da 274edebf e76f65fb d51ad2f1 4898b95b", + + "sha512": "cf83e135 7eefb8bd f1542850 d66d8007 d620e405 0b5715dc 83f4a921 d36ce9ce 47d0d13c 5d85f2b0 ff8318d2 877eec2f 63b931bd 47417a81 a538327a f927da3e", + + "sha512/224": "6ed0dd02 806fa89e 25de060c 19d3ac86 cabb87d6 a0ddd05c 333b84f4", + + "sha512/256": "c672b8d1 ef56ed28 ab87c362 2c511406 9bdd3ad7 b8f97374 98d0c01e cef0967a" +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/browser.js new file mode 100644 index 0000000..4ee02ea --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/browser.js @@ -0,0 +1,103 @@ +var _algos = require('./algos') +var createHash = require('create-hash') +var inherits = require('inherits') +var sign = require('./sign') +var stream = require('stream') +var verify = require('./verify') + +var algos = {} +Object.keys(_algos).forEach(function (key) { + algos[key] = algos[key.toLowerCase()] = _algos[key] +}) + +function Sign (algorithm) { + stream.Writable.call(this) + + var data = algos[algorithm] + if (!data) { + throw new Error('Unknown message digest') + } + + this._hashType = data.hash + this._hash = createHash(data.hash) + this._tag = data.id + this._signType = data.sign +} +inherits(Sign, stream.Writable) + +Sign.prototype._write = function _write (data, _, done) { + this._hash.update(data) + done() +} + +Sign.prototype.update = function update (data, enc) { + if (typeof data === 'string') { + data = new Buffer(data, enc) + } + + this._hash.update(data) + return this +} + +Sign.prototype.sign = function signMethod (key, enc) { + this.end() + var hash = this._hash.digest() + var sig = sign(Buffer.concat([this._tag, hash]), key, this._hashType, this._signType) + + return enc ? sig.toString(enc) : sig +} + +function Verify (algorithm) { + stream.Writable.call(this) + + var data = algos[algorithm] + if (!data) { + throw new Error('Unknown message digest') + } + + this._hash = createHash(data.hash) + this._tag = data.id + this._signType = data.sign +} +inherits(Verify, stream.Writable) + +Verify.prototype._write = function _write (data, _, done) { + this._hash.update(data) + + done() +} + +Verify.prototype.update = function update (data, enc) { + if (typeof data === 'string') { + data = new Buffer(data, enc) + } + + this._hash.update(data) + return this +} + +Verify.prototype.verify = function verifyMethod (key, sig, enc) { + if (typeof sig === 'string') { + sig = new Buffer(sig, enc) + } + + this.end() + var hash = this._hash.digest() + + return verify(sig, Buffer.concat([this._tag, hash]), key, this._signType) +} + +function createSign (algorithm) { + return new Sign(algorithm) +} + +function createVerify (algorithm) { + return new Verify(algorithm) +} + +module.exports = { + Sign: createSign, + Verify: createVerify, + createSign: createSign, + createVerify: createVerify +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/curves.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/curves.js new file mode 100644 index 0000000..ea28991 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/curves.js @@ -0,0 +1,12 @@ +'use strict' +exports['1.3.132.0.10'] = 'secp256k1' + +exports['1.3.132.0.33'] = 'p224' + +exports['1.2.840.10045.3.1.1'] = 'p192' + +exports['1.2.840.10045.3.1.7'] = 'p256' + +exports['1.3.132.0.34'] = 'p384' + +exports['1.3.132.0.35'] = 'p521' diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/ec.param b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/ec.param new file mode 100644 index 0000000..9728ddd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/ec.param @@ -0,0 +1,3 @@ +-----BEGIN EC PARAMETERS----- +BgUrgQQAIQ== +-----END EC PARAMETERS----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/index.js new file mode 100644 index 0000000..dafa0bc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/index.js @@ -0,0 +1,7 @@ +var crypto = require('crypto') + +exports.createSign = crypto.createSign +exports.Sign = crypto.Sign + +exports.createVerify = crypto.createVerify +exports.Verify = crypto.Verify diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/.npmignore new file mode 100644 index 0000000..6d1eebb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/.npmignore @@ -0,0 +1,6 @@ +benchmarks/ +coverage/ +node_modules/ +npm-debug.log +1.js +logo.png diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/.travis.yml new file mode 100644 index 0000000..936b7b7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "5" +env: + matrix: + - TEST_SUITE=unit +matrix: + include: + - node_js: "4" + env: TEST_SUITE=lint +script: npm run $TEST_SUITE diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/README.md new file mode 100644 index 0000000..fee65ba --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/README.md @@ -0,0 +1,219 @@ +# bn.js + +> BigNum in pure javascript + +[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) + +## Install +`npm install --save bn.js` + +## Usage + +```js +const BN = require('bn.js'); + +var a = new BN('dead', 16); +var b = new BN('101010', 2); + +var res = a.add(b); +console.log(res.toString(10)); // 57047 +``` + +**Note**: decimals are not supported in this library. + +## Notation + +### Prefixes + +There are several prefixes to instructions that affect the way the work. Here +is the list of them in the order of appearance in the function name: + +* `i` - perform operation in-place, storing the result in the host object (on + which the method was invoked). Might be used to avoid number allocation costs +* `u` - unsigned, ignore the sign of operands when performing operation, or + always return positive value. Second case applies to reduction operations + like `mod()`. In such cases if the result will be negative - modulo will be + added to the result to make it positive + +### Postfixes + +The only available postfix at the moment is: + +* `n` - which means that the argument of the function must be a plain JavaScript + number + +### Examples + +* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` +* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value +* `a.iushln(13)` - shift bits of `a` left by 13 + +## Instructions + +Prefixes/postfixes are put in parens at the of the line. `endian` - could be +either `le` (little-endian) or `be` (big-endian). + +### Utilities + +* `a.clone()` - clone number +* `a.toString(base, length)` - convert to base-string and pad with zeroes +* `a.toNumber()` - convert to Javascript Number (limited to 53 bits) +* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) +* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero + pad to length, throwing if already exceeding +* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, + which must behave like an `Array` +* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available) +* `a.bitLength()` - get number of bits occupied +* `a.zeroBits()` - return number of less-significant consequent zero bits + (example: `1010000` has 4 zero bits) +* `a.byteLength()` - return number of bytes occupied +* `a.isNeg()` - true if the number is negative +* `a.isEven()` - no comments +* `a.isOdd()` - no comments +* `a.isZero()` - no comments +* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) + depending on the comparison result (`ucmp`, `cmpn`) +* `a.lt(b)` - `a` less than `b` (`n`) +* `a.lte(b)` - `a` less than or equals `b` (`n`) +* `a.gt(b)` - `a` greater than `b` (`n`) +* `a.gte(b)` - `a` greater than or equals `b` (`n`) +* `a.eq(b)` - `a` equals `b` (`n`) +* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width +* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width +* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance + +### Arithmetics + +* `a.neg()` - negate sign (`i`) +* `a.abs()` - absolute value (`i`) +* `a.add(b)` - addition (`i`, `n`, `in`) +* `a.sub(b)` - subtraction (`i`, `n`, `in`) +* `a.mul(b)` - multiply (`i`, `n`, `in`) +* `a.sqr()` - square (`i`) +* `a.pow(b)` - raise `a` to the power of `b` +* `a.div(b)` - divide (`divn`, `idivn`) +* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) +* `a.divRound(b)` - rounded division + +### Bit operations + +* `a.or(b)` - or (`i`, `u`, `iu`) +* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced + with `andn` in future) +* `a.xor(b)` - xor (`i`, `u`, `iu`) +* `a.setn(b)` - set specified bit to `1` +* `a.shln(b)` - shift left (`i`, `u`, `iu`) +* `a.shrn(b)` - shift right (`i`, `u`, `iu`) +* `a.testn(b)` - test if specified bit is set +* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) +* `a.bincn(b)` - add `1 << b` to the number +* `a.notn(w)` - not (for the width specified by `w`) (`i`) + +### Reduction + +* `a.gcd(b)` - GCD +* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) +* `a.invm(b)` - inverse `a` modulo `b` + +## Fast reduction + +When doing lots of reductions using the same modulo, it might be beneficial to +use some tricks: like [Montgomery multiplication][0], or using special algorithm +for [Mersenne Prime][1]. + +### Reduction context + +To enable this tricks one should create a reduction context: + +```js +var red = BN.red(num); +``` +where `num` is just a BN instance. + +Or: + +```js +var red = BN.red(primeName); +``` + +Where `primeName` is either of these [Mersenne Primes][1]: + +* `'k256'` +* `'p224'` +* `'p192'` +* `'p25519'` + +Or: + +```js +var red = BN.mont(num); +``` + +To reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than +`.red(num)`, but slower than `BN.red(primeName)`. + +### Converting numbers + +Before performing anything in reduction context - numbers should be converted +to it. Usually, this means that one should: + +* Convert inputs to reducted ones +* Operate on them in reduction context +* Convert outputs back from the reduction context + +Here is how one may convert numbers to `red`: + +```js +var redA = a.toRed(red); +``` +Where `red` is a reduction context created using instructions above + +Here is how to convert them back: + +```js +var a = redA.fromRed(); +``` + +### Red instructions + +Most of the instructions from the very start of this readme have their +counterparts in red context: + +* `a.redAdd(b)`, `a.redIAdd(b)` +* `a.redSub(b)`, `a.redISub(b)` +* `a.redShl(num)` +* `a.redMul(b)`, `a.redIMul(b)` +* `a.redSqr()`, `a.redISqr()` +* `a.redSqrt()` - square root modulo reduction context's prime +* `a.redInvm()` - modular inverse of the number +* `a.redNeg()` +* `a.redPow(b)` - modular exponentiation + +## LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2015. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + +[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication +[1]: https://en.wikipedia.org/wiki/Mersenne_prime diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/lib/bn.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/lib/bn.js new file mode 100644 index 0000000..3ca1646 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/lib/bn.js @@ -0,0 +1,3420 @@ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buf' + 'fer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + return num !== null && typeof num === 'object' && + num.constructor.name === 'BN' && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var length = this.bitLength(); + var ret; + if (length <= 26) { + ret = this.words[0]; + } else if (length <= 52) { + ret = (this.words[1] * 0x4000000) + this.words[0]; + } else if (length === 53) { + // NOTE: at this stage it is known that the top bit is set + ret = 0x10000000000000 + (this.words[1] * 0x4000000) + this.words[0]; + } else { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid += Math.imul(ah0, bl0); + hi = Math.imul(ah0, bh0); + var w0 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w0 >>> 26); + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid += Math.imul(ah1, bl0); + hi = Math.imul(ah1, bh0); + lo += Math.imul(al0, bl1); + mid += Math.imul(al0, bh1); + mid += Math.imul(ah0, bl1); + hi += Math.imul(ah0, bh1); + var w1 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w1 >>> 26); + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid += Math.imul(ah2, bl0); + hi = Math.imul(ah2, bh0); + lo += Math.imul(al1, bl1); + mid += Math.imul(al1, bh1); + mid += Math.imul(ah1, bl1); + hi += Math.imul(ah1, bh1); + lo += Math.imul(al0, bl2); + mid += Math.imul(al0, bh2); + mid += Math.imul(ah0, bl2); + hi += Math.imul(ah0, bh2); + var w2 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w2 >>> 26); + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid += Math.imul(ah3, bl0); + hi = Math.imul(ah3, bh0); + lo += Math.imul(al2, bl1); + mid += Math.imul(al2, bh1); + mid += Math.imul(ah2, bl1); + hi += Math.imul(ah2, bh1); + lo += Math.imul(al1, bl2); + mid += Math.imul(al1, bh2); + mid += Math.imul(ah1, bl2); + hi += Math.imul(ah1, bh2); + lo += Math.imul(al0, bl3); + mid += Math.imul(al0, bh3); + mid += Math.imul(ah0, bl3); + hi += Math.imul(ah0, bh3); + var w3 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w3 >>> 26); + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid += Math.imul(ah4, bl0); + hi = Math.imul(ah4, bh0); + lo += Math.imul(al3, bl1); + mid += Math.imul(al3, bh1); + mid += Math.imul(ah3, bl1); + hi += Math.imul(ah3, bh1); + lo += Math.imul(al2, bl2); + mid += Math.imul(al2, bh2); + mid += Math.imul(ah2, bl2); + hi += Math.imul(ah2, bh2); + lo += Math.imul(al1, bl3); + mid += Math.imul(al1, bh3); + mid += Math.imul(ah1, bl3); + hi += Math.imul(ah1, bh3); + lo += Math.imul(al0, bl4); + mid += Math.imul(al0, bh4); + mid += Math.imul(ah0, bl4); + hi += Math.imul(ah0, bh4); + var w4 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w4 >>> 26); + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid += Math.imul(ah5, bl0); + hi = Math.imul(ah5, bh0); + lo += Math.imul(al4, bl1); + mid += Math.imul(al4, bh1); + mid += Math.imul(ah4, bl1); + hi += Math.imul(ah4, bh1); + lo += Math.imul(al3, bl2); + mid += Math.imul(al3, bh2); + mid += Math.imul(ah3, bl2); + hi += Math.imul(ah3, bh2); + lo += Math.imul(al2, bl3); + mid += Math.imul(al2, bh3); + mid += Math.imul(ah2, bl3); + hi += Math.imul(ah2, bh3); + lo += Math.imul(al1, bl4); + mid += Math.imul(al1, bh4); + mid += Math.imul(ah1, bl4); + hi += Math.imul(ah1, bh4); + lo += Math.imul(al0, bl5); + mid += Math.imul(al0, bh5); + mid += Math.imul(ah0, bl5); + hi += Math.imul(ah0, bh5); + var w5 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w5 >>> 26); + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid += Math.imul(ah6, bl0); + hi = Math.imul(ah6, bh0); + lo += Math.imul(al5, bl1); + mid += Math.imul(al5, bh1); + mid += Math.imul(ah5, bl1); + hi += Math.imul(ah5, bh1); + lo += Math.imul(al4, bl2); + mid += Math.imul(al4, bh2); + mid += Math.imul(ah4, bl2); + hi += Math.imul(ah4, bh2); + lo += Math.imul(al3, bl3); + mid += Math.imul(al3, bh3); + mid += Math.imul(ah3, bl3); + hi += Math.imul(ah3, bh3); + lo += Math.imul(al2, bl4); + mid += Math.imul(al2, bh4); + mid += Math.imul(ah2, bl4); + hi += Math.imul(ah2, bh4); + lo += Math.imul(al1, bl5); + mid += Math.imul(al1, bh5); + mid += Math.imul(ah1, bl5); + hi += Math.imul(ah1, bh5); + lo += Math.imul(al0, bl6); + mid += Math.imul(al0, bh6); + mid += Math.imul(ah0, bl6); + hi += Math.imul(ah0, bh6); + var w6 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w6 >>> 26); + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid += Math.imul(ah7, bl0); + hi = Math.imul(ah7, bh0); + lo += Math.imul(al6, bl1); + mid += Math.imul(al6, bh1); + mid += Math.imul(ah6, bl1); + hi += Math.imul(ah6, bh1); + lo += Math.imul(al5, bl2); + mid += Math.imul(al5, bh2); + mid += Math.imul(ah5, bl2); + hi += Math.imul(ah5, bh2); + lo += Math.imul(al4, bl3); + mid += Math.imul(al4, bh3); + mid += Math.imul(ah4, bl3); + hi += Math.imul(ah4, bh3); + lo += Math.imul(al3, bl4); + mid += Math.imul(al3, bh4); + mid += Math.imul(ah3, bl4); + hi += Math.imul(ah3, bh4); + lo += Math.imul(al2, bl5); + mid += Math.imul(al2, bh5); + mid += Math.imul(ah2, bl5); + hi += Math.imul(ah2, bh5); + lo += Math.imul(al1, bl6); + mid += Math.imul(al1, bh6); + mid += Math.imul(ah1, bl6); + hi += Math.imul(ah1, bh6); + lo += Math.imul(al0, bl7); + mid += Math.imul(al0, bh7); + mid += Math.imul(ah0, bl7); + hi += Math.imul(ah0, bh7); + var w7 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w7 >>> 26); + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid += Math.imul(ah8, bl0); + hi = Math.imul(ah8, bh0); + lo += Math.imul(al7, bl1); + mid += Math.imul(al7, bh1); + mid += Math.imul(ah7, bl1); + hi += Math.imul(ah7, bh1); + lo += Math.imul(al6, bl2); + mid += Math.imul(al6, bh2); + mid += Math.imul(ah6, bl2); + hi += Math.imul(ah6, bh2); + lo += Math.imul(al5, bl3); + mid += Math.imul(al5, bh3); + mid += Math.imul(ah5, bl3); + hi += Math.imul(ah5, bh3); + lo += Math.imul(al4, bl4); + mid += Math.imul(al4, bh4); + mid += Math.imul(ah4, bl4); + hi += Math.imul(ah4, bh4); + lo += Math.imul(al3, bl5); + mid += Math.imul(al3, bh5); + mid += Math.imul(ah3, bl5); + hi += Math.imul(ah3, bh5); + lo += Math.imul(al2, bl6); + mid += Math.imul(al2, bh6); + mid += Math.imul(ah2, bl6); + hi += Math.imul(ah2, bh6); + lo += Math.imul(al1, bl7); + mid += Math.imul(al1, bh7); + mid += Math.imul(ah1, bl7); + hi += Math.imul(ah1, bh7); + lo += Math.imul(al0, bl8); + mid += Math.imul(al0, bh8); + mid += Math.imul(ah0, bl8); + hi += Math.imul(ah0, bh8); + var w8 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w8 >>> 26); + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid += Math.imul(ah9, bl0); + hi = Math.imul(ah9, bh0); + lo += Math.imul(al8, bl1); + mid += Math.imul(al8, bh1); + mid += Math.imul(ah8, bl1); + hi += Math.imul(ah8, bh1); + lo += Math.imul(al7, bl2); + mid += Math.imul(al7, bh2); + mid += Math.imul(ah7, bl2); + hi += Math.imul(ah7, bh2); + lo += Math.imul(al6, bl3); + mid += Math.imul(al6, bh3); + mid += Math.imul(ah6, bl3); + hi += Math.imul(ah6, bh3); + lo += Math.imul(al5, bl4); + mid += Math.imul(al5, bh4); + mid += Math.imul(ah5, bl4); + hi += Math.imul(ah5, bh4); + lo += Math.imul(al4, bl5); + mid += Math.imul(al4, bh5); + mid += Math.imul(ah4, bl5); + hi += Math.imul(ah4, bh5); + lo += Math.imul(al3, bl6); + mid += Math.imul(al3, bh6); + mid += Math.imul(ah3, bl6); + hi += Math.imul(ah3, bh6); + lo += Math.imul(al2, bl7); + mid += Math.imul(al2, bh7); + mid += Math.imul(ah2, bl7); + hi += Math.imul(ah2, bh7); + lo += Math.imul(al1, bl8); + mid += Math.imul(al1, bh8); + mid += Math.imul(ah1, bl8); + hi += Math.imul(ah1, bh8); + lo += Math.imul(al0, bl9); + mid += Math.imul(al0, bh9); + mid += Math.imul(ah0, bl9); + hi += Math.imul(ah0, bh9); + var w9 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w9 >>> 26); + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid += Math.imul(ah9, bl1); + hi = Math.imul(ah9, bh1); + lo += Math.imul(al8, bl2); + mid += Math.imul(al8, bh2); + mid += Math.imul(ah8, bl2); + hi += Math.imul(ah8, bh2); + lo += Math.imul(al7, bl3); + mid += Math.imul(al7, bh3); + mid += Math.imul(ah7, bl3); + hi += Math.imul(ah7, bh3); + lo += Math.imul(al6, bl4); + mid += Math.imul(al6, bh4); + mid += Math.imul(ah6, bl4); + hi += Math.imul(ah6, bh4); + lo += Math.imul(al5, bl5); + mid += Math.imul(al5, bh5); + mid += Math.imul(ah5, bl5); + hi += Math.imul(ah5, bh5); + lo += Math.imul(al4, bl6); + mid += Math.imul(al4, bh6); + mid += Math.imul(ah4, bl6); + hi += Math.imul(ah4, bh6); + lo += Math.imul(al3, bl7); + mid += Math.imul(al3, bh7); + mid += Math.imul(ah3, bl7); + hi += Math.imul(ah3, bh7); + lo += Math.imul(al2, bl8); + mid += Math.imul(al2, bh8); + mid += Math.imul(ah2, bl8); + hi += Math.imul(ah2, bh8); + lo += Math.imul(al1, bl9); + mid += Math.imul(al1, bh9); + mid += Math.imul(ah1, bl9); + hi += Math.imul(ah1, bh9); + var w10 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w10 >>> 26); + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid += Math.imul(ah9, bl2); + hi = Math.imul(ah9, bh2); + lo += Math.imul(al8, bl3); + mid += Math.imul(al8, bh3); + mid += Math.imul(ah8, bl3); + hi += Math.imul(ah8, bh3); + lo += Math.imul(al7, bl4); + mid += Math.imul(al7, bh4); + mid += Math.imul(ah7, bl4); + hi += Math.imul(ah7, bh4); + lo += Math.imul(al6, bl5); + mid += Math.imul(al6, bh5); + mid += Math.imul(ah6, bl5); + hi += Math.imul(ah6, bh5); + lo += Math.imul(al5, bl6); + mid += Math.imul(al5, bh6); + mid += Math.imul(ah5, bl6); + hi += Math.imul(ah5, bh6); + lo += Math.imul(al4, bl7); + mid += Math.imul(al4, bh7); + mid += Math.imul(ah4, bl7); + hi += Math.imul(ah4, bh7); + lo += Math.imul(al3, bl8); + mid += Math.imul(al3, bh8); + mid += Math.imul(ah3, bl8); + hi += Math.imul(ah3, bh8); + lo += Math.imul(al2, bl9); + mid += Math.imul(al2, bh9); + mid += Math.imul(ah2, bl9); + hi += Math.imul(ah2, bh9); + var w11 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w11 >>> 26); + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid += Math.imul(ah9, bl3); + hi = Math.imul(ah9, bh3); + lo += Math.imul(al8, bl4); + mid += Math.imul(al8, bh4); + mid += Math.imul(ah8, bl4); + hi += Math.imul(ah8, bh4); + lo += Math.imul(al7, bl5); + mid += Math.imul(al7, bh5); + mid += Math.imul(ah7, bl5); + hi += Math.imul(ah7, bh5); + lo += Math.imul(al6, bl6); + mid += Math.imul(al6, bh6); + mid += Math.imul(ah6, bl6); + hi += Math.imul(ah6, bh6); + lo += Math.imul(al5, bl7); + mid += Math.imul(al5, bh7); + mid += Math.imul(ah5, bl7); + hi += Math.imul(ah5, bh7); + lo += Math.imul(al4, bl8); + mid += Math.imul(al4, bh8); + mid += Math.imul(ah4, bl8); + hi += Math.imul(ah4, bh8); + lo += Math.imul(al3, bl9); + mid += Math.imul(al3, bh9); + mid += Math.imul(ah3, bl9); + hi += Math.imul(ah3, bh9); + var w12 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w12 >>> 26); + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid += Math.imul(ah9, bl4); + hi = Math.imul(ah9, bh4); + lo += Math.imul(al8, bl5); + mid += Math.imul(al8, bh5); + mid += Math.imul(ah8, bl5); + hi += Math.imul(ah8, bh5); + lo += Math.imul(al7, bl6); + mid += Math.imul(al7, bh6); + mid += Math.imul(ah7, bl6); + hi += Math.imul(ah7, bh6); + lo += Math.imul(al6, bl7); + mid += Math.imul(al6, bh7); + mid += Math.imul(ah6, bl7); + hi += Math.imul(ah6, bh7); + lo += Math.imul(al5, bl8); + mid += Math.imul(al5, bh8); + mid += Math.imul(ah5, bl8); + hi += Math.imul(ah5, bh8); + lo += Math.imul(al4, bl9); + mid += Math.imul(al4, bh9); + mid += Math.imul(ah4, bl9); + hi += Math.imul(ah4, bh9); + var w13 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w13 >>> 26); + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid += Math.imul(ah9, bl5); + hi = Math.imul(ah9, bh5); + lo += Math.imul(al8, bl6); + mid += Math.imul(al8, bh6); + mid += Math.imul(ah8, bl6); + hi += Math.imul(ah8, bh6); + lo += Math.imul(al7, bl7); + mid += Math.imul(al7, bh7); + mid += Math.imul(ah7, bl7); + hi += Math.imul(ah7, bh7); + lo += Math.imul(al6, bl8); + mid += Math.imul(al6, bh8); + mid += Math.imul(ah6, bl8); + hi += Math.imul(ah6, bh8); + lo += Math.imul(al5, bl9); + mid += Math.imul(al5, bh9); + mid += Math.imul(ah5, bl9); + hi += Math.imul(ah5, bh9); + var w14 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w14 >>> 26); + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid += Math.imul(ah9, bl6); + hi = Math.imul(ah9, bh6); + lo += Math.imul(al8, bl7); + mid += Math.imul(al8, bh7); + mid += Math.imul(ah8, bl7); + hi += Math.imul(ah8, bh7); + lo += Math.imul(al7, bl8); + mid += Math.imul(al7, bh8); + mid += Math.imul(ah7, bl8); + hi += Math.imul(ah7, bh8); + lo += Math.imul(al6, bl9); + mid += Math.imul(al6, bh9); + mid += Math.imul(ah6, bl9); + hi += Math.imul(ah6, bh9); + var w15 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w15 >>> 26); + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid += Math.imul(ah9, bl7); + hi = Math.imul(ah9, bh7); + lo += Math.imul(al8, bl8); + mid += Math.imul(al8, bh8); + mid += Math.imul(ah8, bl8); + hi += Math.imul(ah8, bh8); + lo += Math.imul(al7, bl9); + mid += Math.imul(al7, bh9); + mid += Math.imul(ah7, bl9); + hi += Math.imul(ah7, bh9); + var w16 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w16 >>> 26); + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid += Math.imul(ah9, bl8); + hi = Math.imul(ah9, bh8); + lo += Math.imul(al8, bl9); + mid += Math.imul(al8, bh9); + mid += Math.imul(ah8, bl9); + hi += Math.imul(ah8, bh9); + var w17 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w17 >>> 26); + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid += Math.imul(ah9, bl9); + hi = Math.imul(ah9, bh9); + var w18 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w18 >>> 26); + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})(typeof module === 'undefined' || module, this); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/package.json new file mode 100644 index 0000000..63ecf80 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/package.json @@ -0,0 +1,42 @@ +{ + "name": "bn.js", + "version": "4.11.1", + "description": "Big number implementation in pure javascript", + "main": "lib/bn.js", + "scripts": { + "lint": "semistandard", + "unit": "mocha --reporter=spec test/*-test.js", + "test": "npm run lint && npm run unit" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/bn.js.git" + }, + "keywords": [ + "BN", + "BigNum", + "Big number", + "Modulo", + "Montgomery" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/bn.js/issues" + }, + "homepage": "https://github.com/indutny/bn.js", + "devDependencies": { + "istanbul": "^0.3.5", + "mocha": "^2.1.0", + "semistandard": "^7.0.4" + }, + "readme": "# \"bn.js\"\n\n> BigNum in pure javascript\n\n[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js)\n\n## Install\n`npm install --save bn.js`\n\n## Usage\n\n```js\nconst BN = require('bn.js');\n\nvar a = new BN('dead', 16);\nvar b = new BN('101010', 2);\n\nvar res = a.add(b);\nconsole.log(res.toString(10)); // 57047\n```\n\n**Note**: decimals are not supported in this library.\n\n## Notation\n\n### Prefixes\n\nThere are several prefixes to instructions that affect the way the work. Here\nis the list of them in the order of appearance in the function name:\n\n* `i` - perform operation in-place, storing the result in the host object (on\n which the method was invoked). Might be used to avoid number allocation costs\n* `u` - unsigned, ignore the sign of operands when performing operation, or\n always return positive value. Second case applies to reduction operations\n like `mod()`. In such cases if the result will be negative - modulo will be\n added to the result to make it positive\n\n### Postfixes\n\nThe only available postfix at the moment is:\n\n* `n` - which means that the argument of the function must be a plain JavaScript\n number\n\n### Examples\n\n* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a`\n* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value\n* `a.iushln(13)` - shift bits of `a` left by 13\n\n## Instructions\n\nPrefixes/postfixes are put in parens at the of the line. `endian` - could be\neither `le` (little-endian) or `be` (big-endian).\n\n### Utilities\n\n* `a.clone()` - clone number\n* `a.toString(base, length)` - convert to base-string and pad with zeroes\n* `a.toNumber()` - convert to Javascript Number (limited to 53 bits)\n* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`)\n* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero\n pad to length, throwing if already exceeding\n* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`,\n which must behave like an `Array`\n* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available)\n* `a.bitLength()` - get number of bits occupied\n* `a.zeroBits()` - return number of less-significant consequent zero bits\n (example: `1010000` has 4 zero bits)\n* `a.byteLength()` - return number of bytes occupied\n* `a.isNeg()` - true if the number is negative\n* `a.isEven()` - no comments\n* `a.isOdd()` - no comments\n* `a.isZero()` - no comments\n* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b)\n depending on the comparison result (`ucmp`, `cmpn`)\n* `a.lt(b)` - `a` less than `b` (`n`)\n* `a.lte(b)` - `a` less than or equals `b` (`n`)\n* `a.gt(b)` - `a` greater than `b` (`n`)\n* `a.gte(b)` - `a` greater than or equals `b` (`n`)\n* `a.eq(b)` - `a` equals `b` (`n`)\n* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width\n* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width\n* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance\n\n### Arithmetics\n\n* `a.neg()` - negate sign (`i`)\n* `a.abs()` - absolute value (`i`)\n* `a.add(b)` - addition (`i`, `n`, `in`)\n* `a.sub(b)` - subtraction (`i`, `n`, `in`)\n* `a.mul(b)` - multiply (`i`, `n`, `in`)\n* `a.sqr()` - square (`i`)\n* `a.pow(b)` - raise `a` to the power of `b`\n* `a.div(b)` - divide (`divn`, `idivn`)\n* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`)\n* `a.divRound(b)` - rounded division\n\n### Bit operations\n\n* `a.or(b)` - or (`i`, `u`, `iu`)\n* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced\n with `andn` in future)\n* `a.xor(b)` - xor (`i`, `u`, `iu`)\n* `a.setn(b)` - set specified bit to `1`\n* `a.shln(b)` - shift left (`i`, `u`, `iu`)\n* `a.shrn(b)` - shift right (`i`, `u`, `iu`)\n* `a.testn(b)` - test if specified bit is set\n* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`)\n* `a.bincn(b)` - add `1 << b` to the number\n* `a.notn(w)` - not (for the width specified by `w`) (`i`)\n\n### Reduction\n\n* `a.gcd(b)` - GCD\n* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`)\n* `a.invm(b)` - inverse `a` modulo `b`\n\n## Fast reduction\n\nWhen doing lots of reductions using the same modulo, it might be beneficial to\nuse some tricks: like [Montgomery multiplication][0], or using special algorithm\nfor [Mersenne Prime][1].\n\n### Reduction context\n\nTo enable this tricks one should create a reduction context:\n\n```js\nvar red = BN.red(num);\n```\nwhere `num` is just a BN instance.\n\nOr:\n\n```js\nvar red = BN.red(primeName);\n```\n\nWhere `primeName` is either of these [Mersenne Primes][1]:\n\n* `'k256'`\n* `'p224'`\n* `'p192'`\n* `'p25519'`\n\nOr:\n\n```js\nvar red = BN.mont(num);\n```\n\nTo reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than\n`.red(num)`, but slower than `BN.red(primeName)`.\n\n### Converting numbers\n\nBefore performing anything in reduction context - numbers should be converted\nto it. Usually, this means that one should:\n\n* Convert inputs to reducted ones\n* Operate on them in reduction context\n* Convert outputs back from the reduction context\n\nHere is how one may convert numbers to `red`:\n\n```js\nvar redA = a.toRed(red);\n```\nWhere `red` is a reduction context created using instructions above\n\nHere is how to convert them back:\n\n```js\nvar a = redA.fromRed();\n```\n\n### Red instructions\n\nMost of the instructions from the very start of this readme have their\ncounterparts in red context:\n\n* `a.redAdd(b)`, `a.redIAdd(b)`\n* `a.redSub(b)`, `a.redISub(b)`\n* `a.redShl(num)`\n* `a.redMul(b)`, `a.redIMul(b)`\n* `a.redSqr()`, `a.redISqr()`\n* `a.redSqrt()` - square root modulo reduction context's prime\n* `a.redInvm()` - modular inverse of the number\n* `a.redNeg()`\n* `a.redPow(b)` - modular exponentiation\n\n## LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2015.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication\n[1]: https://en.wikipedia.org/wiki/Mersenne_prime\n", + "readmeFilename": "README.md", + "_id": "bn.js@4.11.1", + "_shasum": "ff1c52c52fd371e9d91419439bac5cfba2b41798", + "_resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz", + "_from": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/arithmetic-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/arithmetic-test.js new file mode 100644 index 0000000..3f336ac --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/arithmetic-test.js @@ -0,0 +1,635 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; +var fixtures = require('./fixtures'); + +describe('BN.js/Arithmetic', function () { + describe('.add()', function () { + it('should add numbers', function () { + assert.equal(new BN(14).add(new BN(26)).toString(16), '28'); + var k = new BN(0x1234); + var r = k; + + for (var i = 0; i < 257; i++) { + r = r.add(k); + } + + assert.equal(r.toString(16), '125868'); + }); + + it('should handle carry properly (in-place)', function () { + var k = new BN('abcdefabcdefabcdef', 16); + var r = new BN('deadbeef', 16); + + for (var i = 0; i < 257; i++) { + r.iadd(k); + } + + assert.equal(r.toString(16), 'ac79bd9b79be7a277bde'); + }); + + it('should properly do positive + negative', function () { + var a = new BN('abcd', 16); + var b = new BN('-abce', 16); + + assert.equal(a.iadd(b).toString(16), '-1'); + + a = new BN('abcd', 16); + b = new BN('-abce', 16); + + assert.equal(a.add(b).toString(16), '-1'); + assert.equal(b.add(a).toString(16), '-1'); + }); + }); + + describe('.iaddn()', function () { + it('should allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should add negative number', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(-200); + + assert.equal(a.toString(), '-300'); + }); + + it('should allow neg + pos with big number', function () { + var a = new BN('-1000000000', 10); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.toString(), '-999999800'); + }); + + it('should carry limb', function () { + var a = new BN('3ffffff', 16); + + assert.equal(a.iaddn(1).toString(16), '4000000'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).iaddn(0x4000000); + }); + }); + }); + + describe('.sub()', function () { + it('should subtract small numbers', function () { + assert.equal(new BN(26).sub(new BN(14)).toString(16), 'c'); + assert.equal(new BN(14).sub(new BN(26)).toString(16), '-c'); + assert.equal(new BN(26).sub(new BN(26)).toString(16), '0'); + assert.equal(new BN(-26).sub(new BN(26)).toString(16), '-34'); + }); + + var a = new BN( + '31ff3c61db2db84b9823d320907a573f6ad37c437abe458b1802cda041d6384' + + 'a7d8daef41395491e2', + 16); + var b = new BN( + '6f0e4d9f1d6071c183677f601af9305721c91d31b0bbbae8fb790000', + 16); + var r = new BN( + '31ff3c61db2db84b9823d3208989726578fd75276287cd9516533a9acfb9a67' + + '76281f34583ddb91e2', + 16); + + it('should subtract big numbers', function () { + assert.equal(a.sub(b).cmp(r), 0); + }); + + it('should subtract numbers in place', function () { + assert.equal(b.clone().isub(a).neg().cmp(r), 0); + }); + + it('should subtract with carry', function () { + // Carry and copy + var a = new BN('12345', 16); + var b = new BN('1000000000000', 16); + assert.equal(a.isub(b).toString(16), '-fffffffedcbb'); + + a = new BN('12345', 16); + b = new BN('1000000000000', 16); + assert.equal(b.isub(a).toString(16), 'fffffffedcbb'); + }); + }); + + describe('.isubn()', function () { + it('should subtract negative number', function () { + var r = new BN( + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b', 16); + assert.equal(r.isubn(-1).toString(16), + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681c'); + }); + + it('should work for positive numbers', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(200); + assert.equal(a.negative, 1); + assert.equal(a.toString(), '-300'); + }); + + it('should not allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(-200); + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should change sign on small numbers at 0', function () { + var a = new BN(0).subn(2); + assert.equal(a.toString(), '-2'); + }); + + it('should change sign on small numbers at 1', function () { + var a = new BN(1).subn(2); + assert.equal(a.toString(), '-1'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).isubn(0x4000000); + }); + }); + }); + + function testMethod (name, mul) { + describe(name, function () { + it('should multiply numbers of different signs', function () { + var offsets = [ + 1, // smallMulTo + 250, // comb10MulTo + 1000, // bigMulTo + 15000 // jumboMulTo + ]; + + for (var i = 0; i < offsets.length; ++i) { + var x = new BN(1).ishln(offsets[i]); + + assert.equal(mul(x, x).isNeg(), false); + assert.equal(mul(x, x.neg()).isNeg(), true); + assert.equal(mul(x.neg(), x).isNeg(), true); + assert.equal(mul(x.neg(), x.neg()).isNeg(), false); + } + }); + + it('should multiply with carry', function () { + var n = new BN(0x1001); + var r = n; + + for (var i = 0; i < 4; i++) { + r = mul(r, n); + } + + assert.equal(r.toString(16), '100500a00a005001'); + }); + + it('should correctly multiply big numbers', function () { + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal( + mul(n, n).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40'); + assert.equal( + mul(mul(n, n), n).toString(16), + '1b888e01a06e974017a28a5b4da436169761c9730b7aeedf75fc60f687b' + + '46e0cf2cb11667f795d5569482640fe5f628939467a01a612b02350' + + '0d0161e9730279a7561043af6197798e41b7432458463e64fa81158' + + '907322dc330562697d0d600'); + }); + + it('should multiply neg number on 0', function () { + assert.equal( + mul(new BN('-100000000000'), new BN('3').div(new BN('4'))) + .toString(16), + '0' + ); + }); + + it('should regress mul big numbers', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + assert.equal(mul(q, q).toString(16), qs); + }); + }); + } + + testMethod('.mul()', function (x, y) { + return BN.prototype.mul.apply(x, [ y ]); + }); + + testMethod('.mulf()', function (x, y) { + return BN.prototype.mulf.apply(x, [ y ]); + }); + + describe('.imul()', function () { + it('should multiply numbers in-place', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('deadbeefa551edebabba8', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + + a = new BN('abcdef01234567890abcd214a25123f512361e6d236', 16); + b = new BN('deadbeefa551edebabba8121234fd21bac0341324dd', 16); + c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should multiply by 0', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('0', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should regress mul big numbers in-place', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + + assert.equal(q.isqr().toString(16), qs); + }); + }); + + describe('.muln()', function () { + it('should multiply number by small number', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('dead', 16); + var c = a.mul(b); + + assert.equal(a.muln(0xdead).toString(16), c.toString(16)); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).imuln(0x4000000); + }); + }); + }); + + describe('.pow()', function () { + it('should raise number to the power', function () { + var a = new BN('ab', 16); + var b = new BN('13', 10); + var c = a.pow(b); + + assert.equal(c.toString(16), '15963da06977df51909c9ba5b'); + }); + }); + + describe('.div()', function () { + it('should divide small numbers (<=26 bits)', function () { + assert.equal(new BN('256').div(new BN(10)).toString(10), + '25'); + assert.equal(new BN('-256').div(new BN(10)).toString(10), + '-25'); + assert.equal(new BN('256').div(new BN(-10)).toString(10), + '-25'); + assert.equal(new BN('-256').div(new BN(-10)).toString(10), + '25'); + + assert.equal(new BN('10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('10').div(new BN(-256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(-256)).toString(10), + '0'); + }); + + it('should divide large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').div(new BN('611111124969028')) + .toString(10), '1'); + assert.equal(new BN('-1222222225255589').div(new BN('611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('1222222225255589').div(new BN('-611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('-1222222225255589').div(new BN('-611111124969028')) + .toString(10), '1'); + + assert.equal(new BN('611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + }); + + it('should divide numbers', function () { + assert.equal(new BN('69527932928').div(new BN('16974594')).toString(16), + 'fff'); + assert.equal(new BN('-69527932928').div(new BN('16974594')).toString(16), + '-fff'); + + var b = new BN( + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40', + 16); + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal(b.div(n).toString(16), n.toString(16)); + + assert.equal(new BN('1').div(new BN('-5')).toString(10), '0'); + }); + + it('should not fail on regression after moving to _wordDiv', function () { + // Regression after moving to word div + var p = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', + 16); + var a = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16); + var as = a.sqr(); + assert.equal( + as.div(p).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729e58090b9'); + + p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.div(p).toString(16), + 'ffffffff00000002000000000000000000000001000000000000000000000001'); + }); + }); + + describe('.idivn()', function () { + it('should divide numbers in-place', function () { + assert.equal(new BN('10', 16).idivn(3).toString(16), '5'); + assert.equal(new BN('12', 16).idivn(3).toString(16), '6'); + assert.equal(new BN('10000000000000000').idivn(3).toString(10), + '3333333333333333'); + assert.equal( + new BN('100000000000000000000000000000').idivn(3).toString(10), + '33333333333333333333333333333'); + + var t = new BN(3); + assert.equal( + new BN('12345678901234567890123456', 16).idivn(3).toString(16), + new BN('12345678901234567890123456', 16).div(t).toString(16)); + }); + }); + + describe('.divRound()', function () { + it('should divide numbers with rounding', function () { + assert.equal(new BN(9).divRound(new BN(20)).toString(10), + '0'); + assert.equal(new BN(10).divRound(new BN(20)).toString(10), + '1'); + assert.equal(new BN(150).divRound(new BN(20)).toString(10), + '8'); + assert.equal(new BN(149).divRound(new BN(20)).toString(10), + '7'); + assert.equal(new BN(149).divRound(new BN(17)).toString(10), + '9'); + assert.equal(new BN(144).divRound(new BN(17)).toString(10), + '8'); + assert.equal(new BN(-144).divRound(new BN(17)).toString(10), + '-8'); + }); + + it('should return 1 on exact division', function () { + assert.equal(new BN(144).divRound(new BN(144)).toString(10), '1'); + }); + }); + + describe('.mod()', function () { + it('should modulo small numbers (<=26 bits)', function () { + assert.equal(new BN('256').mod(new BN(10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(10)).toString(10), + '-6'); + assert.equal(new BN('256').mod(new BN(-10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(-10)).toString(10), + '-6'); + + assert.equal(new BN('10').mod(new BN(256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(256)).toString(10), + '-10'); + assert.equal(new BN('10').mod(new BN(-256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(-256)).toString(10), + '-10'); + }); + + it('should modulo large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').mod(new BN('611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('611111124969028')) + .toString(10), '-611111100286561'); + assert.equal(new BN('1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '-611111100286561'); + + assert.equal(new BN('611111124969028').mod(new BN('1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('1222222225255589')) + .toString(10), '-611111124969028'); + assert.equal(new BN('611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '-611111124969028'); + }); + + it('should mod numbers', function () { + assert.equal(new BN('10').mod(new BN(256)).toString(16), + 'a'); + assert.equal(new BN('69527932928').mod(new BN('16974594')).toString(16), + '102f302'); + + // 178 = 10 * 17 + 8 + assert.equal(new BN(178).div(new BN(10)).toNumber(), 17); + assert.equal(new BN(178).mod(new BN(10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(10)).toNumber(), 8); + + // -178 = 10 * (-17) + (-8) + assert.equal(new BN(-178).div(new BN(10)).toNumber(), -17); + assert.equal(new BN(-178).mod(new BN(10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(10)).toNumber(), 2); + + // 178 = -10 * (-17) + 8 + assert.equal(new BN(178).div(new BN(-10)).toNumber(), -17); + assert.equal(new BN(178).mod(new BN(-10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(-10)).toNumber(), 8); + + // -178 = -10 * (17) + (-8) + assert.equal(new BN(-178).div(new BN(-10)).toNumber(), 17); + assert.equal(new BN(-178).mod(new BN(-10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(-10)).toNumber(), 2); + + // -4 = 1 * (-3) + -1 + assert.equal(new BN(-4).div(new BN(-3)).toNumber(), 1); + assert.equal(new BN(-4).mod(new BN(-3)).toNumber(), -1); + + // -4 = -1 * (3) + -1 + assert.equal(new BN(-4).mod(new BN(3)).toNumber(), -1); + // -4 = 1 * (-3) + (-1 + 3) + assert.equal(new BN(-4).umod(new BN(-3)).toNumber(), 2); + + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.mod(p).toString(16), + '0'); + }); + + it('should properly carry the sign inside division', function () { + var a = new BN('945304eb96065b2a98b57a48a06ae28d285a71b5', 'hex'); + var b = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe', + 'hex'); + + assert.equal(a.mul(b).mod(a).cmpn(0), 0); + }); + }); + + describe('.modn()', function () { + it('should act like .mod() on small numbers', function () { + assert.equal(new BN('10', 16).modn(256).toString(16), '10'); + assert.equal(new BN('100', 16).modn(256).toString(16), '0'); + assert.equal(new BN('1001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(257).toString(16), + new BN('100000000001', 16).mod(new BN(257)).toString(16)); + assert.equal(new BN('123456789012', 16).modn(3).toString(16), + new BN('123456789012', 16).mod(new BN(3)).toString(16)); + }); + }); + + describe('.abs()', function () { + it('should return absolute value', function () { + assert.equal(new BN(0x1001).abs().toString(), '4097'); + assert.equal(new BN(-0x1001).abs().toString(), '4097'); + assert.equal(new BN('ffffffff', 16).abs().toString(), '4294967295'); + }); + }); + + describe('.invm()', function () { + it('should invert relatively-prime numbers', function () { + var p = new BN(257); + var a = new BN(3); + var b = a.invm(p); + assert.equal(a.mul(b).mod(p).toString(16), '1'); + + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + a = new BN('deadbeef', 16); + b = a.invm(p192); + assert.equal(a.mul(b).mod(p192).toString(16), '1'); + + // Even base + var phi = new BN('872d9b030ba368706b68932cf07a0e0c', 16); + var e = new BN(65537); + var d = e.invm(phi); + assert.equal(e.mul(d).mod(phi).toString(16), '1'); + + // Even base (take #2) + a = new BN('5'); + b = new BN('6'); + var r = a.invm(b); + assert.equal(r.mul(a).mod(b).toString(16), '1'); + }); + }); + + describe('.gcd()', function () { + it('should return GCD', function () { + assert.equal(new BN(3).gcd(new BN(2)).toString(10), '1'); + assert.equal(new BN(18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(-12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(0)).toString(10), '18'); + assert.equal(new BN(0).gcd(new BN(-18)).toString(10), '18'); + assert.equal(new BN(2).gcd(new BN(0)).toString(10), '2'); + assert.equal(new BN(0).gcd(new BN(3)).toString(10), '3'); + assert.equal(new BN(0).gcd(new BN(0)).toString(10), '0'); + }); + }); + + describe('.egcd()', function () { + it('should return EGCD', function () { + assert.equal(new BN(3).egcd(new BN(2)).gcd.toString(10), '1'); + assert.equal(new BN(18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(-18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(0).egcd(new BN(12)).gcd.toString(10), '12'); + }); + it('should not allow 0 input', function () { + assert.throws(function () { + BN(1).egcd(0); + }); + }); + it('should not allow negative input', function () { + assert.throws(function () { + BN(1).egcd(-1); + }); + }); + }); + + describe('BN.max(a, b)', function () { + it('should return maximum', function () { + assert.equal(BN.max(new BN(3), new BN(2)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(3)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.max(new BN(2), new BN(-2)).toString(16), '2'); + }); + }); + + describe('BN.min(a, b)', function () { + it('should return minimum', function () { + assert.equal(BN.min(new BN(3), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(3)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(-2)).toString(16), '-2'); + }); + }); + + describe('BN.ineg', function () { + it('shouldn\'t change sign for zero', function () { + assert.equal(new BN(0).ineg().toString(10), '0'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/binary-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/binary-test.js new file mode 100644 index 0000000..b73242c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/binary-test.js @@ -0,0 +1,228 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Binary', function () { + describe('.shl()', function () { + it('should shl numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').shln(45).toString(16), + '206060200000000000000'); + }); + + it('should ushl numbers', function () { + assert.equal(new BN('69527932928').ushln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').ushln(45).toString(16), + '206060200000000000000'); + }); + }); + + describe('.shr()', function () { + it('should shr numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').shrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').shrn(256).toString(16), + '0'); + }); + + it('should ushr numbers', function () { + assert.equal(new BN('69527932928').ushrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').ushrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').ushrn(256).toString(16), + '0'); + }); + }); + + describe('.bincn()', function () { + it('should increment bit', function () { + assert.equal(new BN(0).bincn(1).toString(16), '2'); + assert.equal(new BN(2).bincn(1).toString(16), '4'); + assert.equal(new BN(2).bincn(1).bincn(1).toString(16), + new BN(2).bincn(2).toString(16)); + assert.equal(new BN(0xffffff).bincn(1).toString(16), '1000001'); + assert.equal(new BN(2).bincn(63).toString(16), + '8000000000000002'); + }); + }); + + describe('.imaskn()', function () { + it('should mask bits in-place', function () { + assert.equal(new BN(0).imaskn(1).toString(16), '0'); + assert.equal(new BN(3).imaskn(1).toString(16), '1'); + assert.equal(new BN('123456789', 16).imaskn(4).toString(16), '9'); + assert.equal(new BN('123456789', 16).imaskn(16).toString(16), '6789'); + assert.equal(new BN('123456789', 16).imaskn(28).toString(16), '3456789'); + }); + }); + + describe('.testn()', function () { + it('should support test specific bit', function () { + [ + 'ff', + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' + ].forEach(function (hex) { + var bn = new BN(hex, 16); + var bl = bn.bitLength(); + + for (var i = 0; i < bl; ++i) { + assert.equal(bn.testn(i), true); + } + + // test off the end + assert.equal(bn.testn(bl), false); + }); + + var xbits = '01111001010111001001000100011101' + + '11010011101100011000111001011101' + + '10010100111000000001011000111101' + + '01011111001111100100011110000010' + + '01011010100111010001010011000100' + + '01101001011110100001001111100110' + + '001110010111'; + + var x = new BN( + '23478905234580795234378912401239784125643978256123048348957342' + ); + for (var i = 0; i < x.bitLength(); ++i) { + assert.equal(x.testn(i), (xbits.charAt(i) === '1'), 'Failed @ bit ' + i); + } + }); + + it('should have short-cuts', function () { + var x = new BN('abcd', 16); + assert(!x.testn(128)); + }); + }); + + describe('.and()', function () { + it('should and numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .and(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .and(new BN('abcd', 16)).toString(16), + 'abcd'); + }); + }); + + describe('.iand()', function () { + it('should iand numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .iand(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + assert.equal(new BN('1000000000000000000000000000000000000001', 2) + .iand(new BN('1', 2)) + .toString(2), '1'); + assert.equal(new BN('1', 2) + .iand(new BN('1000000000000000000000000000000000000001', 2)) + .toString(2), '1'); + }); + }); + + describe('.or()', function () { + it('should or numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .or(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + }); + + it('should or numbers of different limb-length', function () { + assert.equal( + new BN('abcd00000000', 16) + .or(new BN('abcd', 16)).toString(16), + 'abcd0000abcd'); + }); + }); + + describe('.ior()', function () { + it('should ior numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .ior(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + assert.equal(new BN('1000000000000000000000000000000000000000', 2) + .ior(new BN('1', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + assert.equal(new BN('1', 2) + .ior(new BN('1000000000000000000000000000000000000000', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + }); + }); + + describe('.xor()', function () { + it('should xor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .xor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + }); + }); + + describe('.ixor()', function () { + it('should ixor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1', 2)) + .toString(2), '11001100110011001100110011001101'); + assert.equal(new BN('1', 2) + .ixor(new BN('11001100110011001100110011001100', 2)) + .toString(2), '11001100110011001100110011001101'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .xor(new BN('abcd', 16)).toString(16), + 'abcd00005432'); + }); + }); + + describe('.setn()', function () { + it('should allow single bits to be set', function () { + assert.equal(new BN(0).setn(2, true).toString(2), '100'); + assert.equal(new BN(0).setn(27, true).toString(2), + '1000000000000000000000000000'); + assert.equal(new BN(0).setn(63, true).toString(16), + new BN(1).iushln(63).toString(16)); + assert.equal(new BN('1000000000000000000000000001', 2).setn(27, false) + .toString(2), '1'); + assert.equal(new BN('101', 2).setn(2, false).toString(2), '1'); + }); + }); + + describe('.notn()', function () { + it('should allow bitwise negation', function () { + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(32).toString(2), + '11111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(32).toString(2), + '11111111111111111111111111000111'); + assert.equal(new BN('111000111', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111111000111'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/constructor-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/constructor-test.js new file mode 100644 index 0000000..bad412b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/constructor-test.js @@ -0,0 +1,149 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Constructor', function () { + describe('with Smi input', function () { + it('should accept one limb number', function () { + assert.equal(new BN(12345).toString(16), '3039'); + }); + + it('should accept two-limb number', function () { + assert.equal(new BN(0x4123456).toString(16), '4123456'); + }); + + it('should accept 52 bits of precision', function () { + var num = Math.pow(2, 52); + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should accept max safe integer', function () { + var num = Math.pow(2, 53) - 1; + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should not accept an unsafe integer', function () { + var num = Math.pow(2, 53); + + assert.throws(function () { + BN(num, 10); + }); + }); + + it('should accept two-limb LE number', function () { + assert.equal(new BN(0x4123456, null, 'le').toString(16), '56341204'); + }); + }); + + describe('with String input', function () { + it('should accept base-16', function () { + assert.equal(new BN('1A6B765D8CDF', 16).toString(16), '1a6b765d8cdf'); + assert.equal(new BN('1A6B765D8CDF', 16).toString(), '29048849665247'); + }); + + it('should accept base-hex', function () { + assert.equal(new BN('FF', 'hex').toString(), '255'); + }); + + it('should accept base-16 with spaces', function () { + var num = 'a89c e5af8724 c0a23e0e 0ff77500'; + assert.equal(new BN(num, 16).toString(16), num.replace(/ /g, '')); + }); + + it('should accept long base-16', function () { + var num = '123456789abcdef123456789abcdef123456789abcdef'; + assert.equal(new BN(num, 16).toString(16), num); + }); + + it('should accept positive base-10', function () { + assert.equal(new BN('10654321').toString(), '10654321'); + assert.equal(new BN('29048849665247').toString(16), '1a6b765d8cdf'); + }); + + it('should accept negative base-10', function () { + assert.equal(new BN('-29048849665247').toString(16), '-1a6b765d8cdf'); + }); + + it('should accept long base-10', function () { + var num = '10000000000000000'; + assert.equal(new BN(num).toString(10), num); + }); + + it('should accept base-2', function () { + var base2 = '11111111111111111111111111111111111111111111111111111'; + assert.equal(new BN(base2, 2).toString(2), base2); + }); + + it('should accept base-36', function () { + var base36 = 'zzZzzzZzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'; + assert.equal(new BN(base36, 36).toString(36), base36.toLowerCase()); + }); + + it('should not overflow limbs during base-10', function () { + var num = '65820182292848241686198767302293' + + '20890292528855852623664389292032'; + assert(new BN(num).words[0] < 0x4000000); + }); + + it('should accept base-16 LE integer', function () { + assert.equal(new BN('1A6B765D8CDF', 16, 'le').toString(16), + 'df8c5d766b1a'); + }); + }); + + describe('with Array input', function () { + it('should not fail on empty array', function () { + assert.equal(new BN([]).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN([ 1, 2, 3 ]).toString(16), '10203'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toString(16), '1020304'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ]).toString(16), '102030405'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toString(16), + '102030405060708'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray().join(','), '1,2,3,4'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray().join(','), + '1,2,3,4,5,6,7,8'); + }); + + it('should import little endian', function () { + assert.equal(new BN([ 1, 2, 3 ], 10, 'le').toString(16), '30201'); + assert.equal(new BN([ 1, 2, 3, 4 ], 10, 'le').toString(16), '4030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 10, 'le').toString(16), + '504030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ], 'le').toString(16), + '807060504030201'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray('le').join(','), '4,3,2,1'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray('le').join(','), + '8,7,6,5,4,3,2,1'); + }); + + it('should import big endian with implicit base', function () { + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 'le').toString(16), '504030201'); + }); + }); + + // the Array code is able to handle Buffer + describe('with Buffer input', function () { + it('should not fail on empty Buffer', function () { + assert.equal(new BN(new Buffer(0)).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex')).toString(16), '10203'); + }); + + it('should import little endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex'), 'le').toString(16), '30201'); + }); + }); + + describe('with BN input', function () { + it('should clone BN', function () { + var num = new BN(12345); + assert.equal(new BN(num).toString(10), '12345'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/fixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/fixtures.js new file mode 100644 index 0000000..39fd661 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/fixtures.js @@ -0,0 +1,264 @@ +exports.dhGroups = { + p16: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199' + + 'ffffffffffffffff', + priv: '6d5923e6449122cbbcc1b96093e0b7e4fd3e469f58daddae' + + '53b49b20664f4132675df9ce98ae0cfdcac0f4181ccb643b' + + '625f98104dcf6f7d8e81961e2cab4b5014895260cb977c7d' + + '2f981f8532fb5da60b3676dfe57f293f05d525866053ac7e' + + '65abfd19241146e92e64f309a97ef3b529af4d6189fa416c' + + '9e1a816c3bdf88e5edf48fbd8233ef9038bb46faa95122c0' + + '5a426be72039639cd2d53d37254b3d258960dcb33c255ede' + + '20e9d7b4b123c8b4f4b986f53cdd510d042166f7dd7dca98' + + '7c39ab36381ba30a5fdd027eb6128d2ef8e5802a2194d422' + + 'b05fe6e1cb4817789b923d8636c1ec4b7601c90da3ddc178' + + '52f59217ae070d87f2e75cbfb6ff92430ad26a71c8373452' + + 'ae1cc5c93350e2d7b87e0acfeba401aaf518580937bf0b6c' + + '341f8c49165a47e49ce50853989d07171c00f43dcddddf72' + + '94fb9c3f4e1124e98ef656b797ef48974ddcd43a21fa06d0' + + '565ae8ce494747ce9e0ea0166e76eb45279e5c6471db7df8' + + 'cc88764be29666de9c545e72da36da2f7a352fb17bdeb982' + + 'a6dc0193ec4bf00b2e533efd6cd4d46e6fb237b775615576' + + 'dd6c7c7bbc087a25e6909d1ebc6e5b38e5c8472c0fc429c6' + + 'f17da1838cbcd9bbef57c5b5522fd6053e62ba21fe97c826' + + 'd3889d0cc17e5fa00b54d8d9f0f46fb523698af965950f4b' + + '941369e180f0aece3870d9335f2301db251595d173902cad' + + '394eaa6ffef8be6c', + pub: 'd53703b7340bc89bfc47176d351e5cf86d5a18d9662eca3c' + + '9759c83b6ccda8859649a5866524d77f79e501db923416ca' + + '2636243836d3e6df752defc0fb19cc386e3ae48ad647753f' + + 'bf415e2612f8a9fd01efe7aca249589590c7e6a0332630bb' + + '29c5b3501265d720213790556f0f1d114a9e2071be3620bd' + + '4ee1e8bb96689ac9e226f0a4203025f0267adc273a43582b' + + '00b70b490343529eaec4dcff140773cd6654658517f51193' + + '13f21f0a8e04fe7d7b21ffeca85ff8f87c42bb8d9cb13a72' + + 'c00e9c6e9dfcedda0777af951cc8ccab90d35e915e707d8e' + + '4c2aca219547dd78e9a1a0730accdc9ad0b854e51edd1e91' + + '4756760bab156ca6e3cb9c625cf0870def34e9ac2e552800' + + 'd6ce506d43dbbc75acfa0c8d8fb12daa3c783fb726f187d5' + + '58131779239c912d389d0511e0f3a81969d12aeee670e48f' + + 'ba41f7ed9f10705543689c2506b976a8ffabed45e33795b0' + + '1df4f6b993a33d1deab1316a67419afa31fbb6fdd252ee8c' + + '7c7d1d016c44e3fcf6b41898d7f206aa33760b505e4eff2e' + + 'c624bc7fe636b1d59e45d6f904fc391419f13d1f0cdb5b6c' + + '2378b09434159917dde709f8a6b5dc30994d056e3f964371' + + '11587ac7af0a442b8367a7bd940f752ddabf31cf01171e24' + + 'd78df136e9681cd974ce4f858a5fb6efd3234a91857bb52d' + + '9e7b414a8bc66db4b5a73bbeccfb6eb764b4f0cbf0375136' + + 'b024b04e698d54a5' + }, + p17: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934028492' + + '36c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bd' + + 'f8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831' + + '179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1b' + + 'db7f1447e6cc254b332051512bd7af426fb8f401378cd2bf' + + '5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6' + + 'd55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f3' + + '23a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aa' + + 'cc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be328' + + '06a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55c' + + 'da56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee' + + '12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff', + priv: '6017f2bc23e1caff5b0a8b4e1fc72422b5204415787801dc' + + '025762b8dbb98ab57603aaaa27c4e6bdf742b4a1726b9375' + + 'a8ca3cf07771779589831d8bd18ddeb79c43e7e77d433950' + + 'e652e49df35b11fa09644874d71d62fdaffb580816c2c88c' + + '2c4a2eefd4a660360316741b05a15a2e37f236692ad3c463' + + 'fff559938fc6b77176e84e1bb47fb41af691c5eb7bb81bd8' + + 'c918f52625a1128f754b08f5a1403b84667231c4dfe07ed4' + + '326234c113931ce606037e960f35a2dfdec38a5f057884d3' + + '0af8fab3be39c1eeb390205fd65982191fc21d5aa30ddf51' + + 'a8e1c58c0c19fc4b4a7380ea9e836aaf671c90c29bc4bcc7' + + '813811aa436a7a9005de9b507957c56a9caa1351b6efc620' + + '7225a18f6e97f830fb6a8c4f03b82f4611e67ab9497b9271' + + 'd6ac252793cc3e5538990dbd894d2dbc2d152801937d9f74' + + 'da4b741b50b4d40e4c75e2ac163f7b397fd555648b249f97' + + 'ffe58ffb6d096aa84534c4c5729cff137759bd34e80db4ab' + + '47e2b9c52064e7f0bf677f72ac9e5d0c6606943683f9d12f' + + '180cf065a5cb8ec3179a874f358847a907f8471d15f1e728' + + '7023249d6d13c82da52628654438f47b8b5cdf4761fbf6ad' + + '9219eceac657dbd06cf2ab776ad4c968f81c3d039367f0a4' + + 'd77c7ec4435c27b6c147071665100063b5666e06eb2fb2cc' + + '3159ba34bc98ca346342195f6f1fb053ddc3bc1873564d40' + + '1c6738cdf764d6e1ff25ca5926f80102ea6593c17170966b' + + 'b5d7352dd7fb821230237ea3ebed1f920feaadbd21be295a' + + '69f2083deae9c5cdf5f4830eb04b7c1f80cc61c17232d79f' + + '7ecc2cc462a7965f804001c89982734e5abba2d31df1b012' + + '152c6b226dff34510b54be8c2cd68d795def66c57a3abfb6' + + '896f1d139e633417f8c694764974d268f46ece3a8d6616ea' + + 'a592144be48ee1e0a1595d3e5edfede5b27cec6c48ceb2ff' + + 'b42cb44275851b0ebf87dfc9aa2d0cb0805e9454b051dfe8' + + 'a29fadd82491a4b4c23f2d06ba45483ab59976da1433c9ce' + + '500164b957a04cf62dd67595319b512fc4b998424d1164dd' + + 'bbe5d1a0f7257cbb04ec9b5ed92079a1502d98725023ecb2', + pub: '3bf836229c7dd874fe37c1790d201e82ed8e192ed61571ca' + + '7285264974eb2a0171f3747b2fc23969a916cbd21e14f7e2' + + 'f0d72dcd2247affba926f9e7bb99944cb5609aed85e71b89' + + 'e89d2651550cb5bd8281bd3144066af78f194032aa777739' + + 'cccb7862a1af401f99f7e5c693f25ddce2dedd9686633820' + + 'd28d0f5ed0c6b5a094f5fe6170b8e2cbc9dff118398baee6' + + 'e895a6301cb6e881b3cae749a5bdf5c56fc897ff68bc73f2' + + '4811bb108b882872bade1f147d886a415cda2b93dd90190c' + + 'be5c2dd53fe78add5960e97f58ff2506afe437f4cf4c912a' + + '397c1a2139ac6207d3ab76e6b7ffd23bb6866dd7f87a9ae5' + + '578789084ff2d06ea0d30156d7a10496e8ebe094f5703539' + + '730f5fdbebc066de417be82c99c7da59953071f49da7878d' + + 'a588775ff2a7f0084de390f009f372af75cdeba292b08ea8' + + '4bd13a87e1ca678f9ad148145f7cef3620d69a891be46fbb' + + 'cad858e2401ec0fd72abdea2f643e6d0197b7646fbb83220' + + '0f4cf7a7f6a7559f9fb0d0f1680822af9dbd8dec4cd1b5e1' + + '7bc799e902d9fe746ddf41da3b7020350d3600347398999a' + + 'baf75d53e03ad2ee17de8a2032f1008c6c2e6618b62f225b' + + 'a2f350179445debe68500fcbb6cae970a9920e321b468b74' + + '5fb524fb88abbcacdca121d737c44d30724227a99745c209' + + 'b970d1ff93bbc9f28b01b4e714d6c9cbd9ea032d4e964d8e' + + '8fff01db095160c20b7646d9fcd314c4bc11bcc232aeccc0' + + 'fbedccbc786951025597522eef283e3f56b44561a0765783' + + '420128638c257e54b972a76e4261892d81222b3e2039c61a' + + 'ab8408fcaac3d634f848ab3ee65ea1bd13c6cd75d2e78060' + + 'e13cf67fbef8de66d2049e26c0541c679fff3e6afc290efe' + + '875c213df9678e4a7ec484bc87dae5f0a1c26d7583e38941' + + 'b7c68b004d4df8b004b666f9448aac1cc3ea21461f41ea5d' + + 'd0f7a9e6161cfe0f58bcfd304bdc11d78c2e9d542e86c0b5' + + '6985cc83f693f686eaac17411a8247bf62f5ccc7782349b5' + + 'cc1f20e312fa2acc0197154d1bfee507e8db77e8f2732f2d' + + '641440ccf248e8643b2bd1e1f9e8239356ab91098fcb431d', + q: 'a899c59999bf877d96442d284359783bdc64b5f878b688fe' + + '51407f0526e616553ad0aaaac4d5bed3046f10a1faaf42bb' + + '2342dc4b7908eea0c46e4c4576897675c2bfdc4467870d3d' + + 'cd90adaed4359237a4bc6924bfb99aa6bf5f5ede15b574ea' + + 'e977eac096f3c67d09bda574c6306c6123fa89d2f086b8dc' + + 'ff92bc570c18d83fe6c810ccfd22ce4c749ef5e6ead3fffe' + + 'c63d95e0e3fde1df9db6a35fa1d107058f37e41957769199' + + 'd945dd7a373622c65f0af3fd9eb1ddc5c764bbfaf7a3dc37' + + '2548e683b970dac4aa4b9869080d2376c9adecebb84e172c' + + '09aeeb25fb8df23e60033260c4f8aac6b8b98ab894b1fb84' + + 'ebb83c0fb2081c3f3eee07f44e24d8fabf76f19ed167b0d7' + + 'ff971565aa4efa3625fce5a43ceeaa3eebb3ce88a00f597f' + + '048c69292b38dba2103ecdd5ec4ccfe3b2d87fa6202f334b' + + 'c1cab83b608dfc875b650b69f2c7e23c0b2b4adf149a6100' + + 'db1b6dbad4679ecb1ea95eafaba3bd00db11c2134f5a8686' + + '358b8b2ab49a1b2e85e1e45caeac5cd4dc0b3b5fffba8871' + + '1c6baf399edd48dad5e5c313702737a6dbdcede80ca358e5' + + '1d1c4fe42e8948a084403f61baed38aa9a1a5ce2918e9f33' + + '100050a430b47bc592995606440272a4994677577a6aaa1b' + + 'a101045dbec5a4e9566dab5445d1af3ed19519f07ac4e2a8' + + 'bd0a84b01978f203a9125a0be020f71fab56c2c9e344d4f4' + + '12d53d3cd8eb74ca5122002e931e3cb0bd4b7492436be17a' + + 'd7ebe27148671f59432c36d8c56eb762655711cfc8471f70' + + '83a8b7283bcb3b1b1d47d37c23d030288cfcef05fbdb4e16' + + '652ee03ee7b77056a808cd700bc3d9ef826eca9a59be959c' + + '947c865d6b372a1ca2d503d7df6d7611b12111665438475a' + + '1c64145849b3da8c2d343410df892d958db232617f9896f1' + + 'de95b8b5a47132be80dd65298c7f2047858409bf762dbc05' + + 'a62ca392ac40cfb8201a0607a2cae07d99a307625f2b2d04' + + 'fe83fbd3ab53602263410f143b73d5b46fc761882e78c782' + + 'd2c36e716a770a7aefaf7f76cea872db7bffefdbc4c2f9e0' + + '39c19adac915e7a63dcb8c8c78c113f29a3e0bc10e100ce0', + qs: '6f0a2fb763eaeb8eb324d564f03d4a55fdcd709e5f1b65e9' + + '5702b0141182f9f945d71bc3e64a7dfdae7482a7dd5a4e58' + + 'bc38f78de2013f2c468a621f08536969d2c8d011bb3bc259' + + '2124692c91140a5472cad224acdacdeae5751dadfdf068b8' + + '77bfa7374694c6a7be159fc3d24ff9eeeecaf62580427ad8' + + '622d48c51a1c4b1701d768c79d8c819776e096d2694107a2' + + 'f3ec0c32224795b59d32894834039dacb369280afb221bc0' + + '90570a93cf409889b818bb30cccee98b2aa26dbba0f28499' + + '08e1a3cd43fa1f1fb71049e5c77c3724d74dc351d9989057' + + '37bbda3805bd6b1293da8774410fb66e3194e18cdb304dd9' + + 'a0b59b583dcbc9fc045ac9d56aea5cfc9f8a0b95da1e11b7' + + '574d1f976e45fe12294997fac66ca0b83fc056183549e850' + + 'a11413cc4abbe39a211e8c8cbf82f2a23266b3c10ab9e286' + + '07a1b6088909cddff856e1eb6b2cde8bdac53fa939827736' + + 'ca1b892f6c95899613442bd02dbdb747f02487718e2d3f22' + + 'f73734d29767ed8d0e346d0c4098b6fdcb4df7d0c4d29603' + + '5bffe80d6c65ae0a1b814150d349096baaf950f2caf298d2' + + 'b292a1d48cf82b10734fe8cedfa16914076dfe3e9b51337b' + + 'ed28ea1e6824bb717b641ca0e526e175d3e5ed7892aebab0' + + 'f207562cc938a821e2956107c09b6ce4049adddcd0b7505d' + + '49ae6c69a20122461102d465d93dc03db026be54c303613a' + + 'b8e5ce3fd4f65d0b6162ff740a0bf5469ffd442d8c509cd2' + + '3b40dab90f6776ca17fc0678774bd6eee1fa85ababa52ec1' + + 'a15031eb677c6c488661dddd8b83d6031fe294489ded5f08' + + '8ad1689a14baeae7e688afa3033899c81f58de39b392ca94' + + 'af6f15a46f19fa95c06f9493c8b96a9be25e78b9ea35013b' + + 'caa76de6303939299d07426a88a334278fc3d0d9fa71373e' + + 'be51d3c1076ab93a11d3d0d703366ff8cde4c11261d488e5' + + '60a2bdf3bfe2476032294800d6a4a39d306e65c6d7d8d66e' + + '5ec63eee94531e83a9bddc458a2b508285c0ee10b7bd94da' + + '2815a0c5bd5b2e15cbe66355e42f5af8955cdfc0b3a4996d' + + '288db1f4b32b15643b18193e378cb7491f3c3951cdd044b1' + + 'a519571bffac2da986f5f1d506c66530a55f70751e24fa8e' + + 'd83ac2347f4069fb561a5565e78c6f0207da24e889a93a96' + + '65f717d9fe8a2938a09ab5f81be7ccecf466c0397fc15a57' + + '469939793f302739765773c256a3ca55d0548afd117a7cae' + + '98ca7e0d749a130c7b743d376848e255f8fdbe4cb4480b63' + + 'cd2c015d1020cf095d175f3ca9dcdfbaf1b2a6e6468eee4c' + + 'c750f2132a77f376bd9782b9d0ff4da98621b898e251a263' + + '4301ba2214a8c430b2f7a79dbbfd6d7ff6e9b0c137b025ff' + + '587c0bf912f0b19d4fff96b1ecd2ca990c89b386055c60f2' + + '3b94214bd55096f17a7b2c0fa12b333235101cd6f28a128c' + + '782e8a72671adadebbd073ded30bd7f09fb693565dcf0bf3' + + '090c21d13e5b0989dd8956f18f17f4f69449a13549c9d80a' + + '77e5e61b5aeeee9528634100e7bc390672f0ded1ca53555b' + + 'abddbcf700b9da6192255bddf50a76b709fbed251dce4c7e' + + '1ca36b85d1e97c1bc9d38c887a5adf140f9eeef674c31422' + + 'e65f63cae719f8c1324e42fa5fd8500899ef5aa3f9856aa7' + + 'ce10c85600a040343204f36bfeab8cfa6e9deb8a2edd2a8e' + + '018d00c7c9fa3a251ad0f57183c37e6377797653f382ec7a' + + '2b0145e16d3c856bc3634b46d90d7198aff12aff88a30e34' + + 'e2bfaf62705f3382576a9d3eeb0829fca2387b5b654af46e' + + '5cf6316fb57d59e5ea6c369061ac64d99671b0e516529dd5' + + 'd9c48ea0503e55fee090d36c5ea8b5954f6fcc0060794e1c' + + 'b7bc24aa1e5c0142fd4ce6e8fd5aa92a7bf84317ea9e1642' + + 'b6995bac6705adf93cbce72433ed0871139970d640f67b78' + + 'e63a7a6d849db2567df69ac7d79f8c62664ac221df228289' + + 'd0a4f9ebd9acb4f87d49da64e51a619fd3f3baccbd9feb12' + + '5abe0cc2c8d17ed1d8546da2b6c641f4d3020a5f9b9f26ac' + + '16546c2d61385505612275ea344c2bbf1ce890023738f715' + + '5e9eba6a071678c8ebd009c328c3eb643679de86e69a9fa5' + + '67a9e146030ff03d546310a0a568c5ba0070e0da22f2cef8' + + '54714b04d399bbc8fd261f9e8efcd0e83bdbc3f5cfb2d024' + + '3e398478cc598e000124eb8858f9df8f52946c2a1ca5c400' + } +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/pummel/dh-group-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/pummel/dh-group-test.js new file mode 100644 index 0000000..37a259f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/pummel/dh-group-test.js @@ -0,0 +1,23 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../../').BN; +var fixtures = require('../fixtures'); + +describe('BN.js/Slow DH test', function () { + var groups = fixtures.dhGroups; + Object.keys(groups).forEach(function (name) { + it('should match public key for ' + name + ' group', function () { + var group = groups[name]; + + this.timeout(3600 * 1000); + + var base = new BN(2); + var mont = BN.red(new BN(group.prime, 16)); + var priv = new BN(group.priv, 16); + var multed = base.toRed(mont).redPow(priv).fromRed(); + var actual = new Buffer(multed.toArray()); + assert.equal(actual.toString('hex'), group.pub); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/red-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/red-test.js new file mode 100644 index 0000000..5f78b83 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/red-test.js @@ -0,0 +1,249 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Reduction context', function () { + function testMethod (name, fn) { + describe(name + ' method', function () { + it('should support add, iadd, sub, isub operations', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(123).toRed(m); + var b = new BN(231).toRed(m); + + assert.equal(a.redAdd(b).fromRed().toString(10), '97'); + assert.equal(a.redSub(b).fromRed().toString(10), '149'); + assert.equal(b.redSub(a).fromRed().toString(10), '108'); + + assert.equal(a.clone().redIAdd(b).fromRed().toString(10), '97'); + assert.equal(a.clone().redISub(b).fromRed().toString(10), '149'); + assert.equal(b.clone().redISub(a).fromRed().toString(10), '108'); + }); + + it('should support pow and mul operations', function () { + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p192); + var a = new BN(123); + var b = new BN(231); + var c = a.toRed(m).redMul(b.toRed(m)).fromRed(); + assert(c.cmp(a.mul(b).mod(p192)) === 0); + + assert.equal(a.toRed(m).redPow(new BN(3)).fromRed() + .cmp(a.sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(4)).fromRed() + .cmp(a.sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(8)).fromRed() + .cmp(a.sqr().sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(9)).fromRed() + .cmp(a.sqr().sqr().sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(17)).fromRed() + .cmp(a.sqr().sqr().sqr().sqr().mul(a)), 0); + assert.equal( + a.toRed(m).redPow(new BN('deadbeefabbadead', 16)).fromRed() + .toString(16), + '3aa0e7e304e320b68ef61592bcb00341866d6fa66e11a4d6'); + }); + + it('should sqrtm numbers', function () { + var p = new BN(263); + var m = fn(p); + var q = new BN(11).toRed(m); + + var qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + m = fn(p); + + q = new BN(13).toRed(m); + qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + // Tonelli-shanks + p = new BN(13); + m = fn(p); + q = new BN(10).toRed(m); + assert.equal(q.redSqrt().fromRed().toString(10), '7'); + }); + + it('should invm numbers', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(3).toRed(m); + var b = a.redInvm(); + assert.equal(a.redMul(b).fromRed().toString(16), '1'); + }); + + it('should invm numbers (regression)', function () { + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'e1d969b8192fbac73ea5b7921896d6a2263d4d4077bb8e5055361d1f7f8163f3', + 16); + + var m = fn(p); + a = a.toRed(m); + + assert.equal(a.redInvm().fromRed().negative, 0); + }); + + it('should imul numbers', function () { + var p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p); + + var a = new BN('deadbeefabbadead', 16); + var b = new BN('abbadeadbeefdead', 16); + var c = a.mul(b).mod(p); + + assert.equal(a.toRed(m).redIMul(b.toRed(m)).fromRed().toString(16), + c.toString(16)); + }); + + it('should pow(base, 0) == 1', function () { + var base = new BN(256).toRed(BN.red('k256')); + var exponent = new BN(0); + var result = base.redPow(exponent); + assert.equal(result.toString(), '1'); + }); + + it('should shl numbers', function () { + var base = new BN(256).toRed(BN.red('k256')); + var result = base.redShl(1); + assert.equal(result.toString(), '512'); + }); + + it('should reduce when converting to red', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(5).toRed(m); + + assert.doesNotThrow(function () { + var b = a.redISub(new BN(512).toRed(m)); + b.redISub(new BN(512).toRed(m)); + }); + }); + + it('redNeg and zero value', function () { + var a = new BN(0).toRed(BN.red('k256')).redNeg(); + assert.equal(a.isZero(), true); + }); + }); + } + + testMethod('Plain', BN.red); + testMethod('Montgomery', BN.mont); + + describe('Pseudo-Mersenne Primes', function () { + it('should reduce numbers mod k256', function () { + var p = BN._prime('k256'); + + assert.equal(p.ireduce(new BN(0xdead)).toString(16), 'dead'); + assert.equal(p.ireduce(new BN('deadbeef', 16)).toString(16), 'deadbeef'); + + var num = new BN('fedcba9876543210fedcba9876543210dead' + + 'fedcba9876543210fedcba9876543210dead', + 16); + var exp = num.mod(p.p).toString(16); + assert.equal(p.ireduce(num).toString(16), exp); + + var regr = new BN('f7e46df64c1815962bf7bc9c56128798' + + '3f4fcef9cb1979573163b477eab93959' + + '335dfb29ef07a4d835d22aa3b6797760' + + '70a8b8f59ba73d56d01a79af9', + 16); + exp = regr.mod(p.p).toString(16); + + assert.equal(p.ireduce(regr).toString(16), exp); + }); + + it('should not fail to invm number mod k256', function () { + var regr2 = new BN( + '6c150c4aa9a8cf1934485d40674d4a7cd494675537bda36d49405c5d2c6f496f', 16); + regr2 = regr2.toRed(BN.red('k256')); + assert.equal(regr2.redInvm().redMul(regr2).fromRed().cmpn(1), 0); + }); + + it('should correctly square the number', function () { + var p = BN._prime('k256').p; + var red = BN.red('k256'); + + var n = new BN('9cd8cb48c3281596139f147c1364a3ed' + + 'e88d3f310fdb0eb98c924e599ca1b3c9', + 16); + var expected = n.sqr().mod(p); + var actual = n.toRed(red).redSqr().fromRed(); + + assert.equal(actual.toString(16), expected.toString(16)); + }); + + it('redISqr should return right result', function () { + var n = new BN('30f28939', 16); + var actual = n.toRed(BN.red('k256')).redISqr().fromRed(); + assert.equal(actual.toString(16), '95bd93d19520eb1'); + }); + }); + + it('should avoid 4.1.0 regresion', function () { + function bits2int (obits, q) { + var bits = new BN(obits); + var shift = (obits.length << 3) - q.bitLength(); + if (shift > 0) { + bits.ishrn(shift); + } + return bits; + } + var t = new Buffer('aff1651e4cd6036d57aa8b2a05ccf1a9d5a40166340ecbbdc55' + + 'be10b568aa0aa3d05ce9a2fcec9df8ed018e29683c6051cb83e' + + '46ce31ba4edb045356a8d0d80b', 'hex'); + var g = new BN('5c7ff6b06f8f143fe8288433493e4769c4d988ace5be25a0e24809670' + + '716c613d7b0cee6932f8faa7c44d2cb24523da53fbe4f6ec3595892d1' + + 'aa58c4328a06c46a15662e7eaa703a1decf8bbb2d05dbe2eb956c142a' + + '338661d10461c0d135472085057f3494309ffa73c611f78b32adbb574' + + '0c361c9f35be90997db2014e2ef5aa61782f52abeb8bd6432c4dd097b' + + 'c5423b285dafb60dc364e8161f4a2a35aca3a10b1c4d203cc76a470a3' + + '3afdcbdd92959859abd8b56e1725252d78eac66e71ba9ae3f1dd24871' + + '99874393cd4d832186800654760e1e34c09e4d155179f9ec0dc4473f9' + + '96bdce6eed1cabed8b6f116f7ad9cf505df0f998e34ab27514b0ffe7', + 16); + var p = new BN('9db6fb5951b66bb6fe1e140f1d2ce5502374161fd6538df1648218642' + + 'f0b5c48c8f7a41aadfa187324b87674fa1822b00f1ecf8136943d7c55' + + '757264e5a1a44ffe012e9936e00c1d3e9310b01c7d179805d3058b2a9' + + 'f4bb6f9716bfe6117c6b5b3cc4d9be341104ad4a80ad6c94e005f4b99' + + '3e14f091eb51743bf33050c38de235567e1b34c3d6a5c0ceaa1a0f368' + + '213c3d19843d0b4b09dcb9fc72d39c8de41f1bf14d4bb4563ca283716' + + '21cad3324b6a2d392145bebfac748805236f5ca2fe92b871cd8f9c36d' + + '3292b5509ca8caa77a2adfc7bfd77dda6f71125a7456fea153e433256' + + 'a2261c6a06ed3693797e7995fad5aabbcfbe3eda2741e375404ae25b', + 16); + var q = new BN('f2c3119374ce76c9356990b465374a17f23f9ed35089bd969f61c6dde' + + '9998c1f', 16); + var k = bits2int(t, q); + var expectedR = '89ec4bb1400eccff8e7d9aa515cd1de7803f2daff09693ee7fd1353e' + + '90a68307'; + var r = g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); + assert.equal(r.toString(16), expectedR); + }); + + it('K256.split for 512 bits number should return equal numbers', function () { + var red = BN.red('k256'); + var input = new BN(1).iushln(512).subn(1); + assert.equal(input.bitLength(), 512); + var output = new BN(0); + red.prime.split(input, output); + assert.equal(input.cmp(output), 0); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/utils-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/utils-test.js new file mode 100644 index 0000000..f51ce4b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/test/utils-test.js @@ -0,0 +1,345 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Utils', function () { + describe('.toString()', function () { + describe('binary padding', function () { + it('should have a length of 256', function () { + var a = new BN(0); + + assert.equal(a.toString(2, 256).length, 256); + }); + }); + describe('hex padding', function () { + it('should have length of 8 from leading 15', function () { + var a = new BN('ffb9602', 16); + + assert.equal(a.toString('hex', 2).length, 8); + }); + + it('should have length of 8 from leading zero', function () { + var a = new BN('fb9604', 16); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 8 from leading zeros', function () { + var a = new BN(0); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 64 from leading 15', function () { + var a = new BN( + 'ffb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 2).length, 64); + }); + + it('should have length of 64 from leading zero', function () { + var a = new BN( + 'fb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 64).length, 64); + }); + }); + }); + + describe('.isNeg()', function () { + it('should return true for negative numbers', function () { + assert.equal(new BN(-1).isNeg(), true); + assert.equal(new BN(1).isNeg(), false); + assert.equal(new BN(0).isNeg(), false); + assert.equal(new BN('-0', 10).isNeg(), false); + }); + }); + + describe('.isOdd()', function () { + it('should return true for odd numbers', function () { + assert.equal(new BN(0).isOdd(), false); + assert.equal(new BN(1).isOdd(), true); + assert.equal(new BN(2).isOdd(), false); + assert.equal(new BN('-0', 10).isOdd(), false); + assert.equal(new BN('-1', 10).isOdd(), true); + assert.equal(new BN('-2', 10).isOdd(), false); + }); + }); + + describe('.isEven()', function () { + it('should return true for even numbers', function () { + assert.equal(new BN(0).isEven(), true); + assert.equal(new BN(1).isEven(), false); + assert.equal(new BN(2).isEven(), true); + assert.equal(new BN('-0', 10).isEven(), true); + assert.equal(new BN('-1', 10).isEven(), false); + assert.equal(new BN('-2', 10).isEven(), true); + }); + }); + + describe('.isZero()', function () { + it('should return true for zero', function () { + assert.equal(new BN(0).isZero(), true); + assert.equal(new BN(1).isZero(), false); + assert.equal(new BN(0xffffffff).isZero(), false); + }); + }); + + describe('.bitLength()', function () { + it('should return proper bitLength', function () { + assert.equal(new BN(0).bitLength(), 0); + assert.equal(new BN(0x1).bitLength(), 1); + assert.equal(new BN(0x2).bitLength(), 2); + assert.equal(new BN(0x3).bitLength(), 2); + assert.equal(new BN(0x4).bitLength(), 3); + assert.equal(new BN(0x8).bitLength(), 4); + assert.equal(new BN(0x10).bitLength(), 5); + assert.equal(new BN(0x100).bitLength(), 9); + assert.equal(new BN(0x123456).bitLength(), 21); + assert.equal(new BN('123456789', 16).bitLength(), 33); + assert.equal(new BN('8023456789', 16).bitLength(), 40); + }); + }); + + describe('.byteLength()', function () { + it('should return proper byteLength', function () { + assert.equal(new BN(0).byteLength(), 0); + assert.equal(new BN(0x1).byteLength(), 1); + assert.equal(new BN(0x2).byteLength(), 1); + assert.equal(new BN(0x3).byteLength(), 1); + assert.equal(new BN(0x4).byteLength(), 1); + assert.equal(new BN(0x8).byteLength(), 1); + assert.equal(new BN(0x10).byteLength(), 1); + assert.equal(new BN(0x100).byteLength(), 2); + assert.equal(new BN(0x123456).byteLength(), 3); + assert.equal(new BN('123456789', 16).byteLength(), 5); + assert.equal(new BN('8023456789', 16).byteLength(), 5); + }); + }); + + describe('.toArray()', function () { + it('should return [ 0 ] for `0`', function () { + var n = new BN(0); + assert.deepEqual(n.toArray('be'), [ 0 ]); + assert.deepEqual(n.toArray('le'), [ 0 ]); + }); + + it('should zero pad to desired lengths', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toArray('be', 5), [ 0x00, 0x00, 0x12, 0x34, 0x56 ]); + assert.deepEqual(n.toArray('le', 5), [ 0x56, 0x34, 0x12, 0x00, 0x00 ]); + }); + + it('should throw when naturally larger than desired length', function () { + var n = new BN(0x123456); + assert.throws(function () { + n.toArray('be', 2); + }); + }); + }); + + describe('.toBuffer', function () { + it('should return proper Buffer', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toBuffer('be', 5).toString('hex'), '0000123456'); + assert.deepEqual(n.toBuffer('le', 5).toString('hex'), '5634120000'); + }); + }); + + describe('.toNumber()', function () { + it('should return proper Number if below the limit', function () { + assert.deepEqual(new BN(0x123456).toNumber(), 0x123456); + assert.deepEqual(new BN(0x3ffffff).toNumber(), 0x3ffffff); + assert.deepEqual(new BN(0x4000000).toNumber(), 0x4000000); + assert.deepEqual(new BN(0x10000000000000).toNumber(), 0x10000000000000); + assert.deepEqual(new BN(0x10040004004000).toNumber(), 0x10040004004000); + assert.deepEqual(new BN(-0x123456).toNumber(), -0x123456); + assert.deepEqual(new BN(-0x3ffffff).toNumber(), -0x3ffffff); + assert.deepEqual(new BN(-0x4000000).toNumber(), -0x4000000); + assert.deepEqual(new BN(-0x10000000000000).toNumber(), -0x10000000000000); + assert.deepEqual(new BN(-0x10040004004000).toNumber(), -0x10040004004000); + }); + + it('should throw when number exceeds 53 bits', function () { + var n = new BN(1).iushln(54); + assert.throws(function () { + n.toNumber(); + }); + }); + }); + + describe('.zeroBits()', function () { + it('should return proper zeroBits', function () { + assert.equal(new BN(0).zeroBits(), 0); + assert.equal(new BN(0x1).zeroBits(), 0); + assert.equal(new BN(0x2).zeroBits(), 1); + assert.equal(new BN(0x3).zeroBits(), 0); + assert.equal(new BN(0x4).zeroBits(), 2); + assert.equal(new BN(0x8).zeroBits(), 3); + assert.equal(new BN(0x10).zeroBits(), 4); + assert.equal(new BN(0x100).zeroBits(), 8); + assert.equal(new BN(0x1000000).zeroBits(), 24); + assert.equal(new BN(0x123456).zeroBits(), 1); + }); + }); + + describe('.toJSON', function () { + it('should return hex string', function () { + assert.equal(new BN(0x123).toJSON(), '123'); + }); + }); + + describe('.cmpn', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmpn(42), 0); + assert.equal(new BN(42).cmpn(43), -1); + assert.equal(new BN(42).cmpn(41), 1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffe), 0); + assert.equal(new BN(0x3fffffe).cmpn(0x3ffffff), -1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffd), 1); + assert.throws(function () { + new BN(0x3fffffe).cmpn(0x4000000); + }); + assert.equal(new BN(42).cmpn(-42), 1); + assert.equal(new BN(-42).cmpn(42), -1); + assert.equal(new BN(-42).cmpn(-42), 0); + assert.equal(1 / new BN(-42).cmpn(-42), Infinity); + }); + }); + + describe('.cmp', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmp(new BN(42)), 0); + assert.equal(new BN(42).cmp(new BN(43)), -1); + assert.equal(new BN(42).cmp(new BN(41)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffe)), 0); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3ffffff)), -1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffd)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x4000000)), -1); + assert.equal(new BN(42).cmp(new BN(-42)), 1); + assert.equal(new BN(-42).cmp(new BN(42)), -1); + assert.equal(new BN(-42).cmp(new BN(-42)), 0); + assert.equal(1 / new BN(-42).cmp(new BN(-42)), Infinity); + }); + }); + + describe('comparison shorthands', function () { + it('.gtn greater than', function () { + assert.equal(new BN(3).gtn(2), true); + assert.equal(new BN(3).gtn(3), false); + assert.equal(new BN(3).gtn(4), false); + }); + it('.gt greater than', function () { + assert.equal(new BN(3).gt(new BN(2)), true); + assert.equal(new BN(3).gt(new BN(3)), false); + assert.equal(new BN(3).gt(new BN(4)), false); + }); + it('.gten greater than or equal', function () { + assert.equal(new BN(3).gten(3), true); + assert.equal(new BN(3).gten(2), true); + assert.equal(new BN(3).gten(4), false); + }); + it('.gte greater than or equal', function () { + assert.equal(new BN(3).gte(new BN(3)), true); + assert.equal(new BN(3).gte(new BN(2)), true); + assert.equal(new BN(3).gte(new BN(4)), false); + }); + it('.ltn less than', function () { + assert.equal(new BN(2).ltn(3), true); + assert.equal(new BN(2).ltn(2), false); + assert.equal(new BN(2).ltn(1), false); + }); + it('.lt less than', function () { + assert.equal(new BN(2).lt(new BN(3)), true); + assert.equal(new BN(2).lt(new BN(2)), false); + assert.equal(new BN(2).lt(new BN(1)), false); + }); + it('.lten less than or equal', function () { + assert.equal(new BN(3).lten(3), true); + assert.equal(new BN(3).lten(2), false); + assert.equal(new BN(3).lten(4), true); + }); + it('.lte less than or equal', function () { + assert.equal(new BN(3).lte(new BN(3)), true); + assert.equal(new BN(3).lte(new BN(2)), false); + assert.equal(new BN(3).lte(new BN(4)), true); + }); + it('.eqn equal', function () { + assert.equal(new BN(3).eqn(3), true); + assert.equal(new BN(3).eqn(2), false); + assert.equal(new BN(3).eqn(4), false); + }); + it('.eq equal', function () { + assert.equal(new BN(3).eq(new BN(3)), true); + assert.equal(new BN(3).eq(new BN(2)), false); + assert.equal(new BN(3).eq(new BN(4)), false); + }); + }); + + describe('.fromTwos', function () { + it('should convert from two\'s complement to negative number', function () { + assert.equal(new BN('00000000', 16).fromTwos(32).toNumber(), 0); + assert.equal(new BN('00000001', 16).fromTwos(32).toNumber(), 1); + assert.equal(new BN('7fffffff', 16).fromTwos(32).toNumber(), 2147483647); + assert.equal(new BN('80000000', 16).fromTwos(32).toNumber(), -2147483648); + assert.equal(new BN('f0000000', 16).fromTwos(32).toNumber(), -268435456); + assert.equal(new BN('f1234567', 16).fromTwos(32).toNumber(), -249346713); + assert.equal(new BN('ffffffff', 16).fromTwos(32).toNumber(), -1); + assert.equal(new BN('fffffffe', 16).fromTwos(32).toNumber(), -2); + assert.equal(new BN('fffffffffffffffffffffffffffffffe', 16) + .fromTwos(128).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'fffffffffffffffffffffffffffffffe', 16).fromTwos(256).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toNumber(), -1); + assert.equal(new BN('7fffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toString(10), + new BN('5789604461865809771178549250434395392663499' + + '2332820282019728792003956564819967', 10).toString(10)); + assert.equal(new BN('80000000000000000000000000000000' + + '00000000000000000000000000000000', 16).fromTwos(256).toString(10), + new BN('-578960446186580977117854925043439539266349' + + '92332820282019728792003956564819968', 10).toString(10)); + }); + }); + + describe('.toTwos', function () { + it('should convert from negative number to two\'s complement', function () { + assert.equal(new BN(0).toTwos(32).toString(16), '0'); + assert.equal(new BN(1).toTwos(32).toString(16), '1'); + assert.equal(new BN(2147483647).toTwos(32).toString(16), '7fffffff'); + assert.equal(new BN('-2147483648', 10).toTwos(32).toString(16), '80000000'); + assert.equal(new BN('-268435456', 10).toTwos(32).toString(16), 'f0000000'); + assert.equal(new BN('-249346713', 10).toTwos(32).toString(16), 'f1234567'); + assert.equal(new BN('-1', 10).toTwos(32).toString(16), 'ffffffff'); + assert.equal(new BN('-2', 10).toTwos(32).toString(16), 'fffffffe'); + assert.equal(new BN('-2', 10).toTwos(128).toString(16), + 'fffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-2', 10).toTwos(256).toString(16), + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-1', 10).toTwos(256).toString(16), + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('5789604461865809771178549250434395392663' + + '4992332820282019728792003956564819967', 10).toTwos(256).toString(16), + '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('-578960446186580977117854925043439539266' + + '34992332820282019728792003956564819968', 10).toTwos(256).toString(16), + '8000000000000000000000000000000000000000000000000000000000000000'); + }); + }); + + describe('.isBN', function () { + it('should return true for BN', function () { + assert.equal(BN.isBN(new BN()), true); + }); + + it('should return false for everything else', function () { + assert.equal(BN.isBN(1), false); + assert.equal(BN.isBN([]), false); + assert.equal(BN.isBN({}), false); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/util/genCombMulTo.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/util/genCombMulTo.js new file mode 100644 index 0000000..8b456c7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/util/genCombMulTo.js @@ -0,0 +1,65 @@ +'use strict'; + +// NOTE: This could be potentionally used to generate loop-less multiplications +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('var w' + k + ' = c;'); + src.push('c = 0;'); + for (var j = minJ; j <= maxJ; j++) { + i = k - j; + + src.push('lo = Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid = Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;'); + src.push('hi = Math.imul(ah' + i + ', bh' + j + ');'); + + src.push('w' + k + ' = (w' + k + ' + lo) | 0;'); + src.push('w' + k + ' = (w' + k + ' + ((mid & 0x1fff) << 13)) | 0;'); + src.push('c = (c + hi) | 0;'); + src.push('c = (c + (mid >>> 13)) | 0;'); + src.push('c = (c + (w' + k + ' >>> 26)) | 0;'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/util/genCombMulTo10.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/util/genCombMulTo10.js new file mode 100644 index 0000000..4214ffd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/bn.js/util/genCombMulTo10.js @@ -0,0 +1,64 @@ +'use strict'; + +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('lo = Math.imul(al' + (k - minJ) + ', bl' + minJ + ');'); + src.push('mid = Math.imul(al' + (k - minJ) + ', bh' + minJ + ');'); + src.push('mid += Math.imul(ah' + (k - minJ) + ', bl' + minJ + ');'); + src.push('hi = Math.imul(ah' + (k - minJ) + ', bh' + minJ + ');'); + + for (var j = minJ + 1; j <= maxJ; j++) { + i = k - j; + + src.push('lo += Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid += Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid += Math.imul(ah' + i + ', bl' + j + ');'); + src.push('hi += Math.imul(ah' + i + ', bh' + j + ');'); + } + + src.push('var w' + k + ' = c + lo + ((mid & 0x1fff) << 13);'); + src.push('c = hi + (mid >>> 13) + (w' + k + ' >>> 26);'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/.travis.yml new file mode 100644 index 0000000..2022962 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.11" \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/LICENSE new file mode 100644 index 0000000..f6d285c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 Calvin Metcalf & contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/index.js new file mode 100644 index 0000000..2b301cd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/index.js @@ -0,0 +1,40 @@ +var bn = require('bn.js'); +var randomBytes = require('randombytes'); +module.exports = crt; +function blind(priv) { + var r = getr(priv); + var blinder = r.toRed(bn.mont(priv.modulus)) + .redPow(new bn(priv.publicExponent)).fromRed(); + return { + blinder: blinder, + unblinder:r.invm(priv.modulus) + }; +} +function crt(msg, priv) { + var blinds = blind(priv); + var len = priv.modulus.byteLength(); + var mod = bn.mont(priv.modulus); + var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus); + var c1 = blinded.toRed(bn.mont(priv.prime1)); + var c2 = blinded.toRed(bn.mont(priv.prime2)); + var qinv = priv.coefficient; + var p = priv.prime1; + var q = priv.prime2; + var m1 = c1.redPow(priv.exponent1); + var m2 = c2.redPow(priv.exponent2); + m1 = m1.fromRed(); + m2 = m2.fromRed(); + var h = m1.isub(m2).imul(qinv).umod(p); + h.imul(q); + m2.iadd(h); + return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); +} +crt.getr = getr; +function getr(priv) { + var len = priv.modulus.byteLength(); + var r = new bn(randomBytes(len)); + while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) { + r = new bn(randomBytes(len)); + } + return r; +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/package.json new file mode 100644 index 0000000..eeabacd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/package.json @@ -0,0 +1,34 @@ +{ + "name": "browserify-rsa", + "version": "4.0.1", + "description": "RSA for browserify", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "author": "", + "license": "MIT", + "dependencies": { + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/crypto-browserify/browserify-rsa.git" + }, + "devDependencies": { + "parse-asn1": "^5.0.0", + "tap-spec": "^2.1.2", + "tape": "^3.0.3" + }, + "readme": "browserify-rsa\n====\n[![Build Status](https://travis-ci.org/crypto-browserify/browserify-rsa.svg)](https://travis-ci.org/crypto-browserify/browserify-rsa)\n\nRSA private decryption/signing using chinese remainder and blinding.\n\nAPI\n====\n\nGive it a message as a buffer and a private key (as decoded by https://www.npmjs.com/package/parse-asn1) and it returns encrypted data as a buffer.\n", + "readmeFilename": "readme.md", + "bugs": { + "url": "https://github.com/crypto-browserify/browserify-rsa/issues" + }, + "homepage": "https://github.com/crypto-browserify/browserify-rsa#readme", + "_id": "browserify-rsa@4.0.1", + "_shasum": "21e0abfaf6f2029cf2fafb133567a701d4135524", + "_resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "_from": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/readme.md new file mode 100644 index 0000000..370fd95 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/readme.md @@ -0,0 +1,10 @@ +browserify-rsa +==== +[![Build Status](https://travis-ci.org/crypto-browserify/browserify-rsa.svg)](https://travis-ci.org/crypto-browserify/browserify-rsa) + +RSA private decryption/signing using chinese remainder and blinding. + +API +==== + +Give it a message as a buffer and a private key (as decoded by https://www.npmjs.com/package/parse-asn1) and it returns encrypted data as a buffer. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/test.js new file mode 100644 index 0000000..3d79a6d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/browserify-rsa/test.js @@ -0,0 +1,53 @@ +var keys = [ + new Buffer('2d2d2d2d2d424547494e2050524956415445204b45592d2d2d2d2d0a4d494943647749424144414e42676b71686b6947397730424151454641415343416d457767674a6441674541416f4742414b756c55545a3842317163635a38630a44585247535930386757384b764c6c63787878474334675a484e543343425546386e3552344b453330615a79595a2f727473515a7530356a755a4a78614a30710a6d62653735646c5135642b586339424d586551672f4d70545a773554414e374f4964475959704642652b31504c5a367745666a6b59724d714d55636671324c710a68544c64416276424a6e755263595a4c716d42654f51384654724b7241674d4241414543675945416e6b485262455055332f57495353517250333669794362320a532f53425a774b6b7a6d764372427844576850654473777039632f324a593736724e57664c7a793869586755473857557a76486a653631516833676d42634b650a62556154476c34567938486131594241446f3552665272646d3046453474766776752f546b7146717042425a7765753534323835686b357a6c47376e2f4437590a646e4e58557075354d6c4e623578336757306b43515144554c2f2f637763585578592f6576614a50346a53652b5a7745515a6f2b7a58524c695055756c426f560a6177323843564d757864677771416f315831494b65665065556166375251753867434b61526e704775457558416b45417a785a54664d6d766d435544496577340a35476b36624b3236355851576468636769713235346c7042474f596d446a397943453779412b7a6d415351774d73585464514f6931684f434579725875534a350a632b2b4544514a4146683357726e7a6f455042797559584d6d45543874534652574d51357670674e716833686148523562346755433268786169756e43424e4c0a315270565939416f55694479774763472f5350683933436e4b42336e69774a42414b503741747369665a6756587469697a4234614d5468546a565961535a727a0a44304b6739447548796c706b4443686d467537375447724e55516741567559746668622f6252626c56612f4630684a3465514854334a554351425654363874620a4f6752556b30615039744333303231564e383258362b6b6c6f7753514e386f425058382b546644575355696c702f2b6a3234486b792b5a3239446f3779522f520a7175746e4c39324376426c564c56343d0a2d2d2d2d2d454e442050524956415445204b45592d2d2d2d2d0a', 'hex'), + new Buffer('2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a4d4949435641494241414a2f4f77737762466f2f757943386c7447662f794131412b6756354947646e4167506255534933477a624843412b782b544c472f744c0a76625277337231736d7070592f6a6b6b70695657314572534d754e307569787035676237385a39724831587057623557576770335761592f3945484d6a4d644f0a6b512f394c565a7652766c2f4d2f4669366f77502b712b616d4a493142456a454359666268474c33726d6c5664713471586334305177494441514142416e38490a565a3042506f414f68794633334b464d4878793872323866735667784a5559674d334e715167647634664661774359586a684a7a3964755535594a47464a474a0a57554765486c6b7959466c70693466336d377459374a61776d51555742304d4e536f4b48493363674458342f7466424e386e692b634f3065536f5235637a42590a4573414842553437703161774e46414877642b5a457576394834526d4d6e37703237397251547470416b4148334e7173322f7672524632635a554e34664958660a347848735142427955617947713861334a305547615346577636387a54554b466865727239755a6f744e70374e4a346a425869415277307138646f63585547310a416b4148676d4f4b486f4f5274416d696b71706d46454a5a4f7473584d614c43496d3445737a506f356369596f4c4d42635669743039416469516c74375a4a4c0a445930327376553162306167435a39376b446b6d48446b58416b414361384d394a454c7544732f502f76494759446b4d566174494666573662574630326546470a746157774d71436353457357766277307871597433346a5552704e62436a6d4379515677596641772f2b544c68503964416b414677526a64776a77333771706a0a646467316d4e697533376237737746786d6b694d4f585a5278614e4e736662353641313452704e337a6f6233516447557962476f644d494b5446626d552f6c750a436a71417861664a416b41473279663652576277464957664d7974375759436830566147424363677935373441696e566965456f335a5a7946664336332b786d0a33756f614e7934694c6f4a763447436a7155427a335a666356614f2f444457470a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a', 'hex'), + new Buffer('2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a4d4949456a77494241414b422f6779376d6a615767506546645659445a5752434139424e69763370506230657332372b464b593068737a4c614f7734374578430a744157704473483438545841667948425977424c67756179666b344c4749757078622b43474d62526f337845703043626659314a62793236543976476a5243310a666f484444554a4738347561526279487161663469367a74346756522b786c4145496a6b614641414b38634f6f58415431435671474c4c6c6a554363684c38500a6a61486a2f7972695a2f53377264776c49334c6e41427877776d4c726d522f7637315774706d4f2f614e47384e2b31706f2b5177616768546b79513539452f5a0a7641754f6b4657486f6b32712f523650594161326a645a397a696d3046714f502b6e6b5161454452624246426d4271547635664647666b32577341664b662f520a47302f5646642b5a654d353235315465547658483639356e6c53476175566c3941674d42414145436766344c725748592f6c35346f7554685a577676627275670a70667a36734a583267396c3779586d576c455773504543566f2f375355627059467074364f5a7939397a53672b494b624771574b6664686f4b725477495674430a4c30595a304e6c6d646e414e53497a30726f785147375a786b4c352b764853772f506d443978345577662b437a38684154436d4e42763171633630646b7975570a34434c71653732716154695657526f4f316961675167684e634c6f6f36765379363545784c614344545068613779753276773468465a705769456a57346478660a7246644c696978353242433836596c416c784d452f724c6738494a5676696c62796f39615764586d784f6155544c527636506b4644312f6756647738563951720a534c4e39466c4b326b6b6a695830647a6f6962765a7733744d6e74337979644178305838372b734d5256616843316270336b56507a3448793045575834514a2f0a504d33317647697549546b324e43643531445874314c746e324f503546614a536d4361456a6830586b5534716f7559796a585774384275364254436c327675610a466730556a6939432b496b504c6d61554d624d494f7761546b386357714c74685378734c6537304a354f6b477267664b554d2f772b4248483150742f506a7a6a0a432b2b6c306b6946614f5644566141563947704c504c43426f4b2f50433952622f72784d4d6f43434e774a2f4e5a756564496e793277334c4d69693737682f540a7a53766572674e47686a5936526e7661386c4c584a36646c726b6350417970733367577778716a344e5230542b474d3062445550564c62374d303758563753580a7637564a476d35324a625247774d3173732b72385854544e656d65476b2b5752784737546774734d715947584c66423851786b2f66352f4d63633030546c38750a7758464e7366784a786d7436416273547233673336774a2f49684f6e69627a3941642b6e63686c426e4e3351655733434b48717a61523138766f717674566d320a6b4a66484b31357072482f7353476d786d6945476772434a545a78744462614e434f372f56426a6e4b756455554968434177734c747571302f7a7562397641640a384731736366497076357161534e7a6d4b6f5838624f77417276725336775037794b726354737557496c484438724a5649374945446e516f5470354738664b310a68774a2f4d4968384d35763072356455594576366f494a5747636c65364148314a6d73503557496166677137325a32323838704863434648774e59384467394a0a3736517377564c6e556850546c6d6d33454f4f50474574616d32694144357230416679746c62346c624e6f51736a32737a65584f4e4458422b366f7565616a680a564e454c55723848635350356c677a525a6a4a57366146497a6a394c44526d516e55414f6a475358564f517445774a2f4d43515a374e2f763464494b654452410a3864385545785a332b674748756d7a697a7447524a30745172795a483250616b50354937562b316c377145556e4a3263336d462b65317634314570394c4376680a627a72504b773964786831386734622b37624d707357506e7372614b6836697078633761614f615a5630447867657a347a635a753050316f6c4f30634e334b4d0a6e784a305064733352386241684e43446453324a5a61527035513d3d0a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a', 'hex') +]; +var parseKey = require('parse-asn1'); +var privs = keys.map(parseKey); +var crt = require('./'); +var crypto = require('crypto'); +var test = require('tape'); +var constants = require('constants'); +var bn = require('bn.js'); +function testIt(priv, run) { + test('r is coprime with n ' + (run + 1), function (t) { + var len = 30; + t.plan(len); + var i = 0; + while(i++ < len) { + var r = crt.getr(priv); + t.equals(r.gcd(priv.modulus).toString(), '1', 'are coprime run ' + i); + } + }); +} +privs.forEach(testIt); + +function testMessage(key, run) { + var len = 40; + var i = 0; + while (len--) { + test('round trip key ' + (run + 1) + ' run ' + (++i), function (t) { + t.plan(1); + var priv = parseKey(key); + var len = priv.modulus.byteLength(); + var r = new bn(crypto.randomBytes(len)); + while (r.cmp(priv.modulus) >= 0) { + r = new bn(crypto.randomBytes(len)); + } + var buf = new Buffer(r.toArray()); + if (buf.byteLength < priv.modulus.byteLength()) { + var tmp = new Buffer(priv.modulus.byteLength() - buf.byteLength); + tmp.fill(0); + buf = Buffer.concat([tmp, buf]); + } + var nodeEncrypt = crypto.privateDecrypt({ + padding: constants.RSA_NO_PADDING, + key: key + }, buf).toString('hex'); + var myEncrypt = crt(buf, priv).toString('hex'); + t.equals(myEncrypt, nodeEncrypt, 'equal encrypts'); + }); + } +} +keys.forEach(testMessage); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/README.md new file mode 100644 index 0000000..038b709 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/README.md @@ -0,0 +1,170 @@ +# Elliptic [![Build Status](https://secure.travis-ci.org/indutny/elliptic.png)](http://travis-ci.org/indutny/elliptic) [![Coverage Status](https://coveralls.io/repos/indutny/elliptic/badge.svg?branch=master&service=github)](https://coveralls.io/github/indutny/elliptic?branch=master) + +Fast elliptic-curve cryptography in a plain javascript implementation. + +NOTE: Please take a look at http://safecurves.cr.yp.to/ before choosing a curve +for your cryptography operations. + +## Incentive + +ECC is much slower than regular RSA cryptography, the JS implementations are +even more slower. + +## Benchmarks + +```bash +$ node benchmarks/index.js +Benchmarking: sign +elliptic#sign x 262 ops/sec ±0.51% (177 runs sampled) +eccjs#sign x 55.91 ops/sec ±0.90% (144 runs sampled) +------------------------ +Fastest is elliptic#sign +======================== +Benchmarking: verify +elliptic#verify x 113 ops/sec ±0.50% (166 runs sampled) +eccjs#verify x 48.56 ops/sec ±0.36% (125 runs sampled) +------------------------ +Fastest is elliptic#verify +======================== +Benchmarking: gen +elliptic#gen x 294 ops/sec ±0.43% (176 runs sampled) +eccjs#gen x 62.25 ops/sec ±0.63% (129 runs sampled) +------------------------ +Fastest is elliptic#gen +======================== +Benchmarking: ecdh +elliptic#ecdh x 136 ops/sec ±0.85% (156 runs sampled) +------------------------ +Fastest is elliptic#ecdh +======================== +``` + +## API + +### ECDSA + +```javascript +var EC = require('elliptic').ec; + +// Create and initialize EC context +// (better do it once and reuse it) +var ec = new EC('secp256k1'); + +// Generate keys +var key = ec.genKeyPair(); + +// Sign message (must be an array, or it'll be treated as a hex sequence) +var msg = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; +var signature = key.sign(msg); + +// Export DER encoded signature in Array +var derSign = signature.toDER(); + +// Verify signature +console.log(key.verify(msg, derSign)); + +// CHECK WITH NO PRIVATE KEY + +// Public key as '04 + x + y' +var pub = '04bb1fa3...'; + +// Signature MUST be either: +// 1) hex-string of DER-encoded signature; or +// 2) DER-encoded signature as buffer; or +// 3) object with two hex-string properties (r and s) + +var signature = 'b102ac...'; // case 1 +var signature = new Buffer('...'); // case 2 +var signature = { r: 'b1fc...', s: '9c42...' }; // case 3 + +// Import public key +var key = ec.keyFromPublic(pub, 'hex'); + +// Verify signature +console.log(key.verify(msg, signature)); +``` + +### ECDH + +```javascript +// Generate keys +var key1 = ec.genKeyPair(); +var key2 = ec.genKeyPair(); + +var shared1 = key1.derive(key2.getPublic()); +var shared2 = key2.derive(key1.getPublic()); + +console.log('Both shared secrets are BN instances'); +console.log(shared1.toString(16)); +console.log(shared2.toString(16)); +``` + +NOTE: `.derive()` returns a [BN][1] instance. + +## Supported curves + +Elliptic.js support following curve types: + +* Short Weierstrass +* Montgomery +* Edwards +* Twisted Edwards + +Following curve 'presets' are embedded into the library: + +* `secp256k1` +* `p192` +* `p224` +* `p256` +* `p384` +* `p521` +* `curve25519` +* `ed25519` + +NOTE: That `curve25519` could not be used for ECDSA, use `ed25519` instead. + +### Implementation details + +ECDSA is using deterministic `k` value generation as per [RFC6979][0]. Most of +the curve operations are performed on non-affine coordinates (either projective +or extended), various windowing techniques are used for different cases. + +All operations are performed in reduction context using [bn.js][1], hashing is +provided by [hash.js][2] + +### Related projects + +* [eccrypto][3]: isomorphic implementation of ECDSA, ECDH and ECIES for both + browserify and node (uses `elliptic` for browser and [secp256k1-node][4] for + node) + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + +[0]: http://tools.ietf.org/html/rfc6979 +[1]: https://github.com/indutny/bn.js +[2]: https://github.com/indutny/hash.js +[3]: https://github.com/bitchan/eccrypto +[4]: https://github.com/wanderer/secp256k1-node diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js new file mode 100644 index 0000000..2291200 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js @@ -0,0 +1,14 @@ +'use strict'; + +var elliptic = exports; + +elliptic.version = require('../package.json').version; +elliptic.utils = require('./elliptic/utils'); +elliptic.rand = require('brorand'); +elliptic.hmacDRBG = require('./elliptic/hmac-drbg'); +elliptic.curve = require('./elliptic/curve'); +elliptic.curves = require('./elliptic/curves'); + +// Protocols +elliptic.ec = require('./elliptic/ec'); +elliptic.eddsa = require('./elliptic/eddsa'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js new file mode 100644 index 0000000..3f84016 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js @@ -0,0 +1,351 @@ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var getNAF = utils.getNAF; +var getJSF = utils.getJSF; +var assert = utils.assert; + +function BaseCurve(type, conf) { + this.type = type; + this.p = new BN(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); + + // Useful for many curves + this.zero = new BN(0).toRed(this.red); + this.one = new BN(1).toRed(this.red); + this.two = new BN(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); +} +module.exports = BaseCurve; + +BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + for (var j = 0; j < naf.length; j += doubles.step) { + var nafW = 0; + for (var k = j + doubles.step - 1; k >= j; k--) + nafW = (nafW << 1) + naf[k]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (var j = 0; j < repr.length; j++) { + var nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; + +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var k = 0; i >= 0 && naf[i] === 0; i--) + k++; + if (i >= 0) + k++; + acc = acc.dblp(k); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; +}; + +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + for (var i = 0; i < len; i++) { + var p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (var i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a]); + naf[b] = getNAF(coeffs[b], wndWidth[b]); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b] /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3 /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (var j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (var i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (var j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (var j = 0; j < len; j++) { + var z = tmp[j]; + var p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (var i = 0; i < len; i++) + wnd[i] = null; + return acc.toP(); +}; + +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} +BaseCurve.BasePoint = BasePoint; + +BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); +}; + +BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); +}; + +BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + if (bytes[0] === 0x04 && bytes.length - 1 === 2 * len) { + return this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); +}; + +BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); +}; + +BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; +}; + +BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); +}; + +BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; +}; + +BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); +}; + +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles + }; +}; + +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res + }; +}; + +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; + +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js new file mode 100644 index 0000000..a9889d9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js @@ -0,0 +1,410 @@ +'use strict'; + +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var assert = elliptic.utils.assert; + +function EdwardsCurve(conf) { + // NOTE: Important as we are creating point in Base.call() + this.twisted = (conf.a | 0) !== 1; + this.mOneA = this.twisted && (conf.a | 0) === -1; + this.extended = this.mOneA; + + Base.call(this, 'edwards', conf); + + this.a = new BN(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; +} +inherits(EdwardsCurve, Base); +module.exports = EdwardsCurve; + +EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); +}; + +EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); +}; + +// Just for compatibility with Short curve +EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); +}; + +EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN(y, 16); + if (!y.red) + y = y.toRed(this.red); + + // x^2 = (y^2 - 1) / (d y^2 + 1) + var y2 = y.redSqr(); + var lhs = y2.redSub(this.one); + var rhs = y2.redMul(this.d).redAdd(this.one); + var x2 = lhs.redMul(rhs.redInvm()); + + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } + + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + if (x.isOdd() !== odd) + x = x.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); + + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + + return lhs.cmp(rhs) === 0; +}; + +function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } +} +inherits(Point, Base.BasePoint); + +EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + this.y.cmp(this.z) === 0; +}; + +Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + if (this.curve.twisted) { + // E = a * C + var e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + var h = this.z.redSqr(); + // J = F - 2 * H + var j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + var e = c.redAdd(d); + // H = (c * Z1)^2 + var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); + // J = E - 2 * H + var j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); +}; + +Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); +}; + +Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2); +}; + +Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; +}; + +Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); +}; + +Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); +}; + +Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; +}; + +// Compatibility with BaseCurve +Point.prototype.toP = Point.prototype.normalize; +Point.prototype.mixedAdd = Point.prototype.add; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js new file mode 100644 index 0000000..c589281 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var curve = exports; + +curve.base = require('./base'); +curve.short = require('./short'); +curve.mont = require('./mont'); +curve.edwards = require('./edwards'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js new file mode 100644 index 0000000..36207e0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js @@ -0,0 +1,176 @@ +'use strict'; + +var curve = require('../curve'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; + +function MontCurve(conf) { + Base.call(this, 'mont', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.i4 = new BN(4).toRed(this.red).redInvm(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); +} +inherits(MontCurve, Base); +module.exports = MontCurve; + +MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; +}; + +function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } +} +inherits(Point, Base.BasePoint); + +MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); +}; + +MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); +}; + +MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +Point.prototype.precompute = function precompute() { + // No-op +}; + +Point.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); +}; + +Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); +}; + +Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; +}; + +Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; +}; + +Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; +}; + +Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/short.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/short.js new file mode 100644 index 0000000..dfe25d0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/short.js @@ -0,0 +1,909 @@ +'use strict'; + +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var assert = elliptic.utils.assert; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; +}; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + } ]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js new file mode 100644 index 0000000..1d8015b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js @@ -0,0 +1,205 @@ +'use strict'; + +var curves = exports; + +var hash = require('hash.js'); +var elliptic = require('../elliptic'); + +var assert = elliptic.utils.assert; + +function PresetCurve(options) { + if (options.type === 'short') + this.curve = new elliptic.curve.short(options); + else if (options.type === 'edwards') + this.curve = new elliptic.curve.edwards(options); + else + this.curve = new elliptic.curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); +} +curves.PresetCurve = PresetCurve; + +function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); +} + +defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' + ] +}); + +defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' + ] +}); + +defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' + ] +}); + +defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' + ] +}); + +defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650' + ] +}); + +defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '0', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9' + ] +}); + +defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658' + ] +}); + +var pre; +try { + pre = require('./precomputed/secp256k1'); +} catch (e) { + pre = undefined; +} + +defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3' + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15' + } + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre + ] +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/index.js new file mode 100644 index 0000000..aec8ef4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/index.js @@ -0,0 +1,222 @@ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +var KeyPair = require('./key'); +var Signature = require('./signature'); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); + + options = elliptic.curves[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof elliptic.curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash for function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(options) { + return new KeyPair(this, options); +}; + +EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); +}; + +EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair.fromPublic(this, pub, enc); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new elliptic.hmacDRBG({ + hash: this.hash, + pers: options.pers, + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + nonce: this.n.toArray() + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + do { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } while (true); +}; + +EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new elliptic.hmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; true; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } +}; + +EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; +}; + +EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var eNeg = n.sub(e); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + var rInv = signature.r.invm(n); + return this.g.mulAdd(eNeg, r, s).mul(rInv); +}; + +EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js new file mode 100644 index 0000000..8d075fb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js @@ -0,0 +1,107 @@ +'use strict'; + +var BN = require('bn.js'); + +function KeyPair(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; + + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); +} +module.exports = KeyPair; + +KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc + }); +}; + +KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc + }); +}; + +KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; +}; + +KeyPair.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); +}; + +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; +}; + +KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); +}; + +KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); +}; + +// ECDH +KeyPair.prototype.derive = function derive(pub) { + return pub.mul(this.priv).getX(); +}; + +// ECDSA +KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); +}; + +KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); +}; + +KeyPair.prototype.inspect = function inspect() { + return ''; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js new file mode 100644 index 0000000..165b179 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js @@ -0,0 +1,135 @@ +'use strict'; + +var BN = require('bn.js'); + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +function Signature(options, enc) { + if (options instanceof Signature) + return options; + + if (this._importDER(options, enc)) + return; + + assert(options.r && options.s, 'Signature without r or s'); + this.r = new BN(options.r, 16); + this.s = new BN(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; +} +module.exports = Signature; + +function Position() { + this.place = 0; +} + +function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + } + p.place = off; + return val; +} + +function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); +} + +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0 && (r[1] & 0x80)) { + r = r.slice(1); + } + if (s[0] === 0 && (s[1] & 0x80)) { + s = s.slice(1); + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; +}; + +function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); +} + +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/index.js new file mode 100644 index 0000000..b218a16 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/index.js @@ -0,0 +1,118 @@ +'use strict'; + +var hash = require('hash.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var KeyPair = require('./key'); +var Signature = require('./signature'); + +function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + var curve = elliptic.curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; +} + +module.exports = EDDSA; + +/** +* @param {Array|String} message - message bytes +* @param {Array|String|KeyPair} secret - secret bytes or a keypair +* @returns {Signature} - signature +*/ +EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); +}; + +/** +* @param {Array} message - message bytes +* @param {Array|String|Signature} sig - sig bytes +* @param {Array|String|Point|KeyPair} pub - public key +* @returns {Boolean} - true if public key matches sig of message +*/ +EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); +}; + +EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); +}; + +EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); +}; + +EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); +}; + +EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); +}; + +/** +* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 +* +* EDDSA defines methods for encoding and decoding points and integers. These are +* helper convenience methods, that pass along to utility functions implied +* parameters. +* +*/ +EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; +}; + +EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); +}; + +EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); +}; + +EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); +}; + +EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/key.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/key.js new file mode 100644 index 0000000..64dafe0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/key.js @@ -0,0 +1,96 @@ +'use strict'; + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var cachedProperty = utils.cachedProperty; + +/** +* @param {EDDSA} eddsa - instance +* @param {Object} params - public/private key parameters +* +* @param {Array} [params.secret] - secret seed bytes +* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) +* @param {Array} [params.pub] - public key point encoded as bytes +* +*/ +function KeyPair(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); +} + +KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); +}; + +KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); +}; + +KeyPair.prototype.secret = function secret() { + return this._secret; +}; + +cachedProperty(KeyPair, function pubBytes() { + return this.eddsa.encodePoint(this.pub()); +}); + +cachedProperty(KeyPair, function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); +}); + +cachedProperty(KeyPair, function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; +}); + +cachedProperty(KeyPair, function priv() { + return this.eddsa.decodeInt(this.privBytes()); +}); + +cachedProperty(KeyPair, function hash() { + return this.eddsa.hash().update(this.secret()).digest(); +}); + +cachedProperty(KeyPair, function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); +}); + +KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); +}; + +KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); +}; + +KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); +}; + +KeyPair.prototype.getPublic = function getPublic(enc) { + return utils.encode(this.pubBytes(), enc); +}; + +module.exports = KeyPair; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/signature.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/signature.js new file mode 100644 index 0000000..cd5f2b1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/signature.js @@ -0,0 +1,66 @@ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var cachedProperty = utils.cachedProperty; +var parseBytes = utils.parseBytes; + +/** +* @param {EDDSA} eddsa - eddsa instance +* @param {Array|Object} sig - +* @param {Array|Point} [sig.R] - R point as Point or bytes +* @param {Array|bn} [sig.S] - S scalar as bn or bytes +* @param {Array} [sig.Rencoded] - R point encoded +* @param {Array} [sig.Sencoded] - S scalar encoded +*/ +function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength) + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; +} + +cachedProperty(Signature, function S() { + return this.eddsa.decodeInt(this.Sencoded()); +}); + +cachedProperty(Signature, function R() { + return this.eddsa.decodePoint(this.Rencoded()); +}); + +cachedProperty(Signature, function Rencoded() { + return this.eddsa.encodePoint(this.R()); +}); + +cachedProperty(Signature, function Sencoded() { + return this.eddsa.encodeInt(this.S()); +}); + +Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); +}; + +Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); +}; + +module.exports = Signature; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/hmac-drbg.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/hmac-drbg.js new file mode 100644 index 0000000..ff63d2a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/hmac-drbg.js @@ -0,0 +1,114 @@ +'use strict'; + +var hash = require('hash.js'); +var elliptic = require('../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + + this.reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + + var entropy = utils.toArray(options.entropy, options.entropyEnc); + var nonce = utils.toArray(options.nonce, options.nonceEnc); + var pers = utils.toArray(options.pers, options.persEnc); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); +} +module.exports = HmacDRBG; + +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this.reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 +}; + +HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); +}; + +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); +}; + +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toBuffer(entropy, entropyEnc); + add = utils.toBuffer(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this.reseed = 1; +}; + +HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this.reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this.reseed++; + return utils.encode(res, enc); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js new file mode 100644 index 0000000..e4c91e5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js @@ -0,0 +1,780 @@ +module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' + ] + ] + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] + } +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js new file mode 100644 index 0000000..d465d93 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js @@ -0,0 +1,173 @@ +'use strict'; + +var utils = exports; +var BN = require('bn.js'); + +utils.assert = function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +}; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + return res; +} +utils.toArray = toArray; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; + +// Represent num in a w-NAF form +function getNAF(num, w) { + var naf = []; + var ws = 1 << (w + 1); + var k = num.clone(); + while (k.cmpn(1) >= 0) { + var z; + if (k.isOdd()) { + var mod = k.andln(ws - 1); + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + naf.push(z); + + // Optimization, shift by word if possible + var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; + for (var i = 1; i < shift; i++) + naf.push(0); + k.iushrn(shift); + } + + return naf; +} +utils.getNAF = getNAF; + +// Represent k1, k2 in a Joint Sparse Form +function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + var m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + var m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; +} +utils.getJSF = getJSF; + +function cachedProperty(obj, computer) { + var name = computer.name; + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; +} +utils.cachedProperty = cachedProperty; + +function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; +} +utils.parseBytes = parseBytes; + +function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); +} +utils.intFromLE = intFromLE; + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/.npmignore new file mode 100644 index 0000000..1ca9571 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/README.md new file mode 100644 index 0000000..f80437d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/README.md @@ -0,0 +1,26 @@ +# Brorand + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/index.js new file mode 100644 index 0000000..436f040 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/index.js @@ -0,0 +1,57 @@ +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +if (typeof window === 'object') { + if (window.crypto && window.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.crypto.getRandomValues(arr); + return arr; + }; + } else if (window.msCrypto && window.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.msCrypto.getRandomValues(arr); + return arr; + }; + } else { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker + try { + var crypto = require('cry' + 'pto'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + // Emulate crypto API using randy + Rand.prototype._rand = function _rand(n) { + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; + }; + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/package.json new file mode 100644 index 0000000..52d4305 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/package.json @@ -0,0 +1,37 @@ +{ + "name": "brorand", + "version": "1.0.5", + "description": "Random number generator for browsers and node.js", + "main": "index.js", + "scripts": { + "test": "mocha --reporter=spec test/**/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/brorand.git" + }, + "keywords": [ + "Random", + "RNG", + "browser", + "crypto" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/brorand/issues" + }, + "homepage": "https://github.com/indutny/brorand", + "devDependencies": { + "mocha": "^2.0.1" + }, + "readme": "# Brorand\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "brorand@1.0.5", + "_shasum": "07b54ca30286abd1718a0e2a830803efdc9bfa04", + "_resolved": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz", + "_from": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/test/api-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/test/api-test.js new file mode 100644 index 0000000..b6c876d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/brorand/test/api-test.js @@ -0,0 +1,8 @@ +var brorand = require('../'); +var assert = require('assert'); + +describe('Brorand', function() { + it('should generate random numbers', function() { + assert.equal(brorand(100).length, 100); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/.npmignore new file mode 100644 index 0000000..1ca9571 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/.travis.yml new file mode 100644 index 0000000..92a990f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "0.10" + - "0.11" +branches: + only: + - master diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/README.md new file mode 100644 index 0000000..63107cb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/README.md @@ -0,0 +1,28 @@ +# hash.js [![Build Status](https://secure.travis-ci.org/indutny/hash.js.png)](http://travis-ci.org/indutny/hash.js) + +Just a bike-shed. + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash.js new file mode 100644 index 0000000..f59b673 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash.js @@ -0,0 +1,15 @@ +var hash = exports; + +hash.utils = require('./hash/utils'); +hash.common = require('./hash/common'); +hash.sha = require('./hash/sha'); +hash.ripemd = require('./hash/ripemd'); +hash.hmac = require('./hash/hmac'); + +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.sha384 = hash.sha.sha384; +hash.sha512 = hash.sha.sha512; +hash.ripemd160 = hash.ripemd.ripemd160; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/common.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/common.js new file mode 100644 index 0000000..a052c55 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/common.js @@ -0,0 +1,91 @@ +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/hmac.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/hmac.js new file mode 100644 index 0000000..3a3da97 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/hmac.js @@ -0,0 +1,48 @@ +var hmac = exports; + +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (var i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (var i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); +}; + +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/ripemd.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/ripemd.js new file mode 100644 index 0000000..cd55bfc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/ripemd.js @@ -0,0 +1,144 @@ +var hash = require('../hash'); +var utils = hash.utils; + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = hash.common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; + +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/sha.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/sha.js new file mode 100644 index 0000000..a7837aa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/sha.js @@ -0,0 +1,564 @@ +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +var rotr32 = utils.rotr32; +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var rotr64_hi = utils.rotr64_hi; +var rotr64_lo = utils.rotr64_lo; +var shr64_hi = utils.shr64_hi; +var shr64_lo = utils.shr64_lo; +var sum64 = utils.sum64; +var sum64_hi = utils.sum64_hi; +var sum64_lo = utils.sum64_lo; +var sum64_4_hi = utils.sum64_4_hi; +var sum64_4_lo = utils.sum64_4_lo; +var sum64_5_hi = utils.sum64_5_hi; +var sum64_5_lo = utils.sum64_5_lo; +var BlockHash = hash.common.BlockHash; + +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; + +var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash); +exports.sha256 = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; + +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +exports.sha224 = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + +function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); +} +utils.inherits(SHA512, BlockHash); +exports.sha512 = SHA512; + +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; + +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi(c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo(c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } +}; + +SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi(c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo(c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + var c0_hi = s0_512_hi(ah, al); + var c0_lo = s0_512_lo(ah, al); + var c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + var c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); +}; + +SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512.call(this); + this.h = [ 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; +} +utils.inherits(SHA384, SHA512); +exports.sha384 = SHA384; + +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; + +SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); +}; + +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash.call(this); + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); +} + +utils.inherits(SHA1, BlockHash); +exports.sha1 = SHA1; + +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; + +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + + for (var i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; + +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} + +function p32(x, y, z) { + return x ^ y ^ z; +} + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} + +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); +} + +function ch64_hi(xh, xl, yh, yl, zh, zl) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_hi(xh, xl, yh, yl, zh, zl) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/utils.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/utils.js new file mode 100644 index 0000000..00ed5fb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/lib/hash/utils.js @@ -0,0 +1,257 @@ +var utils = exports; +var inherits = require('inherits'); + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +utils.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; +} +utils.htonl = htonl; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; +} +utils.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +utils.zero8 = zero8; + +function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; +} +utils.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +utils.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +utils.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +utils.rotl32 = rotl32; + +function sum32(a, b) { + return (a + b) >>> 0; +} +utils.sum32 = sum32; + +function sum32_3(a, b, c) { + return (a + b + c) >>> 0; +} +utils.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; +} +utils.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; +} +utils.sum32_5 = sum32_5; + +function assert(cond, msg) { + if (!cond) + throw new Error(msg || 'Assertion failed'); +} +utils.assert = assert; + +utils.inherits = inherits; + +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +exports.sum64 = sum64; + +function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +}; +exports.sum64_hi = sum64_hi; + +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +}; +exports.sum64_lo = sum64_lo; + +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +}; +exports.sum64_4_hi = sum64_4_hi; + +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +}; +exports.sum64_4_lo = sum64_4_lo; + +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +}; +exports.sum64_5_hi = sum64_5_hi; + +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; +}; +exports.sum64_5_lo = sum64_5_lo; + +function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; +}; +exports.rotr64_hi = rotr64_hi; + +function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +}; +exports.rotr64_lo = rotr64_lo; + +function shr64_hi(ah, al, num) { + return ah >>> num; +}; +exports.shr64_hi = shr64_hi; + +function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +}; +exports.shr64_lo = shr64_lo; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/package.json new file mode 100644 index 0000000..6d79251 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/package.json @@ -0,0 +1,40 @@ +{ + "name": "hash.js", + "version": "1.0.3", + "description": "Various hash functions that could be run by both browser and node", + "main": "lib/hash.js", + "scripts": { + "test": "mocha --reporter=spec test/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/hash.js.git" + }, + "keywords": [ + "hash", + "sha256", + "sha224", + "hmac" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/hash.js/issues" + }, + "homepage": "https://github.com/indutny/hash.js", + "dependencies": { + "inherits": "^2.0.1" + }, + "devDependencies": { + "mocha": "^1.18.2" + }, + "readme": "# hash.js [![Build Status](https://secure.travis-ci.org/indutny/hash.js.png)](http://travis-ci.org/indutny/hash.js)\n\nJust a bike-shed.\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "hash.js@1.0.3", + "_shasum": "1332ff00156c0a0ffdd8236013d07b77a0451573", + "_resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.0.3.tgz", + "_from": "https://registry.npmjs.org/hash.js/-/hash.js-1.0.3.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/test/hash-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/test/hash-test.js new file mode 100644 index 0000000..97347a2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/test/hash-test.js @@ -0,0 +1,119 @@ +var assert = require('assert'); +var hash = require('../'); + +describe('Hash', function() { + function test(fn, cases) { + for (var i = 0; i < cases.length; i++) { + var msg = cases[i][0]; + var res = cases[i][1]; + var enc = cases[i][2]; + + var dgst = fn().update(msg, enc).digest('hex'); + assert.equal(dgst, res); + + // Split message + var dgst = fn().update(msg.slice(0, 2), enc) + .update(msg.slice(2), enc) + .digest('hex'); + assert.equal(dgst, res); + } + } + + it('should support sha256', function() { + assert.equal(hash.sha256.blockSize, 512); + assert.equal(hash.sha256.outSize, 256); + + test(hash.sha256, [ + [ 'abc', + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad' ], + [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1' ], + [ 'deadbeef', + '5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953', + 'hex' ], + ]); + }); + + it('should support sha224', function() { + assert.equal(hash.sha224.blockSize, 512); + assert.equal(hash.sha224.outSize, 224); + + test(hash.sha224, [ + [ 'abc', + '23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7' ], + [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + '75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525' ], + [ 'deadbeef', + '55b9eee5f60cc362ddc07676f620372611e22272f60fdbec94f243f8', + 'hex' ], + ]); + }); + + it('should support ripemd160', function() { + assert.equal(hash.ripemd160.blockSize, 512); + assert.equal(hash.ripemd160.outSize, 160); + + test(hash.ripemd160, [ + [ '', '9c1185a5c5e9fc54612808977ee8f548b2258d31'], + [ 'abc', + '8eb208f7e05d987a9b044a8e98c6b087f15a0bfc' ], + [ 'message digest', + '5d0689ef49d2fae572b881b123a85ffa21595f36' ], + [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + '12a053384a9c0c88e405a06c27dcf49ada62eb2b' ], + [ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', + 'b0e20b6e3116640286ed3a87a5713079b21f5189' ], + ]); + }); + + it('should support sha1', function() { + assert.equal(hash.sha1.blockSize, 512); + assert.equal(hash.sha1.outSize, 160); + + test(hash.sha1, [ + [ '', + 'da39a3ee5e6b4b0d3255bfef95601890afd80709' ], + [ 'abc', + 'a9993e364706816aba3e25717850c26c9cd0d89d' ], + [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + '84983e441c3bd26ebaae4aa1f95129e5e54670f1' ], + [ 'deadbeef', + 'd78f8bb992a56a597f6c7a1fb918bb78271367eb', + 'hex' ], + ]); + }); + + it('should support sha512', function() { + assert.equal(hash.sha512.blockSize, 1024); + assert.equal(hash.sha512.outSize, 512); + + test(hash.sha512, [ + [ 'abc', + 'ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a' + + '2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f' + ], + [ 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn' + + 'hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', + '8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018' + + '501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909' + ] + ]); + }); + + it('should support sha384', function() { + assert.equal(hash.sha384.blockSize, 1024); + assert.equal(hash.sha384.outSize, 384); + + test(hash.sha384, [ + [ 'abc', + 'cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed' + + '8086072ba1e7cc2358baeca134c825a7' + ], + [ 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn' + + 'hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', + '09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712' + + 'fcc7c71a557e2db966c3e9fa91746039' + ] + ]); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/test/hmac-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/test/hmac-test.js new file mode 100644 index 0000000..0a9647e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/elliptic/node_modules/hash.js/test/hmac-test.js @@ -0,0 +1,59 @@ +var assert = require('assert'); +var hash = require('../'); +var utils = hash.utils; + +describe('Hmac', function() { + describe('mixed test vector', function() { + test({ + name: 'nist 1', + key: '00010203 04050607 08090A0B 0C0D0E0F' + + '10111213 14151617 18191A1B 1C1D1E1F 20212223 24252627' + + '28292A2B 2C2D2E2F 30313233 34353637 38393A3B 3C3D3E3F', + msg: 'Sample message for keylen=blocklen', + res: '8bb9a1db9806f20df7f77b82138c7914d174d59e13dc4d0169c9057b133e1d62' + }); + test({ + name: 'nist 2', + key: '00010203 04050607' + + '08090A0B 0C0D0E0F 10111213 14151617 18191A1B 1C1D1E1F', + msg: 'Sample message for keylen, + lastName: , + age: 28, + gender: 'male', + bio: + [ { time: 922820400000, + description: } ] } +*/ +``` + +### Partial decode + +Its possible to parse data without stopping on first error. In order to do it, +you should call: + +```javascript +var human = Human.decode(output, 'der', { partial: true }); +console.log(human); +/* +{ result: { ... }, + errors: [ ... ] } +*/ +``` + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2013. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1.js new file mode 100644 index 0000000..02bbdc1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1.js @@ -0,0 +1,9 @@ +var asn1 = exports; + +asn1.bignum = require('bn.js'); + +asn1.define = require('./asn1/api').define; +asn1.base = require('./asn1/base'); +asn1.constants = require('./asn1/constants'); +asn1.decoders = require('./asn1/decoders'); +asn1.encoders = require('./asn1/encoders'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/api.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/api.js new file mode 100644 index 0000000..0e8a201 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/api.js @@ -0,0 +1,59 @@ +var asn1 = require('../asn1'); +var inherits = require('inherits'); + +var api = exports; + +api.define = function define(name, body) { + return new Entity(name, body); +}; + +function Entity(name, body) { + this.name = name; + this.body = body; + + this.decoders = {}; + this.encoders = {}; +}; + +Entity.prototype._createNamed = function createNamed(base) { + var named; + try { + named = require('vm').runInThisContext( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; + } + inherits(named, base); + named.prototype._initNamed = function initnamed(entity) { + base.call(this, entity); + }; + + return new named(this); +}; + +Entity.prototype._getDecoder = function _getDecoder(enc) { + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(asn1.decoders[enc]); + return this.decoders[enc]; +}; + +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; + +Entity.prototype._getEncoder = function _getEncoder(enc) { + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(asn1.encoders[enc]); + return this.encoders[enc]; +}; + +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/buffer.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/buffer.js new file mode 100644 index 0000000..bc826e8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/buffer.js @@ -0,0 +1,116 @@ +var inherits = require('inherits'); +var Reporter = require('../base').Reporter; +var Buffer = require('buffer').Buffer; + +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } + + this.base = base; + this.offset = 0; + this.length = base.length; +} +inherits(DecoderBuffer, Reporter); +exports.DecoderBuffer = DecoderBuffer; + +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; +}; + +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); + + return res; +}; + +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; + +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +} + +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + + var res = new DecoderBuffer(this.base); + + // Share reporter state + res._reporterState = this._reporterState; + + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +} + +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } +} +exports.EncoderBuffer = EncoderBuffer; + +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; + + if (this.length === 0) + return out; + + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } + + return out; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/index.js new file mode 100644 index 0000000..935abde --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/index.js @@ -0,0 +1,6 @@ +var base = exports; + +base.Reporter = require('./reporter').Reporter; +base.DecoderBuffer = require('./buffer').DecoderBuffer; +base.EncoderBuffer = require('./buffer').EncoderBuffer; +base.Node = require('./node'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/node.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/node.js new file mode 100644 index 0000000..0c196e8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/node.js @@ -0,0 +1,621 @@ +var Reporter = require('../base').Reporter; +var EncoderBuffer = require('../base').EncoderBuffer; +var DecoderBuffer = require('../base').DecoderBuffer; +var assert = require('minimalistic-assert'); + +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +]; + +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); + +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + var state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + var state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(newKey) { + var state = this._baseState; + + assert(state.key === null); + state.key = newKey; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +Node.prototype.contains = function contains(item) { + var state = this._baseState; + + assert(state.use === null); + state.contains = item; + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input)); + + var result = state['default']; + var present = true; + + var prevKey; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + var tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input); + else + this._decodeChoice(input); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + + if (input.isError(present)) + return present; + } + } + + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input); + else + result = this._decodeChoice(input); + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input); + }); + } + + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj)._decode(data); + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input) { + var state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0]); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1]); + else if (tag === 'objid') + return this._decodeObjid(input, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag); + else if (tag === 'null_') + return this._decodeNull(input); + else if (tag === 'bool') + return this._decodeBool(input); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0]); + else if (state.use !== null) + return this._getUse(state.use, input._reporterState.obj)._decode(input); + else + return input.error('unknown tag: ' + tag); + + return null; +}; + +Node.prototype._getUse = function _getUse(entity, obj) { + + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; + + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; + + if (this._skipDefault(result, reporter, parent)) + return; + + return result; +}; + +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + var result = null; + var present = true; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; + } + + // For error reporting + var prevKey; + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be ommited only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else + throw new Error('Unsupported tag: ' + tag); +}; + +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; + +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/reporter.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/reporter.js new file mode 100644 index 0000000..e0a8e89 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/reporter.js @@ -0,0 +1,102 @@ +var inherits = require('inherits'); + +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.Reporter = Reporter; + +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; + +Reporter.prototype.save = function save() { + var state = this._reporterState; + + return { obj: state.obj, pathLen: state.path.length }; +}; + +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; + + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; + +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; + +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; + + state.path = state.path.slice(0, index - 1); + if (state.obj !== null) + state.obj[key] = value; +}; + +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + + var prev = state.obj; + state.obj = {}; + return prev; +}; + +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; + + var now = state.obj; + state.obj = prev; + return now; +}; + +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } + + if (!state.options.partial) + throw err; + + if (!inherited) + state.errors.push(err); + + return err; +}; + +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; + + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; + +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + Error.captureStackTrace(this, ReporterError); + + return this; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/der.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/der.js new file mode 100644 index 0000000..907dd39 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/der.js @@ -0,0 +1,42 @@ +var constants = require('../constants'); + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/index.js new file mode 100644 index 0000000..c44e325 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/index.js @@ -0,0 +1,19 @@ +var constants = exports; + +// Helper +constants._reverse = function reverse(map) { + var res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + var value = map[key]; + res[value] = key; + }); + + return res; +}; + +constants.der = require('./der'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/der.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/der.js new file mode 100644 index 0000000..92d892d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/der.js @@ -0,0 +1,321 @@ +var inherits = require('inherits'); + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; + + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + var state = buffer.save(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + var res = decoder.decode(buffer, 'der'); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); + + var str = ''; + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); + + if (values) + res = values[res.toString(10)] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + var num = len & 0x7f; + if (num >= 4) + return buf.error('length octect is too long'); + + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/index.js new file mode 100644 index 0000000..e2583aa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/index.js @@ -0,0 +1,4 @@ +var decoders = exports; + +decoders.der = require('./der'); +decoders.pem = require('./pem'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/pem.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/pem.js new file mode 100644 index 0000000..a7d5225 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/pem.js @@ -0,0 +1,50 @@ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var DERDecoder = require('./der'); + +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; + +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); + + var label = options.label.toUpperCase(); + + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); + + var base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9\+\/=]+/gi, ''); + + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/der.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/der.js new file mode 100644 index 0000000..fb0b39f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/der.js @@ -0,0 +1,294 @@ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = new Buffer(numArray); + } + + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(new Buffer(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; + + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/index.js new file mode 100644 index 0000000..6a5d29e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/index.js @@ -0,0 +1,4 @@ +var encoders = exports; + +encoders.der = require('./der'); +encoders.pem = require('./pem'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/pem.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/pem.js new file mode 100644 index 0000000..40298b8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/pem.js @@ -0,0 +1,23 @@ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var DEREncoder = require('./der'); + +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; + +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); + + var p = buf.toString('base64'); + var out = [ '-----BEGIN ' + options.label + '-----' ]; + for (var i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/index.js new file mode 100644 index 0000000..70b4ea5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/index.js @@ -0,0 +1,11 @@ +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/package.json new file mode 100644 index 0000000..bd3bd47 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/package.json @@ -0,0 +1,25 @@ +{ + "name": "minimalistic-assert", + "version": "1.0.0", + "description": "minimalistic-assert ===", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/calvinmetcalf/minimalistic-assert.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/calvinmetcalf/minimalistic-assert/issues" + }, + "homepage": "https://github.com/calvinmetcalf/minimalistic-assert", + "readme": "minimalistic-assert\n===\n\nvery minimalistic assert module.\n", + "readmeFilename": "readme.md", + "_id": "minimalistic-assert@1.0.0", + "_shasum": "702be2dda6b37f4836bcb3f5db56641b64a1d3d3", + "_resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz", + "_from": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/readme.md new file mode 100644 index 0000000..2ca0d25 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/readme.md @@ -0,0 +1,4 @@ +minimalistic-assert +=== + +very minimalistic assert module. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/package.json new file mode 100644 index 0000000..31bec4b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/package.json @@ -0,0 +1,39 @@ +{ + "name": "asn1.js", + "version": "4.5.2", + "description": "ASN.1 encoder and decoder", + "main": "lib/asn1.js", + "scripts": { + "test": "mocha --reporter spec test/*-test.js rfc/2560/test/*-test.js rfc/5280/test/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/asn1.js.git" + }, + "keywords": [ + "asn.1", + "der" + ], + "author": { + "name": "Fedor Indutny" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/asn1.js/issues" + }, + "homepage": "https://github.com/indutny/asn1.js", + "devDependencies": { + "mocha": "^2.3.4" + }, + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + }, + "readme": "# ASN1.js\n\nASN.1 DER Encoder/Decoder and DSL.\n\n## Example\n\nDefine model:\n\n```javascript\nvar asn = require('asn1.js');\n\nvar Human = asn.define('Human', function() {\n this.seq().obj(\n this.key('firstName').octstr(),\n this.key('lastName').octstr(),\n this.key('age').int(),\n this.key('gender').enum({ 0: 'male', 1: 'female' }),\n this.key('bio').seqof(Bio)\n );\n});\n\nvar Bio = asn.define('Bio', function() {\n this.seq().obj(\n this.key('time').gentime(),\n this.key('description').octstr()\n );\n});\n```\n\nEncode data:\n\n```javascript\nvar output = Human.encode({\n firstName: 'Thomas',\n lastName: 'Anderson',\n age: 28,\n gender: 'male',\n bio: [\n {\n time: +new Date('31 March 1999'),\n description: 'freedom of mind'\n }\n ]\n}, 'der');\n```\n\nDecode data:\n\n```javascript\nvar human = Human.decode(output, 'der');\nconsole.log(human);\n/*\n{ firstName: ,\n lastName: ,\n age: 28,\n gender: 'male',\n bio:\n [ { time: 922820400000,\n description: } ] }\n*/\n```\n\n### Partial decode\n\nIts possible to parse data without stopping on first error. In order to do it,\nyou should call:\n\n```javascript\nvar human = Human.decode(output, 'der', { partial: true });\nconsole.log(human);\n/*\n{ result: { ... },\n errors: [ ... ] }\n*/\n```\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2013.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "asn1.js@4.5.2", + "_shasum": "17492bdfd4bb5f1d7e56ab6b085297fee9e640e9", + "_resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.5.2.tgz", + "_from": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.5.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/index.js new file mode 100644 index 0000000..fc40c1c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/index.js @@ -0,0 +1,149 @@ +try { + var asn1 = require('asn1.js'); + var rfc5280 = require('asn1.js-rfc5280'); +} catch (e) { + var asn1 = require('../' + '..'); + var rfc5280 = require('../' + '5280'); +} + +var OCSPRequest = asn1.define('OCSPRequest', function() { + this.seq().obj( + this.key('tbsRequest').use(TBSRequest), + this.key('optionalSignature').optional().explicit(0).use(Signature) + ); +}); +exports.OCSPRequest = OCSPRequest; + +var TBSRequest = asn1.define('TBSRequest', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).use(rfc5280.Version), + this.key('requestorName').optional().explicit(1).use(rfc5280.GeneralName), + this.key('requestList').seqof(Request), + this.key('requestExtensions').optional().explicit(2).use(rfc5280.Extensions) + ); +}); +exports.TBSRequest = TBSRequest; + +var Signature = asn1.define('Signature', function() { + this.seq().obj( + this.key('signatureAlgorithm').use(rfc5280.AlgorithmIdentifier), + this.key('signature').bitstr(), + this.key('certs').optional().explicit(0).seqof(rfc5280.Certificate) + ); +}); +exports.Signature = Signature; + +var Request = asn1.define('Request', function() { + this.seq().obj( + this.key('reqCert').use(CertID), + this.key('singleRequestExtensions').optional().explicit(0).use( + rfc5280.Extensions) + ); +}); +exports.Request = Request; + +var OCSPResponse = asn1.define('OCSPResponse', function() { + this.seq().obj( + this.key('responseStatus').use(ResponseStatus), + this.key('responseBytes').optional().explicit(0).seq().obj( + this.key('responseType').objid({ + '1 3 6 1 5 5 7 48 1 1': 'id-pkix-ocsp-basic' + }), + this.key('response').octstr() + ) + ); +}); +exports.OCSPResponse = OCSPResponse; + +var ResponseStatus = asn1.define('ResponseStatus', function() { + this.enum({ + 0: 'successful', + 1: 'malformed_request', + 2: 'internal_error', + 3: 'try_later', + 5: 'sig_required', + 6: 'unauthorized' + }); +}); +exports.ResponseStatus = ResponseStatus; + +var BasicOCSPResponse = asn1.define('BasicOCSPResponse', function() { + this.seq().obj( + this.key('tbsResponseData').use(ResponseData), + this.key('signatureAlgorithm').use(rfc5280.AlgorithmIdentifier), + this.key('signature').bitstr(), + this.key('certs').optional().explicit(0).seqof(rfc5280.Certificate) + ); +}); +exports.BasicOCSPResponse = BasicOCSPResponse; + +var ResponseData = asn1.define('ResponseData', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).use(rfc5280.Version), + this.key('responderID').use(ResponderID), + this.key('producedAt').gentime(), + this.key('responses').seqof(SingleResponse), + this.key('responseExtensions').optional().explicit(0) + .use(rfc5280.Extensions) + ); +}); +exports.ResponseData = ResponseData; + +var ResponderID = asn1.define('ResponderId', function() { + this.choice({ + byName: this.explicit(1).use(rfc5280.Name), + byKey: this.explicit(2).use(KeyHash) + }); +}); +exports.ResponderID = ResponderID; + +var KeyHash = asn1.define('KeyHash', function() { + this.octstr(); +}); +exports.KeyHash = KeyHash; + +var SingleResponse = asn1.define('SingleResponse', function() { + this.seq().obj( + this.key('certId').use(CertID), + this.key('certStatus').use(CertStatus), + this.key('thisUpdate').gentime(), + this.key('nextUpdate').optional().explicit(0).gentime(), + this.key('singleExtensions').optional().explicit(1).use(rfc5280.Extensions) + ); +}); +exports.SingleResponse = SingleResponse; + +var CertStatus = asn1.define('CertStatus', function() { + this.choice({ + good: this.implicit(0).null_(), + revoked: this.implicit(1).use(RevokedInfo), + unknown: this.implicit(2).null_() + }); +}); +exports.CertStatus = CertStatus; + +var RevokedInfo = asn1.define('RevokedInfo', function() { + this.seq().obj( + this.key('revocationTime').gentime(), + this.key('revocationReason').optional().explicit(0).use(rfc5280.CRLReason) + ); +}); +exports.RevokedInfo = RevokedInfo; + +var CertID = asn1.define('CertID', function() { + this.seq().obj( + this.key('hashAlgorithm').use(rfc5280.AlgorithmIdentifier), + this.key('issuerNameHash').octstr(), + this.key('issuerKeyHash').octstr(), + this.key('serialNumber').use(rfc5280.CertificateSerialNumber) + ); +}); +exports.CertID = CertID; + +var Nonce = asn1.define('Nonce', function() { + this.octstr(); +}); +exports.Nonce = Nonce; + +exports['id-pkix-ocsp'] = [ 1, 3, 6, 1, 5, 5, 7, 48, 1 ]; +exports['id-pkix-ocsp-nonce'] = [ 1, 3, 6, 1, 5, 5, 7, 48, 1, 2 ]; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/package.json new file mode 100644 index 0000000..68ce12f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/package.json @@ -0,0 +1,27 @@ +{ + "name": "asn1.js-rfc2560", + "version": "4.0.0", + "description": "RFC2560 structures for asn1.js", + "main": "index.js", + "repository": { + "type": "git", + "url": "git@github.com:indutny/asn1.js" + }, + "keywords": [ + "asn1", + "rfc2560", + "der" + ], + "author": "Fedor Indutny", + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/asn1.js/issues" + }, + "homepage": "https://github.com/indutny/asn1.js", + "dependencies": { + "asn1.js-rfc5280": "^4.4.0" + }, + "peerDependencies": { + "asn1.js": "^4.4.0" + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/test/basic-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/test/basic-test.js new file mode 100644 index 0000000..b8a6005 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/test/basic-test.js @@ -0,0 +1,50 @@ +var assert = require('assert'); +var rfc2560 = require('..'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js RFC2560', function() { + it('should decode OCSP response', function() { + var data = new Buffer( + '308201d40a0100a08201cd308201c906092b0601050507300101048201ba308201b630' + + '819fa216041499e4405f6b145e3e05d9ddd36354fc62b8f700ac180f32303133313133' + + '303037343531305a30743072304a300906052b0e03021a050004140226ee2f5fa28108' + + '34dacc3380e680ace827f604041499e4405f6b145e3e05d9ddd36354fc62b8f700ac02' + + '1100bb4f9a31232b1ba52a0b77af481800588000180f32303133313133303037343531' + + '305aa011180f32303133313230343037343531305a300d06092a864886f70d01010505' + + '00038201010027813333c9b46845dfe3d0cb6b19c03929cdfc9181c1ce823929bb911a' + + 'd9de05721790fcccbab43f9fbdec1217ab8023156d07bbcc3555f25e9e472fbbb5e019' + + '2835efcdc71b3dbc5e5c4c5939fc7a610fc6521d4ed7d2b685a812fa1a3a129ea87873' + + '972be3be54618ba4a4d96090d7f9aaa5f70d4f07cf5cf3611d8a7b3adafe0b319459ed' + + '40d456773d5f45f04c773711d86cc41d274f771a31c10d30cd6f846b587524bfab2445' + + '4bbb4535cff46f6b341e50f26a242dd78e246c8dea0e2fabcac9582e000c138766f536' + + 'd7f7bab81247c294454e62b710b07126de4e09685818f694df5783eb66f384ce5977f1' + + '2721ff38c709f3ec580d22ff40818dd17f', + 'hex'); + + var res = rfc2560.OCSPResponse.decode(data, 'der'); + assert.equal(res.responseStatus, 'successful'); + assert.equal(res.responseBytes.responseType, 'id-pkix-ocsp-basic'); + + var basic = rfc2560.BasicOCSPResponse.decode( + res.responseBytes.response, + 'der' + ); + assert.equal(basic.tbsResponseData.version, 'v1'); + assert.equal(basic.tbsResponseData.producedAt, 1385797510000); + }); + + it('should encode/decode OCSP response', function() { + var encoded = rfc2560.OCSPResponse.encode({ + responseStatus: 'malformed_request', + responseBytes: { + responseType: 'id-pkix-ocsp-basic', + response: 'random-string' + } + }, 'der'); + var decoded = rfc2560.OCSPResponse.decode(encoded, 'der'); + assert.equal(decoded.responseStatus, 'malformed_request'); + assert.equal(decoded.responseBytes.responseType, 'id-pkix-ocsp-basic'); + assert.equal(decoded.responseBytes.response.toString(), 'random-string'); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/index.js new file mode 100644 index 0000000..edbc019 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/index.js @@ -0,0 +1,878 @@ +try { + var asn1 = require('asn1.js'); +} catch (e) { + var asn1 = require('../..'); +} + +/** + * RFC5280 X509 and Extension Definitions + */ + +var rfc5280 = exports; + +// OIDs +var x509OIDs = { + '2 5 29 9': 'subjectDirectoryAttributes', + '2 5 29 14': 'subjectKeyIdentifier', + '2 5 29 15': 'keyUsage', + '2 5 29 17': 'subjectAlternativeName', + '2 5 29 18': 'issuerAlternativeName', + '2 5 29 19': 'basicConstraints', + '2 5 29 20': 'cRLNumber', + '2 5 29 21': 'reasonCode', + '2 5 29 24': 'invalidityDate', + '2 5 29 27': 'deltaCRLIndicator', + '2 5 29 28': 'issuingDistributionPoint', + '2 5 29 29': 'certificateIssuer', + '2 5 29 30': 'nameConstraints', + '2 5 29 31': 'cRLDistributionPoints', + '2 5 29 32': 'certificatePolicies', + '2 5 29 33': 'policyMappings', + '2 5 29 35': 'authorityKeyIdentifier', + '2 5 29 36': 'policyConstraints', + '2 5 29 37': 'extendedKeyUsage', + '2 5 29 46': 'freshestCRL', + '2 5 29 54': 'inhibitAnyPolicy', + '1 3 6 1 5 5 7 1 1': 'authorityInformationAccess', + '1 3 6 1 5 5 7 11': 'subjectInformationAccess' +}; + +// CertificateList ::= SEQUENCE { +// tbsCertList TBSCertList, +// signatureAlgorithm AlgorithmIdentifier, +// signature BIT STRING } +var CertificateList = asn1.define('CertificateList', function() { + this.seq().obj( + this.key('tbsCertList').use(TBSCertList), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signature').bitstr() + ); +}); +rfc5280.CerficateList = CertificateList; + +// AlgorithmIdentifier ::= SEQUENCE { +// algorithm OBJECT IDENTIFIER, +// parameters ANY DEFINED BY algorithm OPTIONAL } +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function() { + this.seq().obj( + this.key('algorithm').objid(), + this.key('parameters').optional().any() + ); +}); +rfc5280.AlgorithmIdentifier = AlgorithmIdentifier; + +// Certificate ::= SEQUENCE { +// tbsCertificate TBSCertificate, +// signatureAlgorithm AlgorithmIdentifier, +// signature BIT STRING } +var Certificate = asn1.define('Certificate', function() { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signature').bitstr() + ); +}); +rfc5280.Certificate = Certificate; + +// TBSCertificate ::= SEQUENCE { +// version [0] Version DEFAULT v1, +// serialNumber CertificateSerialNumber, +// signature AlgorithmIdentifier, +// issuer Name, +// validity Validity, +// subject Name, +// subjectPublicKeyInfo SubjectPublicKeyInfo, +// issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, +// subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, +// extensions [3] Extensions OPTIONAL +var TBSCertificate = asn1.define('TBSCertificate', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).use(Version), + this.key('serialNumber').int(), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').optional().explicit(1).bitstr(), + this.key('subjectUniqueID').optional().explicit(2).bitstr(), + this.key('extensions').optional().explicit(3).seqof(Extension) + ); +}); +rfc5280.TBSCertificate = TBSCertificate; + +// Version ::= INTEGER { v1(0), v2(1), v3(2) } +var Version = asn1.define('Version', function() { + this.int({ + 0: 'v1', + 1: 'v2', + 2: 'v3' + }); +}); +rfc5280.Version = Version; + +// Validity ::= SEQUENCE { +// notBefore Time, +// notAfter Time } +var Validity = asn1.define('Validity', function() { + this.seq().obj( + this.key('notBefore').use(Time), + this.key('notAfter').use(Time) + ); +}); +rfc5280.Validity = Validity; + +// Time ::= CHOICE { +// utcTime UTCTime, +// generalTime GeneralizedTime } +var Time = asn1.define('Time', function() { + this.choice({ + utcTime: this.utctime(), + genTime: this.gentime() + }); +}); +rfc5280.Time = Time; + +// SubjectPublicKeyInfo ::= SEQUENCE { +// algorithm AlgorithmIdentifier, +// subjectPublicKey BIT STRING } +var SubjectPublicKeyInfo = asn1.define('SubjectPublicKeyInfo', function() { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); +rfc5280.SubjectPublicKeyInfo = SubjectPublicKeyInfo; + +// TBSCertList ::= SEQUENCE { +// version Version OPTIONAL, +// signature AlgorithmIdentifier, +// issuer Name, +// thisUpdate Time, +// nextUpdate Time OPTIONAL, +// revokedCertificates SEQUENCE OF SEQUENCE { +// userCertificate CertificateSerialNumber, +// revocationDate Time, +// crlEntryExtensions Extensions OPTIONAL +// } OPTIONAL, +// crlExtensions [0] Extensions OPTIONAL } +var TBSCertList = asn1.define('TBSCertList', function() { + this.seq().obj( + this.key('version').optional().int(), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('thisUpdate').use(Time), + this.key('nextUpdate').use(Time), + this.key('revokedCertificates').optional().seq().obj( + this.seq().obj( + this.key('userCertificate').int(), + this.key('revocationDate').use(Time), + this.key('crlEntryExtensions').optional().seqof(Extension) + ) + ), + this.key('crlExtensions').implicit(0).optional().seqof(Extension) + ); +}); +rfc5280.TBSCertList = TBSCertList; + +// Extension ::= SEQUENCE { +// extnID OBJECT IDENTIFIER, +// critical BOOLEAN DEFAULT FALSE, +// extnValue OCTET STRING } +var Extension = asn1.define('Extension', function() { + this.seq().obj( + this.key('extnID').objid(x509OIDs), + this.key('critical').bool().def(false), + this.key('extnValue').octstr().contains(function(obj) { + var out = x509Extensions[obj.extnID]; + // Cope with unknown extensions + return out ? out : asn1.define('OctString', function() { this.any() }) + }) + ); +}); +rfc5280.Extension = Extension; + +// Name ::= CHOICE { -- only one possibility for now -- +// rdnSequence RDNSequence } +var Name = asn1.define('Name', function() { + this.choice({ + rdnSequence: this.use(RDNSequence) + }); +}); +rfc5280.Name = Name; + +// GeneralName ::= CHOICE { +// otherName [0] AnotherName, +// rfc822Name [1] IA5String, +// dNSName [2] IA5String, +// x400Address [3] ORAddress, +// directoryName [4] Name, +// ediPartyName [5] EDIPartyName, +// uniformResourceIdentifier [6] IA5String, +// iPAddress [7] OCTET STRING, +// registeredID [8] OBJECT IDENTIFIER } +var GeneralName = asn1.define('GeneralName', function() { + this.choice({ + otherName: this.implicit(0).use(AnotherName), + rfc822Name: this.implicit(1).ia5str(), + dNSName: this.implicit(2).ia5str(), + directoryName: this.explicit(4).use(Name), + ediPartyName: this.implicit(5).use(EDIPartyName), + uniformResourceIdentifier: this.implicit(6).ia5str(), + iPAddress: this.implicit(7).octstr(), + registeredID: this.implicit(8).objid() + }); +}); +rfc5280.GeneralName = GeneralName; + +// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName +var GeneralNames = asn1.define('GeneralNames', function() { + this.seqof(GeneralName); +}); +rfc5280.GeneralNames = GeneralNames; + +// AnotherName ::= SEQUENCE { +// type-id OBJECT IDENTIFIER, +// value [0] EXPLICIT ANY DEFINED BY type-id } +var AnotherName = asn1.define('AnotherName', function() { + this.seq().obj( + this.key('type-id').objid(), + this.key('value').explicit(0).any() + ); +}); +rfc5280.AnotherName = AnotherName; + +// EDIPartyName ::= SEQUENCE { +// nameAssigner [0] DirectoryString OPTIONAL, +// partyName [1] DirectoryString } +var EDIPartyName = asn1.define('EDIPartyName', function() { + this.seq().obj( + this.key('nameAssigner').implicit(0).optional().use(DirectoryString), + this.key('partyName').implicit(1).use(DirectoryString) + ); +}); +rfc5280.EDIPartyName = EDIPartyName; + +// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName +var RDNSequence = asn1.define('RDNSequence', function() { + this.seqof(RelativeDistinguishedName); +}); +rfc5280.RDNSequence = RDNSequence; + +// RelativeDistinguishedName ::= +// SET SIZE (1..MAX) OF AttributeTypeAndValue +var RelativeDistinguishedName = asn1.define('RelativeDistinguishedName', + function() { + this.setof(AttributeTypeAndValue); +}); +rfc5280.RelativeDistinguishedName = RelativeDistinguishedName; + +// AttributeTypeAndValue ::= SEQUENCE { +// type AttributeType, +// value AttributeValue } +var AttributeTypeAndValue = asn1.define('AttributeTypeAndValue', function() { + this.seq().obj( + this.key('type').use(AttributeType), + this.key('value').use(AttributeValue) + ); +}); +rfc5280.AttributeTypeAndValue = AttributeTypeAndValue; + +// Attribute ::= SEQUENCE { +// type AttributeType, +// values SET OF AttributeValue } +var Attribute = asn1.define('Attribute', function() { + this.seq().obj( + this.key('type').use(AttributeType), + this.key('values').setof(AttributeValue) + ); +}); +rfc5280.Attribute = Attribute; + +// AttributeType ::= OBJECT IDENTIFIER +var AttributeType = asn1.define('AttributeType', function() { + this.objid(); +}); +rfc5280.AttributeType = AttributeType; + +// AttributeValue ::= ANY -- DEFINED BY AttributeType +var AttributeValue = asn1.define('AttributeValue', function() { + this.any(); +}); +rfc5280.AttributeValue = AttributeValue; + +// DirectoryString ::= CHOICE { +// teletexString TeletexString (SIZE (1..MAX)), +// printableString PrintableString (SIZE (1..MAX)), +// universalString UniversalString (SIZE (1..MAX)), +// utf8String UTF8String (SIZE (1..MAX)), +// bmpString BMPString (SIZE (1..MAX)) } +var DirectoryString = asn1.define('DirectoryString', function() { + this.choice({ + teletexString: this.t61str(), + printableString: this.printstr(), + universalString: this.unistr(), + utf8String: this.utf8str(), + bmpString: this.bmpstr() + }); +}); +rfc5280.DirectoryString = DirectoryString; + +// AuthorityKeyIdentifier ::= SEQUENCE { +// keyIdentifier [0] KeyIdentifier OPTIONAL, +// authorityCertIssuer [1] GeneralNames OPTIONAL, +// authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL } +var AuthorityKeyIdentifier = asn1.define('AuthorityKeyIdentifier', function() { + this.seq().obj( + this.key('keyIdentifier').optional().use(KeyIdentifier), + this.key('authorityCertIssuer').optional().use(GeneralNames), + this.key('authorityCertSerialNumber').optional() + .use(CertificateSerialNumber) + ); +}); +rfc5280.AuthorityKeyIdentifier = AuthorityKeyIdentifier; + +// KeyIdentifier ::= OCTET STRING +var KeyIdentifier = asn1.define('KeyIdentifier', function() { + this.octstr(); +}); +rfc5280.KeyIdentifier = KeyIdentifier; + +// CertificateSerialNumber ::= INTEGER +var CertificateSerialNumber = asn1.define('CertificateSerialNumber', + function() { + this.int(); +}); +rfc5280.CertificateSerialNumber = CertificateSerialNumber; + +// ORAddress ::= SEQUENCE { +// built-in-standard-attributes BuiltInStandardAttributes, +// built-in-domain-defined-attributes BuiltInDomainDefinedAttributes +// OPTIONAL, +// extension-attributes ExtensionAttributes OPTIONAL } +var ORAddress = asn1.define('ORAddress', function() { + this.seq().obj( + this.key('builtInStandardAttributes').use(BuiltInStandardAttributes), + this.key('builtInDomainDefinedAttributes').optional() + .use(BuiltInDomainDefinedAttributes), + this.key('extensionAttributes').optional().use(ExtensionAttributes) + ); +}); +rfc5280.ORAddress = ORAddress; + +// BuiltInStandardAttributes ::= SEQUENCE { +// country-name CountryName OPTIONAL, +// administration-domain-name AdministrationDomainName OPTIONAL, +// network-address [0] IMPLICIT NetworkAddress OPTIONAL, +// terminal-identifier [1] IMPLICIT TerminalIdentifier OPTIONAL, +// private-domain-name [2] PrivateDomainName OPTIONAL, +// organization-name [3] IMPLICIT OrganizationName OPTIONAL, +// numeric-user-identifier [4] IMPLICIT NumericUserIdentifier OPTIONAL, +// personal-name [5] IMPLICIT PersonalName OPTIONAL, +// organizational-unit-names [6] IMPLICIT OrganizationalUnitNames OPTIONAL } +var BuiltInStandardAttributes = asn1.define('BuiltInStandardAttributes', + function() { + this.seq().obj( + this.key('countryName').optional().use(CountryName), + this.key('administrationDomainName').optional() + .use(AdministrationDomainName), + this.key('networkAddress').optional().use(NetworkAddress), + this.key('terminalIdentifier').optional().use(TerminalIdentifier), + this.key('privateDomainName').optional().use(PrivateDomainName), + this.key('organizationName').optional().use(OrganizationName), + this.key('numericUserIdentifier').optional().use(NumericUserIdentifier), + this.key('personalName').optional().use(PersonalName), + this.key('organizationalUnitNames').optional().use(OrganizationalUnitNames) + ); +}); +rfc5280.BuiltInStandardAttributes = BuiltInStandardAttributes; + +// CountryName ::= CHOICE { +// x121-dcc-code NumericString, +// iso-3166-alpha2-code PrintableString } +var CountryName = asn1.define('CountryName', function() { + this.choice({ + x121DccCode: this.numstr(), + iso3166Alpha2Code: this.printstr() + }); +}); +rfc5280.CountryName = CountryName; + + +// AdministrationDomainName ::= CHOICE { +// numeric NumericString, +// printable PrintableString } +var AdministrationDomainName = asn1.define('AdministrationDomainName', + function() { + this.choice({ + numeric: this.numstr(), + printable: this.printstr() + }); +}); +rfc5280.AdministrationDomainName = AdministrationDomainName; + +// NetworkAddress ::= X121Address +var NetworkAddress = asn1.define('NetworkAddress', function() { + this.use(X121Address); +}); +rfc5280.NetworkAddress = NetworkAddress; + +// X121Address ::= NumericString +var X121Address = asn1.define('X121Address', function() { + this.numstr(); +}); +rfc5280.X121Address = X121Address; + +// TerminalIdentifier ::= PrintableString +var TerminalIdentifier = asn1.define('TerminalIdentifier', function() { + this.printstr(); +}); +rfc5280.TerminalIdentifier = TerminalIdentifier; + +// PrivateDomainName ::= CHOICE { +// numeric NumericString, +// printable PrintableString } +var PrivateDomainName = asn1.define('PrivateDomainName', function() { + this.choice({ + numeric: this.numstr(), + printable: this.printstr() + }); +}); +rfc5280.PrivateDomainName = PrivateDomainName; + +// OrganizationName ::= PrintableString +var OrganizationName = asn1.define('OrganizationName', function() { + this.printstr(); +}); +rfc5280.OrganizationName = OrganizationName; + +// NumericUserIdentifier ::= NumericString +var NumericUserIdentifier = asn1.define('NumericUserIdentifier', function() { + this.numstr(); +}); +rfc5280.NumericUserIdentifier = NumericUserIdentifier; + +// PersonalName ::= SET { +// surname [0] IMPLICIT PrintableString, +// given-name [1] IMPLICIT PrintableString OPTIONAL, +// initials [2] IMPLICIT PrintableString OPTIONAL, +// generation-qualifier [3] IMPLICIT PrintableString OPTIONAL } +var PersonalName = asn1.define('PersonalName', function() { + this.set().obj( + this.key('surname').implicit().printstr(), + this.key('givenName').implicit().printstr(), + this.key('initials').implicit().printstr(), + this.key('generationQualifier').implicit().printstr() + ); +}); +rfc5280.PersonalName = PersonalName; + +// OrganizationalUnitNames ::= SEQUENCE SIZE (1..ub-organizational-units) +// OF OrganizationalUnitName +var OrganizationalUnitNames = asn1.define('OrganizationalUnitNames', + function() { + this.seqof(OrganizationalUnitName); +}); +rfc5280.OrganizationalUnitNames = OrganizationalUnitNames; + +// OrganizationalUnitName ::= PrintableString (SIZE +// (1..ub-organizational-unit-name-length)) +var OrganizationalUnitName = asn1.define('OrganizationalUnitName', function() { + this.printstr(); +}); +rfc5280.OrganizationalUnitName = OrganizationalUnitName; + +// uiltInDomainDefinedAttributes ::= SEQUENCE SIZE +// (1..ub-domain-defined-attributes) +// OF BuiltInDomainDefinedAttribute +var BuiltInDomainDefinedAttributes = asn1.define( + 'BuiltInDomainDefinedAttributes', function() { + this.seqof(BuiltInDomainDefinedAttribute); +}); +rfc5280.BuiltInDomainDefinedAttributes = BuiltInDomainDefinedAttributes; + +// BuiltInDomainDefinedAttribute ::= SEQUENCE { +// type PrintableString (SIZE (1..ub-domain-defined-attribute-type-length)), +// value PrintableString (SIZE (1..ub-domain-defined-attribute-value-length)) +//} +var BuiltInDomainDefinedAttribute = asn1.define('BuiltInDomainDefinedAttribute', + function() { + this.seq().obj( + this.key('type').printstr(), + this.key('value').printstr() + ); +}); +rfc5280.BuiltInDomainDefinedAttribute = BuiltInDomainDefinedAttribute; + + +// ExtensionAttributes ::= SET SIZE (1..ub-extension-attributes) OF +// ExtensionAttribute +var ExtensionAttributes = asn1.define('ExtensionAttributes', function() { + this.seqof(ExtensionAttribute); +}); +rfc5280.ExtensionAttributes = ExtensionAttributes; + +// ExtensionAttribute ::= SEQUENCE { +// extension-attribute-type [0] IMPLICIT INTEGER, +// extension-attribute-value [1] ANY DEFINED BY extension-attribute-type } +var ExtensionAttribute = asn1.define('ExtensionAttribute', function() { + this.seq().obj( + this.key('extensionAttributeType').implicit().int(), + this.key('extensionAttributeValue').any().implicit().int() + ); +}); +rfc5280.ExtensionAttribute = ExtensionAttribute; + +// SubjectKeyIdentifier ::= KeyIdentifier +var SubjectKeyIdentifier = asn1.define('SubjectKeyIdentifier', function() { + this.use(KeyIdentifier); +}); +rfc5280.SubjectKeyIdentifier = SubjectKeyIdentifier; + +// KeyUsage ::= BIT STRING { +// digitalSignature (0), +// nonRepudiation (1), -- recent editions of X.509 have +// -- renamed this bit to contentCommitment +// keyEncipherment (2), +// dataEncipherment (3), +// keyAgreement (4), +// keyCertSign (5), +// cRLSign (6), +// encipherOnly (7), +// decipherOnly (8) } +var KeyUsage = asn1.define('KeyUsage', function() { + this.bitstr(); +}); +rfc5280.KeyUsage = KeyUsage; + +// CertificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation +var CertificatePolicies = asn1.define('CertificatePolicies', function() { + this.seqof(PolicyInformation); +}); +rfc5280.CertificatePolicies = CertificatePolicies; + +// PolicyInformation ::= SEQUENCE { +// policyIdentifier CertPolicyId, +// policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo +// OPTIONAL } +var PolicyInformation = asn1.define('PolicyInformation', function() { + this.seq().obj( + this.key('policyIdentifier').use(CertPolicyId), + this.key('policyQualifiers').optional().use(PolicyQualifiers) + ); +}); +rfc5280.PolicyInformation = PolicyInformation; + +// CertPolicyId ::= OBJECT IDENTIFIER +var CertPolicyId = asn1.define('CertPolicyId', function() { + this.objid(); +}); +rfc5280.CertPolicyId = CertPolicyId; + +var PolicyQualifiers = asn1.define('PolicyQualifiers', function() { + this.seqof(PolicyQualifierInfo); +}); +rfc5280.PolicyQualifiers = PolicyQualifiers; + +// PolicyQualifierInfo ::= SEQUENCE { +// policyQualifierId PolicyQualifierId, +// qualifier ANY DEFINED BY policyQualifierId } +var PolicyQualifierInfo = asn1.define('PolicyQualifierInfo', function() { + this.seq().obj( + this.key('policyQualifierId').use(PolicyQualifierId), + this.key('qualifier').any().use(PolicyQualifierId) + ); +}); +rfc5280.PolicyQualifierInfo = PolicyQualifierInfo; + +// PolicyQualifierId ::= OBJECT IDENTIFIER +var PolicyQualifierId = asn1.define('PolicyQualifierId', function() { + this.objid(); +}); +rfc5280.PolicyQualifierId = PolicyQualifierId; + +// PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF SEQUENCE { +// issuerDomainPolicy CertPolicyId, +// subjectDomainPolicy CertPolicyId } +var PolicyMappings = asn1.define('PolicyMappings', function() { + this.seqof(PolicyMapping); +}); +rfc5280.PolicyMappings = PolicyMappings; + +var PolicyMapping = asn1.define('PolicyMapping', function() { + this.seq().obj( + this.key('issuerDomainPolicy').use(CertPolicyId), + this.key('subjectDomainPolicy').use(CertPolicyId) + ); +}); +rfc5280.PolicyMapping = PolicyMapping; + +// SubjectAltName ::= GeneralNames +var SubjectAlternativeName = asn1.define('SubjectAlternativeName', function() { + this.use(GeneralNames); +}); +rfc5280.SubjectAlternativeName = SubjectAlternativeName; + +// IssuerAltName ::= GeneralNames +var IssuerAlternativeName = asn1.define('IssuerAlternativeName', function() { + this.use(GeneralNames); +}); +rfc5280.IssuerAlternativeName = IssuerAlternativeName; + +// SubjectDirectoryAttributes ::= SEQUENCE SIZE (1..MAX) OF Attribute +var SubjectDirectoryAttributes = asn1.define('SubjectDirectoryAttributes', + function() { + this.seqof(Attribute); +}); +rfc5280.SubjectDirectoryAttributes = SubjectDirectoryAttributes; + +// BasicConstraints ::= SEQUENCE { +// cA BOOLEAN DEFAULT FALSE, +// pathLenConstraint INTEGER (0..MAX) OPTIONAL } +var BasicConstraints = asn1.define('BasicConstraints', function() { + this.seq().obj( + this.key('cA').bool().def(false), + this.key('pathLenConstraint').optional().int() + ); +}); +rfc5280.BasicConstraints = BasicConstraints; + +// NameConstraints ::= SEQUENCE { +// permittedSubtrees [0] GeneralSubtrees OPTIONAL, +// excludedSubtrees [1] GeneralSubtrees OPTIONAL } +var NameConstraints = asn1.define('NameConstraints', function() { + this.seq().obj( + this.key('permittedSubtrees').implicit(0).optional().use(GeneralSubtrees), + this.key('excludedSubtrees').implicit(1).optional().use(GeneralSubtrees) + ); +}); +rfc5280.NameConstraints = NameConstraints; + +// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree +var GeneralSubtrees = asn1.define('GeneralSubtrees', function() { + this.seqof(GeneralSubtree); +}); +rfc5280.GeneralSubtrees = GeneralSubtrees; + +// GeneralSubtree ::= SEQUENCE { +// base GeneralName, +// minimum [0] BaseDistance DEFAULT 0, +// maximum [1] BaseDistance OPTIONAL } +var GeneralSubtree = asn1.define('GeneralSubtree', function() { + this.seq().obj( + this.key('base').use(GeneralName), + this.key('minimum').default(0).use(BaseDistance), + this.key('maximum').optional().use(BaseDistance) + ); +}); +rfc5280.GeneralSubtree = GeneralSubtree; + +// BaseDistance ::= INTEGER +var BaseDistance = asn1.define('BaseDistance', function() { + this.int(); +}); +rfc5280.BaseDistance = BaseDistance; + +// PolicyConstraints ::= SEQUENCE { +// requireExplicitPolicy [0] SkipCerts OPTIONAL, +// inhibitPolicyMapping [1] SkipCerts OPTIONAL } +var PolicyConstraints = asn1.define('PolicyConstraints', function() { + this.seq().obj( + this.key('requireExplicitPolicy').implicit(0).optional().use(SkipCerts), + this.key('inhibitPolicyMapping').implicit(1).optional().use(SkipCerts) + ); +}); +rfc5280.PolicyConstraints = PolicyConstraints; + +// SkipCerts ::= INTEGER +var SkipCerts = asn1.define('SkipCerts', function() { + this.int(); +}); +rfc5280.SkipCerts = SkipCerts; + +// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId +var ExtendedKeyUsage = asn1.define('ExtendedKeyUsage', function() { + this.seqof(KeyPurposeId); +}); +rfc5280.ExtendedKeyUsage = ExtendedKeyUsage; + +// KeyPurposeId ::= OBJECT IDENTIFIER +var KeyPurposeId = asn1.define('KeyPurposeId', function() { + this.objid(); +}); +rfc5280.KeyPurposeId = KeyPurposeId; + +// RLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint +var CRLDistributionPoints = asn1.define('CRLDistributionPoints', function() { + this.seqof(DistributionPoint); +}); +rfc5280.CRLDistributionPoints = CRLDistributionPoints; + +// DistributionPoint ::= SEQUENCE { +// distributionPoint [0] DistributionPointName OPTIONAL, +// reasons [1] ReasonFlags OPTIONAL, +// cRLIssuer [2] GeneralNames OPTIONAL } +var DistributionPoint = asn1.define('DistributionPoint', function() { + this.seq().obj( + this.key('distributionPoint').optional().use(DistributionPointName), + this.key('reasons').optional().use(ReasonFlags), + this.key('cRLIssuer').optional().use(GeneralNames) + ); +}); +rfc5280.DistributionPoint = DistributionPoint; + +// DistributionPointName ::= CHOICE { +// fullName [0] GeneralNames, +// nameRelativeToCRLIssuer [1] RelativeDistinguishedName } +var DistributionPointName = asn1.define('DistributionPointName', function() { + this.choice({ + fullName: this.implicit(0).use(GeneralNames), + nameRelativeToCRLIssuer: this.implicit(1).use(RelativeDistinguishedName) + }); +}); +rfc5280.DistributionPointName = DistributionPointName; + +// ReasonFlags ::= BIT STRING { +// unused (0), +// keyCompromise (1), +// cACompromise (2), +// affiliationChanged (3), +// superseded (4), +// cessationOfOperation (5), +// certificateHold (6), +// privilegeWithdrawn (7), +// aACompromise (8) } +var ReasonFlags = asn1.define('ReasonFlags', function() { + this.bitstr(); +}); +rfc5280.ReasonFlags = ReasonFlags; + +// InhibitAnyPolicy ::= SkipCerts +var InhibitAnyPolicy = asn1.define('InhibitAnyPolicy', function() { + this.use(SkipCerts); +}); +rfc5280.InhibitAnyPolicy = InhibitAnyPolicy; + +// FreshestCRL ::= CRLDistributionPoints +var FreshestCRL = asn1.define('FreshestCRL', function() { + this.use(CRLDistributionPoints); +}); +rfc5280.FreshestCRL = FreshestCRL; + +// AuthorityInfoAccessSyntax ::= +// SEQUENCE SIZE (1..MAX) OF AccessDescription +var AuthorityInfoAccessSyntax = asn1.define('AuthorityInfoAccessSyntax', + function() { + this.seqof(AccessDescription); +}); +rfc5280.AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax; + +// AccessDescription ::= SEQUENCE { +// accessMethod OBJECT IDENTIFIER, +// accessLocation GeneralName } +var AccessDescription = asn1.define('AccessDescription', function() { + this.seq().obj( + this.key('accessMethod').objid(), + this.key('accessLocation').use(GeneralName) + ); +}); +rfc5280.AccessDescription = AccessDescription; + +// SubjectInfoAccessSyntax ::= +// SEQUENCE SIZE (1..MAX) OF AccessDescription +var SubjectInformationAccess = asn1.define('SubjectInformationAccess', + function() { + this.seqof(AccessDescription); +}); +rfc5280.SubjectInformationAccess = SubjectInformationAccess; + +/** + * CRL Extensions + */ + +// CRLNumber ::= INTEGER +var CRLNumber = asn1.define('CRLNumber', function() { + this.int(); +}); +rfc5280.CRLNumber = CRLNumber; + +var DeltaCRLIndicator = asn1.define('DeltaCRLIndicator', function() { + this.use(CRLNumber); +}); +rfc5280.DeltaCRLIndicator = DeltaCRLIndicator; + +// IssuingDistributionPoint ::= SEQUENCE { +// distributionPoint [0] DistributionPointName OPTIONAL, +// onlyContainsUserCerts [1] BOOLEAN DEFAULT FALSE, +// onlyContainsCACerts [2] BOOLEAN DEFAULT FALSE, +// onlySomeReasons [3] ReasonFlags OPTIONAL, +// indirectCRL [4] BOOLEAN DEFAULT FALSE, +// onlyContainsAttributeCerts [5] BOOLEAN DEFAULT FALSE } +var IssuingDistributionPoint = asn1.define('IssuingDistributionPoint', + function() { + this.seq().obj( + this.key('distributionPoint').use(DistributionPointName), + this.key('onlyContainsUserCerts').def(false).bool(), + this.key('onlyContainsCACerts').def(false).bool(), + this.key('onlySomeReasons').use(ReasonFlags), + this.key('indirectCRL').def(false).bool(), + this.key('onlyContainsAttributeCerts').def(false).bool() + ); +}); +rfc5280.IssuingDistributionPoint = IssuingDistributionPoint; + +// CRLReason ::= ENUMERATED { +// unspecified (0), +// keyCompromise (1), +// cACompromise (2), +// affiliationChanged (3), +// superseded (4), +// cessationOfOperation (5), +// certificateHold (6), +// -- value 7 is not used +// removeFromCRL (8), +// privilegeWithdrawn (9), +// aACompromise (10) } +var ReasonCode = asn1.define('ReasonCode', function() { + this.enum(); +}); +rfc5280.ReasonCode = ReasonCode; + +// InvalidityDate ::= GeneralizedTime +var InvalidityDate = asn1.define('InvalidityDate', function() { + this.gentime(); +}); +rfc5280.InvalidityDate = InvalidityDate; + +// CertificateIssuer ::= GeneralNames +var CertificateIssuer = asn1.define('CertificateIssuer', function() { + this.use(GeneralNames); +}); +rfc5280.CertificateIssuer = CertificateIssuer; + +// OID label to extension model mapping +var x509Extensions = { + subjectDirectoryAttributes: SubjectDirectoryAttributes, + subjectKeyIdentifier: SubjectKeyIdentifier, + keyUsage: KeyUsage, + subjectAlternativeName: SubjectAlternativeName, + issuerAlternativeName: IssuerAlternativeName, + basicConstraints: BasicConstraints, + cRLNumber: CRLNumber, + reasonCode: ReasonCode, + invalidityDate: InvalidityDate, + deltaCRLIndicator: DeltaCRLIndicator, + issuingDistributionPoint: IssuingDistributionPoint, + certificateIssuer: CertificateIssuer, + nameConstraints: NameConstraints, + cRLDistributionPoints: CRLDistributionPoints, + certificatePolicies: CertificatePolicies, + policyMappings: PolicyMappings, + authorityKeyIdentifier: AuthorityKeyIdentifier, + policyConstraints: PolicyConstraints, + extendedKeyUsage: ExtendedKeyUsage, + freshestCRL: FreshestCRL, + inhibitAnyPolicy: InhibitAnyPolicy, + authorityInformationAccess: AuthorityInfoAccessSyntax, + subjectInformationAccess: SubjectInformationAccess +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/package.json new file mode 100644 index 0000000..42cdca2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/package.json @@ -0,0 +1,24 @@ +{ + "name": "asn1.js-rfc5280", + "version": "1.0.0", + "description": "RFC5280 extension structures for asn1.js", + "main": "index.js", + "repository": { + "type": "git", + "url": "git@github.com:indutny/asn1.js" + }, + "keywords": [ + "asn1", + "rfc5280", + "der" + ], + "author": "Felix Hanley", + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/asn1.js/issues" + }, + "homepage": "https://github.com/indutny/asn1.js", + "dependencies": { + "asn1.js": "^4.5.0" + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/basic-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/basic-test.js new file mode 100644 index 0000000..3ce8ed9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/basic-test.js @@ -0,0 +1,105 @@ +var assert = require('assert'); +var fs = require('fs'); +var asn1 = require('../../../'); +var rfc5280 = require('..'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js RFC5280', function() { + + it('should decode Certificate', function() { + var data = fs.readFileSync(__dirname + '/fixtures/cert1.crt'); + var res = rfc5280.Certificate.decode(data, 'der'); + + var tbs = res.tbsCertificate; + assert.equal(tbs.version, 'v3'); + assert.deepEqual(tbs.serialNumber, + new asn1.bignum('462e4256bb1194dc', 16)); + assert.equal(tbs.signature.algorithm.join('.'), + '1.2.840.113549.1.1.5'); + assert.equal(tbs.signature.parameters.toString('hex'), '0500'); + }); + + it('should decode ECC Certificate', function() { + // Symantec Class 3 ECC 256 bit Extended Validation CA from + // https://knowledge.symantec.com/support/ssl-certificates-support/index?page=content&actp=CROSSLINK&id=AR1908 + var data = fs.readFileSync(__dirname + '/fixtures/cert2.crt'); + var res = rfc5280.Certificate.decode(data, 'der'); + + var tbs = res.tbsCertificate; + assert.equal(tbs.version, 'v3'); + assert.deepEqual(tbs.serialNumber, + new asn1.bignum('4d955d20af85c49f6925fbab7c665f89', 16)); + assert.equal(tbs.signature.algorithm.join('.'), + '1.2.840.10045.4.3.3'); // RFC5754 + var spki = rfc5280.SubjectPublicKeyInfo.encode(tbs.subjectPublicKeyInfo, + 'der'); +// spki check to the output of +// openssl x509 -in ecc_cert.pem -pubkey -noout | +// openssl pkey -pubin -outform der | openssl base64 + assert.equal(spki.toString('base64'), + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE3QQ9svKQk5fG6bu8kdtR8KO' + + 'G7fvG04WTMgVJ4ASDYZZR/1chrgvaDucEoX/bKhy9ypg1xXFzQM3oaqtUhE' + + 'Mm4g==' + ); + }); + + it('should decode AuthorityInfoAccess', function() { + var data = new Buffer('305a302b06082b06010505073002861f687474703a2f2f70' + + '6b692e676f6f676c652e636f6d2f47494147322e63727430' + + '2b06082b06010505073001861f687474703a2f2f636c6965' + + '6e7473312e676f6f676c652e636f6d2f6f637370', + 'hex'); + + var info = rfc5280.AuthorityInfoAccessSyntax.decode(data, 'der'); + + assert(info[0].accessMethod); + }); + + it('should decode directoryName in GeneralName', function() { + var data = new Buffer('a411300f310d300b06022a03160568656c6c6f', 'hex'); + + var name = rfc5280.GeneralName.decode(data, 'der'); + assert.equal(name.type, 'directoryName'); + }); + + it('should decode Certificate Extensions', function() { + var data; + var cert; + + var extensions = {} + data = fs.readFileSync(__dirname + '/fixtures/cert3.crt'); + cert = rfc5280.Certificate.decode(data, 'der'); + cert.tbsCertificate.extensions.forEach(function(e) { + extensions[e.extnID] = e + }); + assert.equal(extensions.basicConstraints.extnValue.cA, false); + assert.equal(extensions.extendedKeyUsage.extnValue.length, 2); + + extensions = {} + data = fs.readFileSync(__dirname + '/fixtures/cert4.crt'); + cert = rfc5280.Certificate.decode(data, 'der'); + cert.tbsCertificate.extensions.forEach(function(e) { + extensions[e.extnID] = e + }); + assert.equal(extensions.basicConstraints.extnValue.cA, true); + assert.equal(extensions.authorityInformationAccess.extnValue[0] + .accessLocation.value, 'http://ocsp.godaddy.com/') + + extensions = {} + data = fs.readFileSync(__dirname + '/fixtures/cert5.crt'); + cert = rfc5280.Certificate.decode(data, 'der'); + cert.tbsCertificate.extensions.forEach(function(e) { + extensions[e.extnID] = e + }); + assert.equal(extensions.basicConstraints.extnValue.cA, true); + + extensions = {} + data = fs.readFileSync(__dirname + '/fixtures/cert6.crt'); + cert = rfc5280.Certificate.decode(data, 'der'); + cert.tbsCertificate.extensions.forEach(function(e) { + extensions[e.extnID] = e + }); + assert.equal(extensions.basicConstraints.extnValue.cA, true); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert1.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert1.crt new file mode 100644 index 0000000..35447cf Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert1.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert2.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert2.crt new file mode 100644 index 0000000..bf9eff1 Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert2.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert3.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert3.crt new file mode 100644 index 0000000..218a8a0 Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert3.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert4.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert4.crt new file mode 100644 index 0000000..885c45a Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert4.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert5.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert5.crt new file mode 100644 index 0000000..0ba053c Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert5.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert6.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert6.crt new file mode 100644 index 0000000..3cd289b Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert6.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/der-decode-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/der-decode-test.js new file mode 100644 index 0000000..0f1ad86 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/der-decode-test.js @@ -0,0 +1,149 @@ +var assert = require('assert'); +var asn1 = require('..'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js DER decoder', function() { + it('should propagate implicit tag', function() { + var B = asn1.define('B', function() { + this.seq().obj( + this.key('b').octstr() + ); + }); + + var A = asn1.define('Bug', function() { + this.seq().obj( + this.key('a').implicit(0).use(B) + ); + }); + + var out = A.decode(new Buffer('300720050403313233', 'hex'), 'der'); + assert.equal(out.a.b.toString(), '123'); + }); + + it('should decode optional tag to undefined key', function() { + var A = asn1.define('A', function() { + this.seq().obj( + this.key('key').bool(), + this.optional().key('opt').bool() + ); + }); + var out = A.decode(new Buffer('30030101ff', 'hex'), 'der'); + assert.deepEqual(out, { 'key': true }); + }); + + it('should decode optional tag to default value', function() { + var A = asn1.define('A', function() { + this.seq().obj( + this.key('key').bool(), + this.optional().key('opt').octstr().def('default') + ); + }); + var out = A.decode(new Buffer('30030101ff', 'hex'), 'der'); + assert.deepEqual(out, { 'key': true, 'opt': 'default' }); + }); + + function test(name, model, inputHex, expected) { + it(name, function() { + var M = asn1.define('Model', model); + var decoded = M.decode(new Buffer(inputHex,'hex'), 'der'); + assert.deepEqual(decoded, expected); + }); + } + + test('should decode choice', function() { + this.choice({ + apple: this.bool(), + }); + }, '0101ff', { 'type': 'apple', 'value': true }); + + it('should decode optional and use', function() { + var B = asn1.define('B', function() { + this.int(); + }); + + var A = asn1.define('A', function() { + this.optional().use(B); + }); + + var out = A.decode(new Buffer('020101', 'hex'), 'der'); + assert.equal(out.toString(10), '1'); + }); + + test('should decode indefinite length', function() { + this.seq().obj( + this.key('key').bool() + ); + }, '30800101ff0000', { 'key': true }); + + test('should decode bmpstr', function() { + this.bmpstr(); + }, '1e26004300650072007400690066006900630061' + + '0074006500540065006d0070006c006100740065', 'CertificateTemplate'); + + test('should decode bmpstr with cyrillic chars', function() { + this.bmpstr(); + }, '1e0c041f04400438043204350442', 'Привет'); + + test('should properly decode objid with dots', function() { + this.objid({ + '1.2.398.3.10.1.1.1.2.2': 'yes' + }); + }, '060a2a830e030a0101010202', 'yes'); + + it('should decode encapsulated models', function() { + var B = asn1.define('B', function() { + this.seq().obj( + this.key('nested').int() + ); + }); + var A = asn1.define('A', function() { + this.octstr().contains(B); + }); + + var out = A.decode(new Buffer('04053003020105', 'hex'), 'der'); + assert.equal(out.nested.toString(10), '5'); + }); + + test('should decode IA5 string', function() { + this.ia5str(); + }, '160C646F6720616E6420626F6E65', 'dog and bone'); + + test('should decode printable string', function() { + this.printstr(); + }, '1310427261686D7320616E64204C69737A74', 'Brahms and Liszt'); + + test('should decode T61 string', function() { + this.t61str(); + }, '140C4F6C69766572205477697374', 'Oliver Twist'); + + test('should decode ISO646 string', function() { + this.iso646str(); + }, '1A0B7365707469632074616E6B', 'septic tank'); + + it('should decode optional seqof', function() { + var B = asn1.define('B', function() { + this.seq().obj( + this.key('num').int() + ); + }); + var A = asn1.define('A', function() { + this.seq().obj( + this.key('test1').seqof(B), + this.key('test2').optional().seqof(B) + ); + }); + + var out = A.decode(new Buffer( + '3018300A30030201013003020102300A30030201033003020104', 'hex'), 'der'); + assert.equal(out.test1[0].num.toString(10), 1); + assert.equal(out.test1[1].num.toString(10), 2); + assert.equal(out.test2[0].num.toString(10), 3); + assert.equal(out.test2[1].num.toString(10), 4); + + out = A.decode(new Buffer('300C300A30030201013003020102', 'hex'), 'der'); + assert.equal(out.test1[0].num.toString(10), 1); + assert.equal(out.test1[1].num.toString(10), 2); + assert.equal(out.test2, undefined); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/der-encode-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/der-encode-test.js new file mode 100644 index 0000000..af37293 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/der-encode-test.js @@ -0,0 +1,133 @@ +var assert = require('assert'); +var asn1 = require('..'); +var BN = require('bn.js'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js DER encoder', function() { + /* + * Explicit value shold be wrapped with A0 | EXPLICIT tag + * this adds two more bytes to resulting buffer. + * */ + it('should code explicit tag as 0xA2', function() { + var E = asn1.define('E', function() { + this.explicit(2).octstr() + }); + + var encoded = E.encode('X', 'der'); + + // + assert.equal(encoded.toString('hex'), 'a203040158'); + assert.equal(encoded.length, 5); + }) + + function test(name, model_definition, model_value, der_expected) { + it(name, function() { + var Model, der_actual; + Model = asn1.define('Model', model_definition); + der_actual = Model.encode(model_value, 'der'); + assert.deepEqual(der_actual, new Buffer(der_expected,'hex')); + }); + } + + test('should encode choice', function() { + this.choice({ + apple: this.bool(), + }); + }, { type: 'apple', value: true }, '0101ff'); + + test('should encode implicit seqof', function() { + var Int = asn1.define('Int', function() { + this.int(); + }); + this.implicit(0).seqof(Int); + }, [ 1 ], 'A003020101' ); + + test('should encode explicit seqof', function() { + var Int = asn1.define('Int', function() { + this.int(); + }); + this.explicit(0).seqof(Int); + }, [ 1 ], 'A0053003020101' ); + + test('should encode BN(128) properly', function() { + this.int(); + }, new BN(128), '02020080'); + + test('should encode int 128 properly', function() { + this.int(); + }, 128, '02020080'); + + test('should encode 0x8011 properly', function() { + this.int(); + }, 0x8011, '0203008011'); + + test('should omit default value in DER', function() { + this.seq().obj( + this.key('required').def(false).bool(), + this.key('value').int() + ); + }, {required: false, value: 1}, '3003020101'); + + it('should encode optional and use', function() { + var B = asn1.define('B', function() { + this.int(); + }); + + var A = asn1.define('A', function() { + this.optional().use(B); + }); + + var out = A.encode(1, 'der'); + assert.equal(out.toString('hex'), '020101'); + }); + + test('should properly encode objid with dots', function() { + this.objid({ + '1.2.398.3.10.1.1.1.2.2': 'yes' + }); + }, 'yes', '060a2a830e030a0101010202'); + + test('should properly encode objid as array of strings', function() { + this.objid(); + }, '1.2.398.3.10.1.1.1.2.2'.split('.'), '060a2a830e030a0101010202'); + + test('should properly encode bmpstr', function() { + this.bmpstr(); + }, 'CertificateTemplate', '1e26004300650072007400690066006900630061' + + '0074006500540065006d0070006c006100740065'); + + test('should properly encode bmpstr with cyrillic chars', function() { + this.bmpstr(); + }, 'Привет', '1e0c041f04400438043204350442'); + + it('should encode encapsulated models', function() { + var B = asn1.define('B', function() { + this.seq().obj( + this.key('nested').int() + ); + }); + var A = asn1.define('A', function() { + this.octstr().contains(B); + }); + + var out = A.encode({ nested: 5 }, 'der') + assert.equal(out.toString('hex'), '04053003020105'); + }); + + test('should properly encode IA5 string', function() { + this.ia5str(); + }, 'dog and bone', '160C646F6720616E6420626F6E65'); + + test('should properly encode printable string', function() { + this.printstr(); + }, 'Brahms and Liszt', '1310427261686D7320616E64204C69737A74'); + + test('should properly encode T61 string', function() { + this.t61str(); + }, 'Oliver Twist', '140C4F6C69766572205477697374'); + + test('should properly encode ISO646 string', function() { + this.iso646str(); + }, 'septic tank', '1A0B7365707469632074616E6B'); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/error-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/error-test.js new file mode 100644 index 0000000..9892905 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/error-test.js @@ -0,0 +1,222 @@ +var assert = require('assert'); +var asn1 = require('..'); +var bn = asn1.bignum; +var fixtures = require('./fixtures'); +var jsonEqual = fixtures.jsonEqual; + +var Buffer = require('buffer').Buffer; + +describe('asn1.js error', function() { + describe('encoder', function() { + function test(name, model, input, expected) { + it('should support ' + name, function() { + var M = asn1.define('TestModel', model); + + var error; + assert.throws(function() { + try { + var encoded = M.encode(input, 'der'); + } catch (e) { + error = e; + throw e; + } + }); + + assert(expected.test(error.stack), + 'Failed to match, expected: ' + expected + ' got: ' + + JSON.stringify(error.stack)); + }); + } + + describe('primitives', function() { + test('int', function() { + this.int(); + }, 'hello', /no values map/i); + + test('enum', function() { + this.enum({ 0: 'hello', 1: 'world' }); + }, 'gosh', /contain: "gosh"/); + + test('objid', function() { + this.objid(); + }, 1, /objid\(\) should be either array or string, got: 1/); + + test('numstr', function() { + this.numstr(); + }, 'hello', /only digits and space/); + + test('printstr', function() { + this.printstr(); + }, 'hello!', /only latin upper and lower case letters/); + }); + + describe('composite', function() { + test('shallow', function() { + this.seq().obj( + this.key('key').int() + ); + }, { key: 'hello' } , /map at: \["key"\]/i); + + test('deep and empty', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ) + ) + ); + }, { } , /input is not object at: \["a"\]\["b"\]/i); + + test('deep', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ) + ) + ); + }, { a: { b: { c: 'hello' } } } , /map at: \["a"\]\["b"\]\["c"\]/i); + + test('use', function() { + var S = asn1.define('S', function() { + this.seq().obj( + this.key('x').int() + ); + }); + + this.seq().obj( + this.key('a').seq().obj( + this.key('b').use(S) + ) + ); + }, { a: { b: { x: 'hello' } } } , /map at: \["a"\]\["b"\]\["x"\]/i); + }); + }); + + describe('decoder', function() { + function test(name, model, input, expected) { + it('should support ' + name, function() { + var M = asn1.define('TestModel', model); + + var error; + assert.throws(function() { + try { + var decoded = M.decode(new Buffer(input, 'hex'), 'der'); + } catch (e) { + error = e; + throw e; + } + }); + var partial = M.decode(new Buffer(input, 'hex'), 'der', { + partial: true + }); + + assert(expected.test(error.stack), + 'Failed to match, expected: ' + expected + ' got: ' + + JSON.stringify(error.stack)); + + assert.equal(partial.errors.length, 1); + assert(expected.test(partial.errors[0].stack), + 'Failed to match, expected: ' + expected + ' got: ' + + JSON.stringify(partial.errors[0].stack)); + }); + } + + describe('primitive', function() { + test('int', function() { + this.int(); + }, '2201', /body of: "int"/); + + test('int', function() { + this.int(); + }, '', /tag of "int"/); + + test('bmpstr invalid length', function() { + this.bmpstr(); + }, '1e0b041f04400438043204350442', /bmpstr length mismatch/); + + test('numstr unsupported characters', function() { + this.numstr(); + }, '12024141', /numstr unsupported characters/); + + test('printstr unsupported characters', function() { + this.printstr(); + }, '13024121', /printstr unsupported characters/); + }); + + describe('composite', function() { + test('shallow', function() { + this.seq().obj( + this.key('a').seq().obj() + ); + }, '30', /length of "seq"/); + + test('deep and empty', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ) + ) + ); + }, '300430023000', /tag of "int" at: \["a"\]\["b"\]\["c"\]/); + + test('deep and incomplete', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ) + ) + ); + }, '30053003300122', /length of "int" at: \["a"\]\["b"\]\["c"\]/); + }); + }); + + describe('partial decoder', function() { + function test(name, model, input, expectedObj, expectedErrs) { + it('should support ' + name, function() { + var M = asn1.define('TestModel', model); + + var decoded = M.decode(new Buffer(input, 'hex'), 'der', { + partial: true + }); + + jsonEqual(decoded.result, expectedObj); + + assert.equal(decoded.errors.length, expectedErrs.length); + expectedErrs.forEach(function(expected, i) { + assert(expected.test(decoded.errors[i].stack), + 'Failed to match, expected: ' + expected + ' got: ' + + JSON.stringify(decoded.errors[i].stack)); + }); + }); + } + + test('last key not present', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ), + this.key('d').int() + ) + ); + }, '30073005300022012e', { a: { b: {}, d: new bn(46) } }, [ + /"int" at: \["a"\]\["b"\]\["c"\]/ + ]); + + test('first key not present', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ), + this.key('d').int() + ) + ); + }, '30073005300322012e', { a: { b: { c: new bn(46) } } }, [ + /"int" at: \["a"\]\["d"\]/ + ]); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/fixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/fixtures.js new file mode 100644 index 0000000..9ee4db6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/fixtures.js @@ -0,0 +1,7 @@ +var assert = require('assert'); + +function jsonEqual(a, b) { + assert.deepEqual(JSON.parse(JSON.stringify(a)), + JSON.parse(JSON.stringify(b))); +} +exports.jsonEqual = jsonEqual; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/pem-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/pem-test.js new file mode 100644 index 0000000..dfbe7db --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/pem-test.js @@ -0,0 +1,54 @@ +var assert = require('assert'); +var asn1 = require('..'); +var BN = require('bn.js'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js PEM encoder/decoder', function() { + var model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('b').bitstr(), + this.key('c').int() + ); + }); + + var hundred = new Buffer(100); + hundred.fill('A'); + + it('should encode PEM', function() { + + var out = model.encode({ + a: new BN(123), + b: { + data: hundred, + unused: 0 + }, + c: new BN(456) + }, 'pem', { + label: 'MODEL' + }); + + var expected = + '-----BEGIN MODEL-----\n' + + 'MG4CAXsDZQBBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n' + + 'QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n' + + 'QUFBQUFBQUFBQUFBAgIByA==\n' + + '-----END MODEL-----'; + assert.equal(out, expected); + }); + + it('should decode PEM', function() { + var expected = + '-----BEGIN MODEL-----\n' + + 'MG4CAXsDZQBBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n' + + 'QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n' + + 'QUFBQUFBQUFBQUFBAgIByA==\n' + + '-----END MODEL-----'; + + var out = model.decode(expected, 'pem', { label: 'MODEL' }); + assert.equal(out.a.toString(), '123'); + assert.equal(out.b.data.toString(), hundred.toString()); + assert.equal(out.c.toString(), '456'); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/ping-pong-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/ping-pong-test.js new file mode 100644 index 0000000..0e2be0a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/ping-pong-test.js @@ -0,0 +1,170 @@ +var assert = require('assert'); +var asn1 = require('..'); +var fixtures = require('./fixtures'); +var jsonEqual = fixtures.jsonEqual; + +var Buffer = require('buffer').Buffer; + +describe('asn1.js ping/pong', function() { + function test(name, model, input, expected) { + it('should support ' + name, function() { + var M = asn1.define('TestModel', model); + + var encoded = M.encode(input, 'der'); + var decoded = M.decode(encoded, 'der'); + jsonEqual(decoded, expected !== undefined ? expected : input); + }); + } + + describe('primitives', function() { + test('bigint', function() { + this.int(); + }, new asn1.bignum('0102030405060708', 16)); + + test('enum', function() { + this.enum({ 0: 'hello', 1: 'world' }); + }, 'world'); + + test('octstr', function() { + this.octstr(); + }, new Buffer('hello')); + + test('bitstr', function() { + this.bitstr(); + }, { unused: 4, data: new Buffer('hello!') }); + + test('ia5str', function() { + this.ia5str(); + }, 'hello'); + + test('utf8str', function() { + this.utf8str(); + }, 'hello'); + + test('bmpstr', function() { + this.bmpstr(); + }, 'hello'); + + test('numstr', function() { + this.numstr(); + }, '1234 5678 90'); + + test('printstr', function() { + this.printstr(); + }, 'hello'); + + test('gentime', function() { + this.gentime(); + }, 1385921175000); + + test('utctime', function() { + this.utctime(); + }, 1385921175000); + + test('utctime regression', function() { + this.utctime(); + }, 1414454400000); + + test('null', function() { + this.null_(); + }, null); + + test('objid', function() { + this.objid({ + '1 3 6 1 5 5 7 48 1 1': 'id-pkix-ocsp-basic' + }); + }, 'id-pkix-ocsp-basic'); + + test('true', function() { + this.bool(); + }, true); + + test('false', function() { + this.bool(); + }, false); + + test('any', function() { + this.any(); + }, new Buffer('02210081347a0d3d674aeeb563061d94a3aea5f6a7' + + 'c6dc153ea90a42c1ca41929ac1b9', 'hex')); + + test('default explicit', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).int({ + 0: 'v1', + 1: 'v2' + }) + ); + }, {}, {'version': 'v1'}); + + test('implicit', function() { + this.implicit(0).int({ + 0: 'v1', + 1: 'v2' + }); + }, 'v2', 'v2'); + }); + + describe('composite', function() { + test('2x int', function() { + this.seq().obj( + this.key('hello').int(), + this.key('world').int() + ); + }, { hello: 4, world: 2 }); + + test('enum', function() { + this.seq().obj( + this.key('hello').enum({ 0: 'world', 1: 'devs' }) + ); + }, { hello: 'devs' }); + + test('optionals', function() { + this.seq().obj( + this.key('hello').enum({ 0: 'world', 1: 'devs' }), + this.key('how').optional().def('are you').enum({ + 0: 'are you', + 1: 'are we?!' + }) + ); + }, { hello: 'devs', how: 'are we?!' }); + + test('optionals #2', function() { + this.seq().obj( + this.key('hello').enum({ 0: 'world', 1: 'devs' }), + this.key('how').optional().def('are you').enum({ + 0: 'are you', + 1: 'are we?!' + }) + ); + }, { hello: 'devs' }, { hello: 'devs', how: 'are you' }); + + test('optionals #3', function() { + this.seq().obj( + this.key('content').optional().int() + ); + }, {}, {}); + + test('optional + any', function() { + this.seq().obj( + this.key('content').optional().any() + ); + }, { content: new Buffer('0500', 'hex') }); + + test('seqof', function() { + var S = asn1.define('S', function() { + this.seq().obj( + this.key('a').def('b').int({ 0: 'a', 1: 'b' }), + this.key('c').def('d').int({ 2: 'c', 3: 'd' }) + ); + }); + this.seqof(S); + }, [{}, { a: 'a', c: 'c' }], [{ a: 'b', c: 'd' }, { a: 'a', c: 'c' }]); + + test('choice', function() { + this.choice({ + apple: this.bool() + }); + }, { type: 'apple', value: true }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/use-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/use-test.js new file mode 100644 index 0000000..93e088a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/asn1.js/test/use-test.js @@ -0,0 +1,128 @@ +var assert = require('assert'); +var asn1 = require('..'); +var bn = asn1.bignum; +var fixtures = require('./fixtures'); +var jsonEqual = fixtures.jsonEqual; + +var Buffer = require('buffer').Buffer; + +describe('asn1.js models', function() { + describe('plain use', function() { + it('should encode submodel', function() { + var SubModel = asn1.define('SubModel', function() { + this.seq().obj( + this.key('b').octstr() + ); + }); + var Model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('sub').use(SubModel) + ); + }); + + var data = {a: new bn(1), sub: {b: new Buffer("XXX")}}; + var wire = Model.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300a02010130050403585858'); + var back = Model.decode(wire, 'der'); + jsonEqual(back, data); + }); + + it('should honour implicit tag from parent', function() { + var SubModel = asn1.define('SubModel', function() { + this.seq().obj( + this.key('x').octstr() + ) + }); + var Model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('sub').use(SubModel).implicit(0) + ); + }); + + var data = {a: new bn(1), sub: {x: new Buffer("123")}}; + var wire = Model.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300a020101a0050403313233'); + var back = Model.decode(wire, 'der'); + jsonEqual(back, data); + }); + + it('should honour explicit tag from parent', function() { + var SubModel = asn1.define('SubModel', function() { + this.seq().obj( + this.key('x').octstr() + ) + }); + var Model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('sub').use(SubModel).explicit(0) + ); + }); + + var data = {a: new bn(1), sub: {x: new Buffer("123")}}; + var wire = Model.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300c020101a00730050403313233'); + var back = Model.decode(wire, 'der'); + jsonEqual(back, data); + + }); + + it('should get model with function call', function() { + var SubModel = asn1.define('SubModel', function() { + this.seq().obj( + this.key('x').octstr() + ) + }); + var Model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('sub').use(function(obj) { + assert.equal(obj.a, 1); + return SubModel; + }) + ); + }); + + var data = {a: new bn(1), sub: {x: new Buffer("123")}}; + var wire = Model.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300a02010130050403313233'); + var back = Model.decode(wire, 'der'); + jsonEqual(back, data); + + }); + + it('should support recursive submodels', function() { + var PlainSubModel = asn1.define('PlainSubModel', function() { + this.int(); + }); + var RecursiveModel = asn1.define('RecursiveModel', function() { + this.seq().obj( + this.key('plain').bool(), + this.key('content').use(function(obj) { + if(obj.plain) { + return PlainSubModel; + } else { + return RecursiveModel; + } + }) + ); + }); + + var data = { + 'plain': false, + 'content': { + 'plain': true, + 'content': new bn(1) + } + }; + var wire = RecursiveModel.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300b01010030060101ff020101'); + var back = RecursiveModel.decode(wire, 'der'); + jsonEqual(back, data); + }); + + }); +}); + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.eslintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.eslintrc new file mode 100644 index 0000000..bed248a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.eslintrc @@ -0,0 +1,132 @@ +{ + "ecmaFeatures": { + "modules": true, + "experimentalObjectRestSpread": true + }, + + "env": { + "browser": false, + "es6": true, + "node": true + }, + + "plugins": [ + "standard" + ], + + "globals": { + "document": false, + "navigator": false, + "window": false + }, + + "rules": { + "accessor-pairs": 2, + "arrow-spacing": [2, { "before": true, "after": true }], + "block-spacing": [2, "always"], + "brace-style": [2, "1tbs", { "allowSingleLine": true }], + "comma-dangle": [2, "never"], + "comma-spacing": [2, { "before": false, "after": true }], + "comma-style": [2, "last"], + "constructor-super": 2, + "curly": [2, "multi-line"], + "dot-location": [2, "property"], + "eol-last": 2, + "eqeqeq": [2, "allow-null"], + "generator-star-spacing": [2, { "before": true, "after": true }], + "handle-callback-err": [2, "^(err|error)$" ], + "indent": [2, 2, { "SwitchCase": 1 }], + "key-spacing": [2, { "beforeColon": false, "afterColon": true }], + "new-cap": [2, { "newIsCap": true, "capIsNew": false }], + "new-parens": 2, + "no-array-constructor": 2, + "no-caller": 2, + "no-class-assign": 2, + "no-cond-assign": 2, + "no-const-assign": 2, + "no-control-regex": 2, + "no-debugger": 2, + "no-delete-var": 2, + "no-dupe-args": 2, + "no-dupe-class-members": 2, + "no-dupe-keys": 2, + "no-duplicate-case": 2, + "no-empty-character-class": 2, + "no-empty-label": 2, + "no-eval": 2, + "no-ex-assign": 2, + "no-extend-native": 2, + "no-extra-bind": 2, + "no-extra-boolean-cast": 2, + "no-extra-parens": [2, "functions"], + "no-fallthrough": 2, + "no-floating-decimal": 2, + "no-func-assign": 2, + "no-implied-eval": 2, + "no-inner-declarations": [2, "functions"], + "no-invalid-regexp": 2, + "no-irregular-whitespace": 2, + "no-iterator": 2, + "no-label-var": 2, + "no-labels": 2, + "no-lone-blocks": 2, + "no-mixed-spaces-and-tabs": 2, + "no-multi-spaces": 2, + "no-multi-str": 2, + "no-multiple-empty-lines": [2, { "max": 1 }], + "no-native-reassign": 2, + "no-negated-in-lhs": 2, + "no-new": 2, + "no-new-func": 2, + "no-new-object": 2, + "no-new-require": 2, + "no-new-wrappers": 2, + "no-obj-calls": 2, + "no-octal": 2, + "no-octal-escape": 2, + "no-proto": 2, + "no-redeclare": 2, + "no-regex-spaces": 2, + "no-return-assign": 2, + "no-self-compare": 2, + "no-sequences": 2, + "no-shadow-restricted-names": 2, + "no-spaced-func": 2, + "no-sparse-arrays": 2, + "no-this-before-super": 2, + "no-throw-literal": 2, + "no-trailing-spaces": 2, + "no-undef": 2, + "no-undef-init": 2, + "no-unexpected-multiline": 2, + "no-unneeded-ternary": [2, { "defaultAssignment": false }], + "no-unreachable": 2, + "no-unused-vars": [2, { "vars": "all", "args": "none" }], + "no-useless-call": 2, + "no-with": 2, + "one-var": [2, { "initialized": "never" }], + "operator-linebreak": [2, "after", { "overrides": { "?": "before", ":": "before" } }], + "padded-blocks": [2, "never"], + "quotes": [2, "single", "avoid-escape"], + "radix": 2, + "semi": [2, "never"], + "semi-spacing": [2, { "before": false, "after": true }], + "space-after-keywords": [2, "always"], + "space-before-blocks": [2, "always"], + "space-before-function-paren": [2, "always"], + "space-before-keywords": [2, "always"], + "space-in-parens": [2, "never"], + "space-infix-ops": 2, + "space-return-throw-case": 2, + "space-unary-ops": [2, { "words": true, "nonwords": false }], + "spaced-comment": [2, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }], + "use-isnan": 2, + "valid-typeof": 2, + "wrap-iife": [2, "any"], + "yoda": [2, "never"], + + "standard/object-curly-even-spacing": [2, "either"], + "standard/array-bracket-even-spacing": [2, "either"], + "standard/computed-property-even-spacing": [2, "even"] + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.npmignore new file mode 100644 index 0000000..65e3ba2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.npmignore @@ -0,0 +1 @@ +test/ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/LICENSE new file mode 100644 index 0000000..924b38b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 browserify-aes contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/aes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/aes.js new file mode 100644 index 0000000..4829057 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/aes.js @@ -0,0 +1,177 @@ +// based on the aes implimentation in triple sec +// https://github.com/keybase/triplesec + +// which is in turn based on the one from crypto-js +// https://code.google.com/p/crypto-js/ + +var uint_max = Math.pow(2, 32) +function fixup_uint32 (x) { + var ret, x_pos + ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x + return ret +} +function scrub_vec (v) { + for (var i = 0; i < v.length; v++) { + v[i] = 0 + } + return false +} + +function Global () { + this.SBOX = [] + this.INV_SBOX = [] + this.SUB_MIX = [[], [], [], []] + this.INV_SUB_MIX = [[], [], [], []] + this.init() + this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] +} + +Global.prototype.init = function () { + var d, i, sx, t, x, x2, x4, x8, xi, _i + d = (function () { + var _i, _results + _results = [] + for (i = _i = 0; _i < 256; i = ++_i) { + if (i < 128) { + _results.push(i << 1) + } else { + _results.push((i << 1) ^ 0x11b) + } + } + return _results + })() + x = 0 + xi = 0 + for (i = _i = 0; _i < 256; i = ++_i) { + sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 + this.SBOX[x] = sx + this.INV_SBOX[sx] = x + x2 = d[x] + x4 = d[x2] + x8 = d[x4] + t = (d[sx] * 0x101) ^ (sx * 0x1010100) + this.SUB_MIX[0][x] = (t << 24) | (t >>> 8) + this.SUB_MIX[1][x] = (t << 16) | (t >>> 16) + this.SUB_MIX[2][x] = (t << 8) | (t >>> 24) + this.SUB_MIX[3][x] = t + t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) + this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) + this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) + this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) + this.INV_SUB_MIX[3][sx] = t + if (x === 0) { + x = xi = 1 + } else { + x = x2 ^ d[d[d[x8 ^ x2]]] + xi ^= d[d[xi]] + } + } + return true +} + +var G = new Global() + +AES.blockSize = 4 * 4 + +AES.prototype.blockSize = AES.blockSize + +AES.keySize = 256 / 8 + +AES.prototype.keySize = AES.keySize + +function bufferToArray (buf) { + var len = buf.length / 4 + var out = new Array(len) + var i = -1 + while (++i < len) { + out[i] = buf.readUInt32BE(i * 4) + } + return out +} +function AES (key) { + this._key = bufferToArray(key) + this._doReset() +} + +AES.prototype._doReset = function () { + var invKsRow, keySize, keyWords, ksRow, ksRows, t + keyWords = this._key + keySize = keyWords.length + this._nRounds = keySize + 6 + ksRows = (this._nRounds + 1) * 4 + this._keySchedule = [] + for (ksRow = 0; ksRow < ksRows; ksRow++) { + this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t) + } + this._invKeySchedule = [] + for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { + ksRow = ksRows - invKsRow + t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)] + this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]] + } + return true +} + +AES.prototype.encryptBlock = function (M) { + M = bufferToArray(new Buffer(M)) + var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} + +AES.prototype.decryptBlock = function (M) { + M = bufferToArray(new Buffer(M)) + var temp = [M[3], M[1]] + M[1] = temp[0] + M[3] = temp[1] + var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[3], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[1], 12) + return buf +} + +AES.prototype.scrub = function () { + scrub_vec(this._keySchedule) + scrub_vec(this._invKeySchedule) + scrub_vec(this._key) +} + +AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) { + var ksRow, s0, s1, s2, s3, t0, t1, t2, t3 + + s0 = M[0] ^ keySchedule[0] + s1 = M[1] ^ keySchedule[1] + s2 = M[2] ^ keySchedule[2] + s3 = M[3] ^ keySchedule[3] + ksRow = 4 + for (var round = 1; round < this._nRounds; round++) { + t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++] + t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++] + t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + s2 = t2 + s3 = t3 + } + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] + t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] + t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + return [ + fixup_uint32(t0), + fixup_uint32(t1), + fixup_uint32(t2), + fixup_uint32(t3) + ] +} + +exports.AES = AES diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/authCipher.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/authCipher.js new file mode 100644 index 0000000..1107a01 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/authCipher.js @@ -0,0 +1,97 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var GHASH = require('./ghash') +var xor = require('buffer-xor') +inherits(StreamCipher, Transform) +module.exports = StreamCipher + +function StreamCipher (mode, key, iv, decrypt) { + if (!(this instanceof StreamCipher)) { + return new StreamCipher(mode, key, iv) + } + Transform.call(this) + this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])]) + iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])]) + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + this._cache = new Buffer('') + this._secCache = new Buffer('') + this._decrypt = decrypt + this._alen = 0 + this._len = 0 + iv.copy(this._prev) + this._mode = mode + var h = new Buffer(4) + h.fill(0) + this._ghash = new GHASH(this._cipher.encryptBlock(h)) + this._authTag = null + this._called = false +} +StreamCipher.prototype._update = function (chunk) { + if (!this._called && this._alen) { + var rump = 16 - (this._alen % 16) + if (rump < 16) { + rump = new Buffer(rump) + rump.fill(0) + this._ghash.update(rump) + } + } + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) + } else { + this._ghash.update(out) + } + this._len += chunk.length + return out +} +StreamCipher.prototype._final = function () { + if (this._decrypt && !this._authTag) { + throw new Error('Unsupported state or unable to authenticate data') + } + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) + if (this._decrypt) { + if (xorTest(tag, this._authTag)) { + throw new Error('Unsupported state or unable to authenticate data') + } + } else { + this._authTag = tag + } + this._cipher.scrub() +} +StreamCipher.prototype.getAuthTag = function getAuthTag () { + if (!this._decrypt && Buffer.isBuffer(this._authTag)) { + return this._authTag + } else { + throw new Error('Attempting to get auth tag in unsupported state') + } +} +StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { + if (this._decrypt) { + this._authTag = tag + } else { + throw new Error('Attempting to set auth tag in unsupported state') + } +} +StreamCipher.prototype.setAAD = function setAAD (buf) { + if (!this._called) { + this._ghash.update(buf) + this._alen += buf.length + } else { + throw new Error('Attempting to set AAD in unsupported state') + } +} +function xorTest (a, b) { + var out = 0 + if (a.length !== b.length) { + out++ + } + var len = Math.min(a.length, b.length) + var i = -1 + while (++i < len) { + out += (a[i] ^ b[i]) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/browser.js new file mode 100644 index 0000000..a058a84 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/browser.js @@ -0,0 +1,11 @@ +var ciphers = require('./encrypter') +exports.createCipher = exports.Cipher = ciphers.createCipher +exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv +var deciphers = require('./decrypter') +exports.createDecipher = exports.Decipher = deciphers.createDecipher +exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv +var modes = require('./modes') +function getCiphers () { + return Object.keys(modes) +} +exports.listCiphers = exports.getCiphers = getCiphers diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/decrypter.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/decrypter.js new file mode 100644 index 0000000..b7b8bb0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/decrypter.js @@ -0,0 +1,137 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var modes = require('./modes') +var StreamCipher = require('./streamCipher') +var AuthCipher = require('./authCipher') +var ebtk = require('evp_bytestokey') + +inherits(Decipher, Transform) +function Decipher (mode, key, iv) { + if (!(this instanceof Decipher)) { + return new Decipher(mode, key, iv) + } + Transform.call(this) + this._cache = new Splitter() + this._last = void 0 + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + iv.copy(this._prev) + this._mode = mode + this._autopadding = true +} +Decipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get(this._autopadding))) { + thing = this._mode.decrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} +Decipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)) + } else if (chunk) { + throw new Error('data not multiple of block length') + } +} +Decipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} +function Splitter () { + if (!(this instanceof Splitter)) { + return new Splitter() + } + this.cache = new Buffer('') +} +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function (autoPadding) { + var out + if (autoPadding) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } + return null +} +Splitter.prototype.flush = function () { + if (this.cache.length) { + return this.cache + } +} +function unpad (last) { + var padded = last[15] + var i = -1 + while (++i < padded) { + if (last[(i + (16 - padded))] !== padded) { + throw new Error('unable to decrypt data') + } + } + if (padded === 16) { + return + } + return last.slice(0, 16 - padded) +} + +var modelist = { + ECB: require('./modes/ecb'), + CBC: require('./modes/cbc'), + CFB: require('./modes/cfb'), + CFB8: require('./modes/cfb8'), + CFB1: require('./modes/cfb1'), + OFB: require('./modes/ofb'), + CTR: require('./modes/ctr'), + GCM: require('./modes/ctr') +} + +function createDecipheriv (suite, password, iv) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + if (typeof iv === 'string') { + iv = new Buffer(iv) + } + if (typeof password === 'string') { + password = new Buffer(password) + } + if (password.length !== config.key / 8) { + throw new TypeError('invalid key length ' + password.length) + } + if (iv.length !== config.iv) { + throw new TypeError('invalid iv length ' + iv.length) + } + if (config.type === 'stream') { + return new StreamCipher(modelist[config.mode], password, iv, true) + } else if (config.type === 'auth') { + return new AuthCipher(modelist[config.mode], password, iv, true) + } + return new Decipher(modelist[config.mode], password, iv) +} + +function createDecipher (suite, password) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, config.key, config.iv) + return createDecipheriv(suite, keys.key, keys.iv) +} +exports.createDecipher = createDecipher +exports.createDecipheriv = createDecipheriv diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/encrypter.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/encrypter.js new file mode 100644 index 0000000..3d3f561 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/encrypter.js @@ -0,0 +1,122 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var modes = require('./modes') +var ebtk = require('evp_bytestokey') +var StreamCipher = require('./streamCipher') +var AuthCipher = require('./authCipher') +inherits(Cipher, Transform) +function Cipher (mode, key, iv) { + if (!(this instanceof Cipher)) { + return new Cipher(mode, key, iv) + } + Transform.call(this) + this._cache = new Splitter() + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + iv.copy(this._prev) + this._mode = mode + this._autopadding = true +} +Cipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get())) { + thing = this._mode.encrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} +Cipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + chunk = this._mode.encrypt(this, chunk) + this._cipher.scrub() + return chunk + } else if (chunk.toString('hex') !== '10101010101010101010101010101010') { + this._cipher.scrub() + throw new Error('data not multiple of block length') + } +} +Cipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + if (!(this instanceof Splitter)) { + return new Splitter() + } + this.cache = new Buffer('') +} +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function () { + if (this.cache.length > 15) { + var out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + return null +} +Splitter.prototype.flush = function () { + var len = 16 - this.cache.length + var padBuff = new Buffer(len) + + var i = -1 + while (++i < len) { + padBuff.writeUInt8(len, i) + } + var out = Buffer.concat([this.cache, padBuff]) + return out +} +var modelist = { + ECB: require('./modes/ecb'), + CBC: require('./modes/cbc'), + CFB: require('./modes/cfb'), + CFB8: require('./modes/cfb8'), + CFB1: require('./modes/cfb1'), + OFB: require('./modes/ofb'), + CTR: require('./modes/ctr'), + GCM: require('./modes/ctr') +} + +function createCipheriv (suite, password, iv) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + if (typeof iv === 'string') { + iv = new Buffer(iv) + } + if (typeof password === 'string') { + password = new Buffer(password) + } + if (password.length !== config.key / 8) { + throw new TypeError('invalid key length ' + password.length) + } + if (iv.length !== config.iv) { + throw new TypeError('invalid iv length ' + iv.length) + } + if (config.type === 'stream') { + return new StreamCipher(modelist[config.mode], password, iv) + } else if (config.type === 'auth') { + return new AuthCipher(modelist[config.mode], password, iv) + } + return new Cipher(modelist[config.mode], password, iv) +} +function createCipher (suite, password) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, config.key, config.iv) + return createCipheriv(suite, keys.key, keys.iv) +} + +exports.createCipheriv = createCipheriv +exports.createCipher = createCipher diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/ghash.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/ghash.js new file mode 100644 index 0000000..0ca143c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/ghash.js @@ -0,0 +1,98 @@ +var zeros = new Buffer(16) +zeros.fill(0) +module.exports = GHASH +function GHASH (key) { + this.h = key + this.state = new Buffer(16) + this.state.fill(0) + this.cache = new Buffer('') +} +// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html +// by Juho Vähä-Herttua +GHASH.prototype.ghash = function (block) { + var i = -1 + while (++i < block.length) { + this.state[i] ^= block[i] + } + this._multiply() +} + +GHASH.prototype._multiply = function () { + var Vi = toArray(this.h) + var Zi = [0, 0, 0, 0] + var j, xi, lsb_Vi + var i = -1 + while (++i < 128) { + xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0 + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi = xor(Zi, Vi) + } + + // Store the value of LSB(V_i) + lsb_Vi = (Vi[3] & 1) !== 0 + + // V_i+1 = V_i >> 1 + for (j = 3; j > 0; j--) { + Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) + } + Vi[0] = Vi[0] >>> 1 + + // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R + if (lsb_Vi) { + Vi[0] = Vi[0] ^ (0xe1 << 24) + } + } + this.state = fromArray(Zi) +} +GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + this.ghash(chunk) + } +} +GHASH.prototype.final = function (abl, bl) { + if (this.cache.length) { + this.ghash(Buffer.concat([this.cache, zeros], 16)) + } + this.ghash(fromArray([ + 0, abl, + 0, bl + ])) + return this.state +} + +function toArray (buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] +} +function fromArray (out) { + out = out.map(fixup_uint32) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} +var uint_max = Math.pow(2, 32) +function fixup_uint32 (x) { + var ret, x_pos + ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x + return ret +} +function xor (a, b) { + return [ + a[0] ^ b[0], + a[1] ^ b[1], + a[2] ^ b[2], + a[3] ^ b[3] + ] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/index.js new file mode 100644 index 0000000..58fa883 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/index.js @@ -0,0 +1,7 @@ +var crypto = require('crypto') + +exports.createCipher = exports.Cipher = crypto.createCipher +exports.createCipheriv = exports.Cipheriv = crypto.createCipheriv +exports.createDecipher = exports.Decipher = crypto.createDecipher +exports.createDecipheriv = exports.Decipheriv = crypto.createDecipheriv +exports.listCiphers = exports.getCiphers = crypto.getCiphers diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes.js new file mode 100644 index 0000000..c070086 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes.js @@ -0,0 +1,171 @@ +exports['aes-128-ecb'] = { + cipher: 'AES', + key: 128, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-192-ecb'] = { + cipher: 'AES', + key: 192, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-256-ecb'] = { + cipher: 'AES', + key: 256, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-128-cbc'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes-192-cbc'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes-256-cbc'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes128'] = exports['aes-128-cbc'] +exports['aes192'] = exports['aes-192-cbc'] +exports['aes256'] = exports['aes-256-cbc'] +exports['aes-128-cfb'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-192-cfb'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-256-cfb'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-128-cfb8'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-192-cfb8'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-256-cfb8'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-128-cfb1'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-192-cfb1'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-256-cfb1'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-128-ofb'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-192-ofb'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-256-ofb'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-128-ctr'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-192-ctr'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-256-ctr'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-128-gcm'] = { + cipher: 'AES', + key: 128, + iv: 12, + mode: 'GCM', + type: 'auth' +} +exports['aes-192-gcm'] = { + cipher: 'AES', + key: 192, + iv: 12, + mode: 'GCM', + type: 'auth' +} +exports['aes-256-gcm'] = { + cipher: 'AES', + key: 256, + iv: 12, + mode: 'GCM', + type: 'auth' +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cbc.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cbc.js new file mode 100644 index 0000000..b133e40 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cbc.js @@ -0,0 +1,17 @@ +var xor = require('buffer-xor') + +exports.encrypt = function (self, block) { + var data = xor(block, self._prev) + + self._prev = self._cipher.encryptBlock(data) + return self._prev +} + +exports.decrypt = function (self, block) { + var pad = self._prev + + self._prev = block + var out = self._cipher.decryptBlock(block) + + return xor(out, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb.js new file mode 100644 index 0000000..0bfe4fa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb.js @@ -0,0 +1,31 @@ +var xor = require('buffer-xor') + +exports.encrypt = function (self, data, decrypt) { + var out = new Buffer('') + var len + + while (data.length) { + if (self._cache.length === 0) { + self._cache = self._cipher.encryptBlock(self._prev) + self._prev = new Buffer('') + } + + if (self._cache.length <= data.length) { + len = self._cache.length + out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) + data = data.slice(len) + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]) + break + } + } + + return out +} +function encryptStart (self, data, decrypt) { + var len = data.length + var out = xor(data, self._cache) + self._cache = self._cache.slice(len) + self._prev = Buffer.concat([self._prev, decrypt ? data : out]) + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb1.js new file mode 100644 index 0000000..335542e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb1.js @@ -0,0 +1,34 @@ +function encryptByte (self, byteParam, decrypt) { + var pad + var i = -1 + var len = 8 + var out = 0 + var bit, value + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev) + bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 + value = pad[0] ^ bit + out += ((value & 0x80) >> (i % 8)) + self._prev = shiftIn(self._prev, decrypt ? bit : value) + } + return out +} +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = new Buffer(len) + var i = -1 + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + return out +} +function shiftIn (buffer, value) { + var len = buffer.length + var i = -1 + var out = new Buffer(buffer.length) + buffer = Buffer.concat([buffer, new Buffer([value])]) + while (++i < len) { + out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb8.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb8.js new file mode 100644 index 0000000..c967a95 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb8.js @@ -0,0 +1,15 @@ +function encryptByte (self, byteParam, decrypt) { + var pad = self._cipher.encryptBlock(self._prev) + var out = pad[0] ^ byteParam + self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])]) + return out +} +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = new Buffer(len) + var i = -1 + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ctr.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ctr.js new file mode 100644 index 0000000..0ef2278 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ctr.js @@ -0,0 +1,31 @@ +var xor = require('buffer-xor') + +function incr32 (iv) { + var len = iv.length + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } +} + +function getBlock (self) { + var out = self._cipher.encryptBlock(self._prev) + incr32(self._prev) + return out +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ecb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ecb.js new file mode 100644 index 0000000..4dd97e7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ecb.js @@ -0,0 +1,6 @@ +exports.encrypt = function (self, block) { + return self._cipher.encryptBlock(block) +} +exports.decrypt = function (self, block) { + return self._cipher.decryptBlock(block) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ofb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ofb.js new file mode 100644 index 0000000..bd87558 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/modes/ofb.js @@ -0,0 +1,16 @@ +var xor = require('buffer-xor') + +function getBlock (self) { + self._prev = self._cipher.encryptBlock(self._prev) + return self._prev +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml new file mode 100644 index 0000000..d9f695b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +before_install: + - "npm install npm -g" +node_js: + - "0.12" +env: + - TEST_SUITE=standard + - TEST_SUITE=unit +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE new file mode 100644 index 0000000..bba5218 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Daniel Cousens + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/README.md new file mode 100644 index 0000000..007f058 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/README.md @@ -0,0 +1,41 @@ +# buffer-xor + +[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-xor.png)](http://travis-ci.org/crypto-browserify/buffer-xor) +[![NPM](http://img.shields.io/npm/v/buffer-xor.svg)](https://www.npmjs.org/package/buffer-xor) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +A simple module for bitwise-xor on buffers. + + +## Examples + +``` javascript +var xor = require("buffer-xor") +var a = new Buffer('00ff0f', 'hex') +var b = new Buffer('f0f0', 'hex') + +console.log(xor(a, b)) +// => +``` + + +Or for those seeking those few extra cycles, perform the operation in place: + +``` javascript +var xorInplace = require("buffer-xor/inplace") +var a = new Buffer('00ff0f', 'hex') +var b = new Buffer('f0f0', 'hex') + +console.log(xorInplace(a, b)) +// => +// NOTE: xorInplace will return the shorter slice of its parameters + +// See that a has been mutated +console.log(a) +// => +``` + + +## License [MIT](LICENSE) + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/index.js new file mode 100644 index 0000000..85ee6f6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/index.js @@ -0,0 +1,10 @@ +module.exports = function xor (a, b) { + var length = Math.min(a.length, b.length) + var buffer = new Buffer(length) + + for (var i = 0; i < length; ++i) { + buffer[i] = a[i] ^ b[i] + } + + return buffer +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inline.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inline.js new file mode 100644 index 0000000..8797570 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inline.js @@ -0,0 +1 @@ +module.exports = require('./inplace') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js new file mode 100644 index 0000000..d71c172 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js @@ -0,0 +1,9 @@ +module.exports = function xorInplace (a, b) { + var length = Math.min(a.length, b.length) + + for (var i = 0; i < length; ++i) { + a[i] = a[i] ^ b[i] + } + + return a.slice(0, length) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/package.json new file mode 100644 index 0000000..31c573c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/package.json @@ -0,0 +1,45 @@ +{ + "name": "buffer-xor", + "version": "1.0.3", + "description": "A simple module for bitwise-xor on buffers", + "main": "index.js", + "scripts": { + "standard": "standard", + "test": "npm run-script unit", + "unit": "mocha" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/buffer-xor.git" + }, + "bugs": { + "url": "https://github.com/crypto-browserify/buffer-xor/issues" + }, + "homepage": "https://github.com/crypto-browserify/buffer-xor", + "keywords": [ + "bits", + "bitwise", + "buffer", + "buffer-xor", + "crypto", + "inline", + "math", + "memory", + "performance", + "xor" + ], + "author": { + "name": "Daniel Cousens" + }, + "license": "MIT", + "devDependencies": { + "mocha": "*", + "standard": "*" + }, + "readme": "# buffer-xor\n\n[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-xor.png)](http://travis-ci.org/crypto-browserify/buffer-xor)\n[![NPM](http://img.shields.io/npm/v/buffer-xor.svg)](https://www.npmjs.org/package/buffer-xor)\n\n[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n\nA simple module for bitwise-xor on buffers.\n\n\n## Examples\n\n``` javascript\nvar xor = require(\"buffer-xor\")\nvar a = new Buffer('00ff0f', 'hex')\nvar b = new Buffer('f0f0', 'hex')\n\nconsole.log(xor(a, b))\n// => \n```\n\n\nOr for those seeking those few extra cycles, perform the operation in place:\n\n``` javascript\nvar xorInplace = require(\"buffer-xor/inplace\")\nvar a = new Buffer('00ff0f', 'hex')\nvar b = new Buffer('f0f0', 'hex')\n\nconsole.log(xorInplace(a, b))\n// => \n// NOTE: xorInplace will return the shorter slice of its parameters\n\n// See that a has been mutated\nconsole.log(a)\n// => \n```\n\n\n## License [MIT](LICENSE)\n\n", + "readmeFilename": "README.md", + "_id": "buffer-xor@1.0.3", + "_shasum": "26e61ed1422fb70dd42e6e36729ed51d855fe8d9", + "_resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "_from": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json new file mode 100644 index 0000000..6f3431e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json @@ -0,0 +1,23 @@ +[ + { + "a": "000f", + "b": "f0ff", + "expected": "f0f0" + }, + { + "a": "000f0f", + "b": "f0ff", + "mutated": "f0f00f", + "expected": "f0f0" + }, + { + "a": "000f", + "b": "f0ffff", + "expected": "f0f0" + }, + { + "a": "000000", + "b": "000000", + "expected": "000000" + } +] diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js new file mode 100644 index 0000000..06eacab --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js @@ -0,0 +1,38 @@ +/* global describe, it */ + +var assert = require('assert') +var xor = require('../') +var xorInplace = require('../inplace') +var fixtures = require('./fixtures') + +describe('xor', function () { + fixtures.forEach(function (f) { + it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () { + var a = new Buffer(f.a, 'hex') + var b = new Buffer(f.b, 'hex') + var actual = xor(a, b) + + assert.equal(actual.toString('hex'), f.expected) + + // a/b unchanged + assert.equal(a.toString('hex'), f.a) + assert.equal(b.toString('hex'), f.b) + }) + }) +}) + +describe('xor/inplace', function () { + fixtures.forEach(function (f) { + it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () { + var a = new Buffer(f.a, 'hex') + var b = new Buffer(f.b, 'hex') + var actual = xorInplace(a, b) + + assert.equal(actual.toString('hex'), f.expected) + + // a mutated, b unchanged + assert.equal(a.toString('hex'), f.mutated || f.expected) + assert.equal(b.toString('hex'), f.b) + }) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc new file mode 100644 index 0000000..a755cdb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": ["standard"] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/index.js new file mode 100644 index 0000000..34fcae2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/index.js @@ -0,0 +1,90 @@ +var Transform = require('stream').Transform +var inherits = require('inherits') +var StringDecoder = require('string_decoder').StringDecoder +module.exports = CipherBase +inherits(CipherBase, Transform) +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + this._decoder = null + this._encoding = null +} +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = new Buffer(data, inputEnc) + } + var outData = this._update(data) + if (this.hashMode) { + return this + } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} + +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this._final()) + } catch (e) { + err = e + } finally { + done(err) + } +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this._final() || new Buffer('') + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, final) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + if (this._encoding !== enc) { + throw new Error('can\'t switch encodings') + } + var out = this._decoder.write(value) + if (final) { + out += this._decoder.end() + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/package.json new file mode 100644 index 0000000..1e71e16 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/package.json @@ -0,0 +1,39 @@ +{ + "name": "cipher-base", + "version": "1.0.2", + "description": "abstract base class for crypto-streams", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/cipher-base.git" + }, + "keywords": [ + "cipher", + "stream" + ], + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/cipher-base/issues" + }, + "homepage": "https://github.com/crypto-browserify/cipher-base#readme", + "dependencies": { + "inherits": "^2.0.1" + }, + "devDependencies": { + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "cipher-base\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base)\n\nAbstract base class to inherit from if you want to create streams implementing\nthe same api as node crypto streams.\n\nRequires you to implement 2 methods `_final` and `_update`. `_update` takes a\nbuffer and should return a buffer, `_final` takes no arguments and should return\na buffer.\n\n\nThe constructor takes one argument and that is a string which if present switches\nit into hash mode, i.e. the object you get from crypto.createHash or\ncrypto.createSign, this switches the name of the final method to be the string\nyou passed instead of `final` and returns `this` from update.\n", + "readmeFilename": "readme.md", + "_id": "cipher-base@1.0.2", + "_shasum": "54ac1d1ebdf6a1bcd3559e6f369d72697f2cab8f", + "_resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz", + "_from": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/readme.md new file mode 100644 index 0000000..db9a781 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/readme.md @@ -0,0 +1,17 @@ +cipher-base +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) + +Abstract base class to inherit from if you want to create streams implementing +the same api as node crypto streams. + +Requires you to implement 2 methods `_final` and `_update`. `_update` takes a +buffer and should return a buffer, `_final` takes no arguments and should return +a buffer. + + +The constructor takes one argument and that is a string which if present switches +it into hash mode, i.e. the object you get from crypto.createHash or +crypto.createSign, this switches the name of the final method to be the string +you passed instead of `final` and returns `this` from update. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/test.js new file mode 100644 index 0000000..57d144a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/test.js @@ -0,0 +1,108 @@ +var test = require('tape') +var CipherBase = require('./') +var inherits = require('inherits') + +test('basic version', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + return input + } + Cipher.prototype._final = function () { + // noop + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8', 'base64') + cipher.final('base64') + var string = (new Buffer(update, 'base64')).toString() + t.equals(utf8, string) + t.end() +}) +test('hash mode', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8').finalName('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('hash mode as stream', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + cipher.on('error', function (e) { + t.notOk(e) + }) + var utf8 = 'abc123abcd' + cipher.end(utf8, 'utf8') + var update = cipher.read().toString('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('encodings', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + return input + } + Cipher.prototype._final = function () { + // noop + } + t.test('mix and match encoding', function (t) { + t.plan(2) + + var cipher = new Cipher() + cipher.update('foo', 'utf8', 'utf8') + t.throws(function () { + cipher.update('foo', 'utf8', 'base64') + }) + cipher = new Cipher() + cipher.update('foo', 'utf8', 'base64') + t.doesNotThrow(function () { + cipher.update('foo', 'utf8') + cipher.final('base64') + }) + }) + t.test('handle long uft8 plaintexts', function (t) { + t.plan(1) + var txt = 'ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん' + + var cipher = new Cipher() + var decipher = new Cipher() + var enc = decipher.update(cipher.update(txt, 'utf8', 'base64'), 'base64', 'utf8') + enc += decipher.update(cipher.final('base64'), 'base64', 'utf8') + enc += decipher.final('utf8') + + t.equals(txt, enc) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/package.json new file mode 100644 index 0000000..5e83424 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/package.json @@ -0,0 +1,46 @@ +{ + "name": "browserify-aes", + "version": "1.0.6", + "description": "aes, for browserify", + "browser": "browser.js", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "standard && node test/index.js|tspec" + }, + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/browserify-aes.git" + }, + "keywords": [ + "aes", + "crypto", + "browserify" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/browserify-aes/issues" + }, + "homepage": "https://github.com/crypto-browserify/browserify-aes", + "dependencies": { + "buffer-xor": "^1.0.2", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "inherits": "^2.0.1" + }, + "devDependencies": { + "standard": "^3.7.3", + "tap-spec": "^1.0.0", + "tape": "^3.0.0" + }, + "readme": "browserify-aes\n====\n\n[![Build Status](https://travis-ci.org/crypto-browserify/browserify-aes.svg)](https://travis-ci.org/crypto-browserify/browserify-aes)\n\nNode style aes for use in the browser. Implements:\n\n - createCipher\n - createCipheriv\n - createDecipher\n - createDecipheriv\n - getCiphers\n\nIn node.js, the `crypto` implementation is used, in browsers it falls back to a pure JavaScript implementation.\n\nMuch of this library has been taken from the aes implementation in [triplesec](https://github.com/keybase/triplesec), a partial derivation of [crypto-js](https://code.google.com/p/crypto-js/).\n\n`EVP_BytesToKey` is a straight up port of the same function from OpenSSL as there is literally no documenation on it beyond it using 'undocumented extensions' for longer keys.\n", + "readmeFilename": "readme.md", + "_id": "browserify-aes@1.0.6", + "_shasum": "5e7725dbdef1fd5930d4ebab48567ce451c48a0a", + "_resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz", + "_from": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/populateFixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/populateFixtures.js new file mode 100644 index 0000000..ac31eb3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/populateFixtures.js @@ -0,0 +1,25 @@ +var modes = require('./modes') +var fixtures = require('./test/fixtures.json') +var crypto = require('crypto') +var types = ['aes-128-cfb1', 'aes-192-cfb1', 'aes-256-cfb1'] +var ebtk = require('./EVP_BytesToKey') +var fs = require('fs') + +fixtures.forEach(function (fixture) { + types.forEach(function (cipher) { + var suite = crypto.createCipher(cipher, new Buffer(fixture.password)) + var buf = new Buffer('') + buf = Buffer.concat([buf, suite.update(new Buffer(fixture.text))]) + buf = Buffer.concat([buf, suite.final()]) + fixture.results.ciphers[cipher] = buf.toString('hex') + if (modes[cipher].mode === 'ECB') { + return + } + var suite2 = crypto.createCipheriv(cipher, ebtk(crypto, fixture.password, modes[cipher].key).key, new Buffer(fixture.iv, 'hex')) + var buf2 = new Buffer('') + buf2 = Buffer.concat([buf2, suite2.update(new Buffer(fixture.text))]) + buf2 = Buffer.concat([buf2, suite2.final()]) + fixture.results.cipherivs[cipher] = buf2.toString('hex') + }) +}) +fs.writeFileSync('./test/fixturesNew.json', JSON.stringify(fixtures, false, 4)) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/readme.md new file mode 100644 index 0000000..1d7b085 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/readme.md @@ -0,0 +1,18 @@ +browserify-aes +==== + +[![Build Status](https://travis-ci.org/crypto-browserify/browserify-aes.svg)](https://travis-ci.org/crypto-browserify/browserify-aes) + +Node style aes for use in the browser. Implements: + + - createCipher + - createCipheriv + - createDecipher + - createDecipheriv + - getCiphers + +In node.js, the `crypto` implementation is used, in browsers it falls back to a pure JavaScript implementation. + +Much of this library has been taken from the aes implementation in [triplesec](https://github.com/keybase/triplesec), a partial derivation of [crypto-js](https://code.google.com/p/crypto-js/). + +`EVP_BytesToKey` is a straight up port of the same function from OpenSSL as there is literally no documenation on it beyond it using 'undocumented extensions' for longer keys. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/streamCipher.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/streamCipher.js new file mode 100644 index 0000000..a55c762 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/browserify-aes/streamCipher.js @@ -0,0 +1,25 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') + +inherits(StreamCipher, Transform) +module.exports = StreamCipher +function StreamCipher (mode, key, iv, decrypt) { + if (!(this instanceof StreamCipher)) { + return new StreamCipher(mode, key, iv) + } + Transform.call(this) + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + this._cache = new Buffer('') + this._secCache = new Buffer('') + this._decrypt = decrypt + iv.copy(this._prev) + this._mode = mode +} +StreamCipher.prototype._update = function (chunk) { + return this._mode.encrypt(this, chunk, this._decrypt) +} +StreamCipher.prototype._final = function () { + this._cipher.scrub() +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/index.js new file mode 100644 index 0000000..25fbc9c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/index.js @@ -0,0 +1,68 @@ +var md5 = require('create-hash/md5') +module.exports = EVP_BytesToKey +function EVP_BytesToKey (password, salt, keyLen, ivLen) { + if (!Buffer.isBuffer(password)) { + password = new Buffer(password, 'binary') + } + if (salt && !Buffer.isBuffer(salt)) { + salt = new Buffer(salt, 'binary') + } + keyLen = keyLen / 8 + ivLen = ivLen || 0 + var ki = 0 + var ii = 0 + var key = new Buffer(keyLen) + var iv = new Buffer(ivLen) + var addmd = 0 + var md_buf + var i + var bufs = [] + while (true) { + if (addmd++ > 0) { + bufs.push(md_buf) + } + bufs.push(password) + if (salt) { + bufs.push(salt) + } + md_buf = md5(Buffer.concat(bufs)) + bufs = [] + i = 0 + if (keyLen > 0) { + while (true) { + if (keyLen === 0) { + break + } + if (i === md_buf.length) { + break + } + key[ki++] = md_buf[i] + keyLen-- + i++ + } + } + if (ivLen > 0 && i !== md_buf.length) { + while (true) { + if (ivLen === 0) { + break + } + if (i === md_buf.length) { + break + } + iv[ii++] = md_buf[i] + ivLen-- + i++ + } + } + if (keyLen === 0 && ivLen === 0) { + break + } + } + for (i = 0; i < md_buf.length; i++) { + md_buf[i] = 0 + } + return { + key: key, + iv: iv + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/package.json new file mode 100644 index 0000000..66f2e69 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/package.json @@ -0,0 +1,40 @@ +{ + "name": "evp_bytestokey", + "version": "1.0.0", + "description": "he super secure key derivation algorithm from openssl", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/EVP_BytesToKey.git" + }, + "keywords": [ + "crypto", + "openssl" + ], + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/EVP_BytesToKey/issues" + }, + "homepage": "https://github.com/crypto-browserify/EVP_BytesToKey", + "dependencies": { + "create-hash": "^1.1.1" + }, + "devDependencies": { + "standard": "^5.3.1", + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "EVP_BytesToKey\n===\n\nThe super secure [key derivation algorithm from openssl](https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3)) (spoiler alert not actually secure, only every use it for compatibility reasons).\n\nApi:\n===\n\n```js\nvar result = EVP_BytesToKey('password', 'salt', keyLen, ivLen);\nBuffer.isBuffer(result.password); // true\nBuffer.isBuffer(result.iv); // true\n```\n", + "readmeFilename": "readme.md", + "_id": "evp_bytestokey@1.0.0", + "_shasum": "497b66ad9fef65cd7c08a6180824ba1476b66e53", + "_resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz", + "_from": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/readme.md new file mode 100644 index 0000000..86234db --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/readme.md @@ -0,0 +1,13 @@ +EVP_BytesToKey +=== + +The super secure [key derivation algorithm from openssl](https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3)) (spoiler alert not actually secure, only every use it for compatibility reasons). + +Api: +=== + +```js +var result = EVP_BytesToKey('password', 'salt', keyLen, ivLen); +Buffer.isBuffer(result.password); // true +Buffer.isBuffer(result.iv); // true +``` diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/test.js new file mode 100644 index 0000000..a638fa0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/node_modules/evp_bytestokey/test.js @@ -0,0 +1,19 @@ +var test = require('tape') +var evp = require('./') +var crypto = require('crypto') + +function runTest (password) { + test('password: ' + password, function (t) { + t.plan(1) + var keys = evp(password, false, 256, 16) + var nodeCipher = crypto.createCipher('aes-256-ctr', password) + var ourCipher = crypto.createCipheriv('aes-256-ctr', keys.key, keys.iv) + var nodeOut = nodeCipher.update('foooooo') + var ourOut = ourCipher.update('foooooo') + t.equals(nodeOut.toString('hex'), ourOut.toString('hex')) + }) +} +runTest('password') +runTest('ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん') +runTest('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞') +runTest('💩') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/package.json new file mode 100644 index 0000000..bc3c4e6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/package.json @@ -0,0 +1,38 @@ +{ + "name": "parse-asn1", + "version": "5.0.0", + "description": "[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/parse-asn1.png)](http://travis-ci.org/crypto-browserify/parse-asn1) [![NPM](http://img.shields.io/npm/v/parse-asn1.svg)](https://www.npmjs.org/package/parse-asn1)", + "main": "index.js", + "scripts": { + "unit": "node ./test", + "standard": "standard", + "test": "npm run standard && npm run unit" + }, + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/parse-asn1.git" + }, + "author": "", + "license": "ISC", + "dependencies": { + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3" + }, + "devDependencies": { + "tape": "^3.4.0", + "standard": "^5.0.0" + }, + "readme": "#parse-asn1\n\n[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/parse-asn1.png)](http://travis-ci.org/crypto-browserify/parse-asn1)\n[![NPM](http://img.shields.io/npm/v/parse-asn1.svg)](https://www.npmjs.org/package/parse-asn1)\n\n[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n\nutility library for parsing asn1 files for use with browserify-sign.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/crypto-browserify/parse-asn1/issues" + }, + "homepage": "https://github.com/crypto-browserify/parse-asn1#readme", + "_id": "parse-asn1@5.0.0", + "_shasum": "35060f6d5015d37628c770f4e091a0b5a278bc23", + "_resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.0.0.tgz", + "_from": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/1024.priv new file mode 100644 index 0000000..7206216 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/1024.priv @@ -0,0 +1,16 @@ +-----BEGIN PRIVATE KEY----- +MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKulUTZ8B1qccZ8c +DXRGSY08gW8KvLlcxxxGC4gZHNT3CBUF8n5R4KE30aZyYZ/rtsQZu05juZJxaJ0q +mbe75dlQ5d+Xc9BMXeQg/MpTZw5TAN7OIdGYYpFBe+1PLZ6wEfjkYrMqMUcfq2Lq +hTLdAbvBJnuRcYZLqmBeOQ8FTrKrAgMBAAECgYEAnkHRbEPU3/WISSQrP36iyCb2 +S/SBZwKkzmvCrBxDWhPeDswp9c/2JY76rNWfLzy8iXgUG8WUzvHje61Qh3gmBcKe +bUaTGl4Vy8Ha1YBADo5RfRrdm0FE4tvgvu/TkqFqpBBZweu54285hk5zlG7n/D7Y +dnNXUpu5MlNb5x3gW0kCQQDUL//cwcXUxY/evaJP4jSe+ZwEQZo+zXRLiPUulBoV +aw28CVMuxdgwqAo1X1IKefPeUaf7RQu8gCKaRnpGuEuXAkEAzxZTfMmvmCUDIew4 +5Gk6bK265XQWdhcgiq254lpBGOYmDj9yCE7yA+zmASQwMsXTdQOi1hOCEyrXuSJ5 +c++EDQJAFh3WrnzoEPByuYXMmET8tSFRWMQ5vpgNqh3haHR5b4gUC2hxaiunCBNL +1RpVY9AoUiDywGcG/SPh93CnKB3niwJBAKP7AtsifZgVXtiizB4aMThTjVYaSZrz +D0Kg9DuHylpkDChmFu77TGrNUQgAVuYtfhb/bRblVa/F0hJ4eQHT3JUCQBVT68tb +OgRUk0aP9tC3021VN82X6+klowSQN8oBPX8+TfDWSUilp/+j24Hky+Z29Do7yR/R +qutnL92CvBlVLV4= +-----END PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/1024.pub new file mode 100644 index 0000000..2dba785 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/1024.pub @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrpVE2fAdanHGfHA10RkmNPIFv +Cry5XMccRguIGRzU9wgVBfJ+UeChN9GmcmGf67bEGbtOY7mScWidKpm3u+XZUOXf +l3PQTF3kIPzKU2cOUwDeziHRmGKRQXvtTy2esBH45GKzKjFHH6ti6oUy3QG7wSZ7 +kXGGS6pgXjkPBU6yqwIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.1024.priv new file mode 100644 index 0000000..1145b7d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.1024.priv @@ -0,0 +1,18 @@ +-----BEGIN DSA PARAMETERS----- +MIIBHgKBgQDdFg3WQmpOZxObxraIe4rrbUhrBw99fbnz99IvLj60sM/7Uk7eHYvp +UrPaJBIcjPy68BjV4ekDljuPpFoAorsLzyvVSHuNvN6I/bRGm1TCOjDFVe98Oz6k +XmI6pRfIF0TiIPXkel/sWIfBYa1lqdoW82h9FIjhbxVHrKGfvMEc9wIVAOzmJHec +s6yBm+nE3+OmpWFYj0ylAoGAYxO6mFSoIY7PDRyRzKJEnULSzYXd3FoMkPwDCd5I +ch/piIoAUIIQ542TL54GT9wuiCL+0D48qi9GWKasPZABfPQ008WOzmKzD8ncrUTd +a7pzvUvdmwldA4Aa5/5xSXwtpK+DDye7KPlu+oi1BF6uj4TgfeGr1uxouxC2WhBE +qH0= +-----END DSA PARAMETERS----- +-----BEGIN PRIVATE KEY----- +MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAOY0KsTt5EpJ4LtlD3xRS5mDiGE1 +CMNp0S9X0sK8kP8Aps8iYwMLbZYglk18GCNnCk4SjbAnZHSB3kaIv6AKQc2J8W2Y +V5se3VhpKOFst7bqRtkGsl8uJtGlKTiXNclkv2jsKOrsBokSD1USGCECTNeMt3Og +ziRcZ1dS+djSOZ2nAhUAzB96SpxlAak+K/QLVJ+lDe5DcY0CgYEAtxX1/Hckvhlh +HQyKZWLQsDfZBILbhc+OLDpOyT6cJS/sJzfFIYZgK5M3rOS4OmzdYfJccQAuGq+T +VJQ3VcYOdbrIANJV8CDrn4jkkejTzJI6fCwAkPWOyxw8kbV1Hsoy6WLfSCHKpBUc +rogAqRGESqBVTawjyF/ECX667y/P49MEFgIUSeRVRgAXsLmeWR/V4Rh9Hex+9+s= +-----END PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.1024.pub new file mode 100644 index 0000000..80a731e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.1024.pub @@ -0,0 +1,12 @@ +-----BEGIN PUBLIC KEY----- +MIIBtzCCASwGByqGSM44BAEwggEfAoGBAOY0KsTt5EpJ4LtlD3xRS5mDiGE1CMNp +0S9X0sK8kP8Aps8iYwMLbZYglk18GCNnCk4SjbAnZHSB3kaIv6AKQc2J8W2YV5se +3VhpKOFst7bqRtkGsl8uJtGlKTiXNclkv2jsKOrsBokSD1USGCECTNeMt3OgziRc +Z1dS+djSOZ2nAhUAzB96SpxlAak+K/QLVJ+lDe5DcY0CgYEAtxX1/HckvhlhHQyK +ZWLQsDfZBILbhc+OLDpOyT6cJS/sJzfFIYZgK5M3rOS4OmzdYfJccQAuGq+TVJQ3 +VcYOdbrIANJV8CDrn4jkkejTzJI6fCwAkPWOyxw8kbV1Hsoy6WLfSCHKpBUcrogA +qRGESqBVTawjyF/ECX667y/P49MDgYQAAoGAXYmxO4+52C1gBzh7GgTwNLJl7bLn +gOhKTFlKhT36VjMjeFfdXmBVBVbfUottKZby/gVX1IXT38PStB/dswbF45bGDdoS +zMFjYmHTtLtrU/4hReVtvb5MYmrPDFX58SwcSRRO/cH6WJPvfu4Aq0cJZA9Kb0B9 +5Wo18JxAqvPtTB8= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.2048.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.2048.priv new file mode 100644 index 0000000..2a77c2e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.2048.priv @@ -0,0 +1,20 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIDVQIBAAKCAQEA0jDs9lLWX//NXYE1kNKw4UiDVMHHEtTF1OzJvBJvUh3/xMlU +ic8mUpIMU5mt7BTjcijyLLl/TeNBcI/xDvWH3PAfCjP1CmNzOMHwU6wKA4Q20m5v +zjauVycd7loRm5h+1XyD2JL1KmQTzhIIRAmRTeXMnr8LAHidYfUKmzCOCCrnctlE +EOh1S6e7BFxQBRrlUxZF0LTjcAz31rrjIH6wKkYR4mnpGuI2vVJ+qHGmEhvq1hAb +DvP0GN0iofxHlIVqOlfXYCZO388ZabfcBOQG57tTofm8aS4pnXCgbok9wEYPgbU5 +n6fEvDGOOObQyY109hZZaDJmfygr5mmD0TIXrQIhAMVBhV4liqAN2MrT/+ZUH6hY ++DhTazzSNLIZKQ5gfd+1AoIBADqHGUVQa9pbwyjbzooeWdijUM9W5P7UUj1OjrA0 +HIkcx37qHiYOVFqHpbjDs3tbgRBxBX5zBpwuhywC/6OetDiqzDy7zZCV/YMn06d2 +ncW2Ctjp3KPl7of39+HgXXePgTdKcfkjH9upJQTko88rA4NWwZbHYeA3Lv7DcA11 +XY3+TQHcxMtxf/E6aePjANJBsJsQjYLy3WyUiS87jkgi0Bigjg/cD3Nel4LToCTR +JvQ4m3w3T4W0xL1+8nPjRZ2q0GgmxZzPfwALrwiSYMgGZC/ov43wqOs6WXs0NnpJ +moU4oxutC/uDvTZmJvRj77FINjK0ZA20jmNvWmTIeEm1Xn4CggEABeRpOymQS5IS +X+u9ya7C+P3MPIRGm4dcWPWgPpD1QcclNYLGnhRp7JazNsbbPMjnx1qtF+2qjfy9 +JDeWTAR8qfCNVmQHPAhJsJtV0C/V4PUii71FRNPVC3EAYbcBk8deMGoUg99cxSac +6MCxIIOxuUKWpw8XPlMVpuXc8+lIMTYCPeLGinmT4DQ573t0MS6U3Ck/987xjkH9 +sos7zcYn3vnjywDCxXMidC0eUK1rxAAuY7PL4vQiKwXq8kFtWiKAnns/Zm5LTjiZ +NrwlhNlU2wQVvyIcKaGfSRPheb69IbP+9qp5b7Xe7DNWdo48S0jl2KAFeZ91BnhM +TH6WPtMpjQIgOaTTn6xYK0kZvvH3lZXrzkjp4aNlNY65R0JAKKNsx3s= +-----END DSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.2048.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.2048.pub new file mode 100644 index 0000000..9f6cac1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/dsa.2048.pub @@ -0,0 +1,20 @@ +-----BEGIN PUBLIC KEY----- +MIIDRjCCAjkGByqGSM44BAEwggIsAoIBAQDSMOz2UtZf/81dgTWQ0rDhSINUwccS +1MXU7Mm8Em9SHf/EyVSJzyZSkgxTma3sFONyKPIsuX9N40Fwj/EO9Yfc8B8KM/UK +Y3M4wfBTrAoDhDbSbm/ONq5XJx3uWhGbmH7VfIPYkvUqZBPOEghECZFN5cyevwsA +eJ1h9QqbMI4IKudy2UQQ6HVLp7sEXFAFGuVTFkXQtONwDPfWuuMgfrAqRhHiaeka +4ja9Un6ocaYSG+rWEBsO8/QY3SKh/EeUhWo6V9dgJk7fzxlpt9wE5Abnu1Oh+bxp +LimdcKBuiT3ARg+BtTmfp8S8MY445tDJjXT2FlloMmZ/KCvmaYPRMhetAiEAxUGF +XiWKoA3YytP/5lQfqFj4OFNrPNI0shkpDmB937UCggEAOocZRVBr2lvDKNvOih5Z +2KNQz1bk/tRSPU6OsDQciRzHfuoeJg5UWoeluMOze1uBEHEFfnMGnC6HLAL/o560 +OKrMPLvNkJX9gyfTp3adxbYK2Onco+Xuh/f34eBdd4+BN0px+SMf26klBOSjzysD +g1bBlsdh4Dcu/sNwDXVdjf5NAdzEy3F/8Tpp4+MA0kGwmxCNgvLdbJSJLzuOSCLQ +GKCOD9wPc16XgtOgJNEm9DibfDdPhbTEvX7yc+NFnarQaCbFnM9/AAuvCJJgyAZk +L+i/jfCo6zpZezQ2ekmahTijG60L+4O9NmYm9GPvsUg2MrRkDbSOY29aZMh4SbVe +fgOCAQUAAoIBAAXkaTspkEuSEl/rvcmuwvj9zDyERpuHXFj1oD6Q9UHHJTWCxp4U +aeyWszbG2zzI58darRftqo38vSQ3lkwEfKnwjVZkBzwISbCbVdAv1eD1Iou9RUTT +1QtxAGG3AZPHXjBqFIPfXMUmnOjAsSCDsblClqcPFz5TFabl3PPpSDE2Aj3ixop5 +k+A0Oe97dDEulNwpP/fO8Y5B/bKLO83GJ97548sAwsVzInQtHlCta8QALmOzy+L0 +IisF6vJBbVoigJ57P2ZuS044mTa8JYTZVNsEFb8iHCmhn0kT4Xm+vSGz/vaqeW+1 +3uwzVnaOPEtI5digBXmfdQZ4TEx+lj7TKY0= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.pass.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.pass.priv new file mode 100644 index 0000000..bf1836d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.pass.priv @@ -0,0 +1,7 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIHeMEkGCSqGSIb3DQEFDTA8MBsGCSqGSIb3DQEFDDAOBAi9LqZQx4JFXAICCAAw +HQYJYIZIAWUDBAECBBA+js1fG4Rv/yRN7oZvxbgyBIGQ/D4yj86M1x8lMsnAHQ/K +7/ryb/baDNHqN9LTZanEGBuyxgrTzt08SiL+h91yFGMoaly029K1VgEI8Lxu5Np/ +A+LK7ewh73ABzsbuxYdcXI+rKnrvLN9Tt6veDs4GlqTTsWwq5wF0C+6gaYRBXA74 +T1b6NykGh2UNL5U5pHZEYdOVLz+lRJL7gYqlweNHP/S3 +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.priv new file mode 100644 index 0000000..25fffbd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.priv @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHQCAQEEIDF6Xv8Sv//wGUWD+c780ppGrU0QdZWCAzxAQPQX8r/uoAcGBSuBBAAK +oUQDQgAEIZeowDylls4K/wfBjO18bYo7gGx8nYQRija4e/qEMikOHJai7geeUreU +r5Xky/Ax7s2dGtegsPNsPgGe5MpQvg== +-----END EC PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.pub new file mode 100644 index 0000000..2e39e5b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/ec.pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEIZeowDylls4K/wfBjO18bYo7gGx8nYQR +ija4e/qEMikOHJai7geeUreUr5Xky/Ax7s2dGtegsPNsPgGe5MpQvg== +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/index.js new file mode 100644 index 0000000..4d16030 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/index.js @@ -0,0 +1,92 @@ +var test = require('tape') +var fs = require('fs') +var parseKey = require('../') +var crypto = require('crypto') +var rsa1024 = { + private: fs.readFileSync(__dirname + '/rsa.1024.priv'), + public: fs.readFileSync(__dirname + '/rsa.1024.pub') +} +var rsa2028 = { + private: fs.readFileSync(__dirname + '/rsa.2028.priv'), + public: fs.readFileSync(__dirname + '/rsa.2028.pub') +} +var nonrsa1024 = { + private: fs.readFileSync(__dirname + '/1024.priv'), + public: fs.readFileSync(__dirname + '/1024.pub') +} +var pass1024 = { + private: { + passphrase: 'fooo', + key: fs.readFileSync(__dirname + '/pass.1024.priv') + }, + public: fs.readFileSync(__dirname + '/pass.1024.pub') +} +var ec = { + private: fs.readFileSync(__dirname + '/ec.priv'), + public: fs.readFileSync(__dirname + '/ec.pub') +} +var ecpass = { + private: { + key: fs.readFileSync(__dirname + '/ec.pass.priv'), + passphrase: 'bard' + }, + public: fs.readFileSync(__dirname + '/ec.pub') +} +var dsa = { + private: fs.readFileSync(__dirname + '/dsa.1024.priv'), + public: fs.readFileSync(__dirname + '/dsa.1024.pub') +} +var dsa2 = { + private: fs.readFileSync(__dirname + '/dsa.2048.priv'), + public: fs.readFileSync(__dirname + '/dsa.2048.pub') +} +var dsapass = { + private: { + key: fs.readFileSync(__dirname + '/pass.dsa.1024.priv'), + passphrase: 'password' + }, + public: fs.readFileSync(__dirname + '/pass.dsa.1024.pub') +} +var dsapass2 = { + private: { + key: fs.readFileSync(__dirname + '/pass2.dsa.1024.priv'), + passphrase: 'password' + }, + public: fs.readFileSync(__dirname + '/pass2.dsa.1024.pub') +} +var rsapass = { + private: { + key: fs.readFileSync(__dirname + '/pass.rsa.1024.priv'), + passphrase: 'password' + }, + public: fs.readFileSync(__dirname + '/pass.rsa.1024.pub') +} +var rsapass2 = { + private: { + key: fs.readFileSync(__dirname + '/pass.rsa.2028.priv'), + passphrase: 'password' + }, + public: fs.readFileSync(__dirname + '/pass.rsa.2028.pub') +} +var i = 0 +function testIt (keys) { + test('key ' + (++i), function (t) { + t.plan(2) + t.ok(parseKey(keys.public, crypto), 'public key') + t.ok(parseKey(keys.private, crypto), 'private key') + }) +} + +testIt(dsa) +testIt(dsa2) +testIt(rsa1024) +testIt(ec) +testIt(rsa2028) +testIt(nonrsa1024) +testIt(ecpass) +testIt(dsapass) +testIt(dsapass2) +testIt(rsapass) +testIt(rsapass2) +testIt(pass1024) +testIt(pass1024) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.1024.priv new file mode 100644 index 0000000..b9f3884 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.1024.priv @@ -0,0 +1,18 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIICzzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQIji3ZZ6JbsA4CAggA +MB0GCWCGSAFlAwQBFgQQC6MKblq8zyX90/KmgotsMQSCAoDghNf+yxPC/KRh7F3O +k0lMgtDkV+wCLDv7aBvUqy8Ry2zqFPIlfLb8XtSW943XEu6KUI13IZPEr8p9h1ve +Iye6L0g6uAgbFxBE2DwBBSI7mYr7lokr4v0k+inMKf4JeRdI9XWgwOILKTGf1vH7 +PhvBnqLhOg6BIOuF426qpiyYlmRda74d0Th4o6ZyhyMSzPI1XbWSg719Ew3N/tLe +OHdYl0eFrgNjq+xO4Ev+W7eNIh/XBMQtk9wo+mxeNdldRnX822HxTsL8fSSPs+9T +W5M/2EBTJMSsswSjZyFkq8ehtxovI2u0IBX1IiPulyUZLnSNPDV1eUVClK6rk+q1 +kVsfJhUr2qvIjNlQWlbEXQj4VwGtgl0++l8vdpj59MuN2J3Nx5TNMLjA6BYAa/tr +Bu928QoT7ET+SGx5XKCwKb5fwXmDlV5zZC4kZWTaF/d/Icvj5F+fDZuYFg1JOXNZ ++q2oA1qMYaHGX6lF3pbO84ebg1iwQTDM8iIqFeSMGUJTnk/3a7sqfaWQbEQwGb+X +fXnSTwkF+wO2rriPbFvWyzecWu67zDCP0ZWUgGb86sSJCM7xRGShESwCjOrb88F1 +5SZjyIqogrkc3IWiLH9gc5U8d86qoFjJnP6BfwYks1UIyXNGKfZTCqICpMphV+IS +b0N2jprjLTkWR6nxYGSH1bkKMs7x1M0FBLWWLAZqPn9X3pe6JwIBds04O6XjF0un +oxwDjcJdoxVs7PgRiM5d1Tubqu2zmpCCmXNiqi9B0+rV9/jHg9IA5gUfvYdCcEv+ +oAr90I+2+PuBFa9lgdbDV6DtZk4bSYluqamxVeLPg/vrewYfVfDv6jftfY1D0DEy +69H0 +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.1024.pub new file mode 100644 index 0000000..617e7fb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.1024.pub @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSK/7i5BV0x+gmX16Wrm7kRkCZ +y1QUt6wiM2g+SAZTYR0381VnSMX2cv7CpN3499lZj1rL5S7YTaZZwX3RvU5fz56/ +eDX6ciL/PZsbclN2KdkMWYgmcb9J1zUeoMQ3cjfFUCdQZ/ZvDWa+wY2Zg8os2Bow +AoufHtYHm3eOly/cWwIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.dsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.dsa.1024.priv new file mode 100644 index 0000000..aab5fc2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.dsa.1024.priv @@ -0,0 +1,11 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIBnzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQI1z4IJORFws4CAggA +MB0GCWCGSAFlAwQBAgQQq7f0CuKCTITfPS5Xax1H4wSCAVDFyIjYVXfBNe+BARqz +Tfo09y4vKkErOb7Sz4bQkAjRLjOXiUjM4eTNtivml8NqVrQTKAghN+ggxj416OD4 +oq6Ns7Ncbd4Xm5Ni8wrrWbJxVog6rAa/ioU0sfgRExYy/xE2Q9KkW+VE7SUwanwY +e81Od9qNM5KhZGM1yUSKa0JA6Xqb8dAqBo9rVt8DceumB9OP83xV3fLEimSZfR6p +slA1P/dTvKxwhpguQe4Z3OkzTzGCxyboqeRW1woNHKbxjzzSHcaki9SHQm3xpUW8 +hRAJd6OtDnLbkE9MnC+UcI3mjru1xfnR5MU7qG7e9nvOhEDVaDkiK3DbrSf0B0Bi +p1hyX1XsSXDewSEd/mlfMLdD8WecgUtl9ea7JzxY3/6R78yB951I5TmY45mp/v+N +tbxEv29B65UKf0ac7gVw4LNy8JF2ef/L/meEmBoIAE71f+8= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.dsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.dsa.1024.pub new file mode 100644 index 0000000..80a731e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.dsa.1024.pub @@ -0,0 +1,12 @@ +-----BEGIN PUBLIC KEY----- +MIIBtzCCASwGByqGSM44BAEwggEfAoGBAOY0KsTt5EpJ4LtlD3xRS5mDiGE1CMNp +0S9X0sK8kP8Aps8iYwMLbZYglk18GCNnCk4SjbAnZHSB3kaIv6AKQc2J8W2YV5se +3VhpKOFst7bqRtkGsl8uJtGlKTiXNclkv2jsKOrsBokSD1USGCECTNeMt3OgziRc +Z1dS+djSOZ2nAhUAzB96SpxlAak+K/QLVJ+lDe5DcY0CgYEAtxX1/HckvhlhHQyK +ZWLQsDfZBILbhc+OLDpOyT6cJS/sJzfFIYZgK5M3rOS4OmzdYfJccQAuGq+TVJQ3 +VcYOdbrIANJV8CDrn4jkkejTzJI6fCwAkPWOyxw8kbV1Hsoy6WLfSCHKpBUcrogA +qRGESqBVTawjyF/ECX667y/P49MDgYQAAoGAXYmxO4+52C1gBzh7GgTwNLJl7bLn +gOhKTFlKhT36VjMjeFfdXmBVBVbfUottKZby/gVX1IXT38PStB/dswbF45bGDdoS +zMFjYmHTtLtrU/4hReVtvb5MYmrPDFX58SwcSRRO/cH6WJPvfu4Aq0cJZA9Kb0B9 +5Wo18JxAqvPtTB8= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.1024.priv new file mode 100644 index 0000000..b67bd80 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.1024.priv @@ -0,0 +1,18 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-192-CBC,04D2D7882E0C474E07E542FE997D2A49 + +vfB5Gtm34n3SeI6JELjWiGw6O+j+tGR6Wbi3SNeAZkfSA8PTjei6PVHr+dGK5zMd +nTckd0EpxItqxEdtLK6GtBIa9KRd3cEbayHmyyybH2FC4STXJCUFBe2eb7ZKmnCl +RB5FcmAqExif+QOJwHnZw6DTzq+oGSwi9cSoy2qE62FgXkj8uKAYcBLONmsP1YQA +4zIub4bnEbIghL/swEB/HVS86FyMCsMXrHEOnSuUUBf/UfZFNypI6kVUNXlItnN1 +14eeRsBD37VkL7dAQPMx+Dwm7DbU07QWrVvzgmWlu3KqR0tRNA9e4a5f14XOYxgS +HZ+XVZK8iAd+76OnprlFtGDowDXGM0wUXPYq5j8WpKxNsVs2RV+S6U0gQLoSqNxt +We7UPWZufzEdjTUO8q9KhdGqFmJ53XIYClZf0bp148b+Bk3P+dN5TbmKQEfulScn +rTLTRo34fdTIAJr5BJh0OXGNs9rFlMJ9Nz4FwVTEB1DMerXtt9ICdhud9BktRhvq +axgoz+XA3LrBrlPPcrSCZyIYjZFydGSkzg439OyDEZ6+uRmc0qhWA4j6AgXx6gGR +NvvypoFVKvXqEq/2F+SVyyMGrm4xPmsr/HUBeE9SmuTzNzDfVAM/xerqIoR2szR0 +O0hwtOj4fk7//cd1CjFzd0JiF/SqMkHxkdbmIC9qlhshkWlQbvvhbefodYPuGxmj +L1TaPgX36OcrQSodzyWBN5tSmmX1Nmftcz7iwc4AKrqkdnM3sPS3SczsAjMWrjRr +7iYhdPQSZtxVCTjACU3h7scNAg9AU6l4YZrowR//J6U= +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.1024.pub new file mode 100644 index 0000000..3506c33 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.1024.pub @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGcMA0GCSqGSIb3DQEBAQUAA4GKADCBhgJ/OwswbFo/uyC8ltGf/yA1A+gV5IGd +nAgPbUSI3GzbHCA+x+TLG/tLvbRw3r1smppY/jkkpiVW1ErSMuN0uixp5gb78Z9r +H1XpWb5WWgp3WaY/9EHMjMdOkQ/9LVZvRvl/M/Fi6owP+q+amJI1BEjECYfbhGL3 +rmlVdq4qXc40QwIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.2028.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.2028.priv new file mode 100644 index 0000000..99e8213 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.2028.priv @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-256-CBC,7A6A055AD675947A657041422F06D439 + +HQdjzAKUuqqKhZHmpzzY/monfqFhiHnZ5c24jtR9fM4aQJXf/e1fz6MEhyIz6XON +sb4CnXZstnxUuVWDkHEu6KWQ/dKALgiDUuT+UdMawVoVPGdgyWZp35pQPWi3fT2V +XZn58YkG8bO3Y403eZPyhadOefD1VtuFuK6/f90jjzx6ZDnwveXpYgFV7Jy1/pFd +cLLMf07C+hbk416nX6UVipWe4GH+ADFom5ZCfAaUotM7n8i149dULNF4YYi2wP31 +1YaDH5vf1CqiaieDY7xLzpEixwJz6ZEg3gLXaUvz2MpF8owiGI3eP0g7voWp3xt4 +TQx/qDURlaXiaRriWdWtpKyW1MFuJ5+KdNtR1/kXr2BLPB/ZLwyqtynUy8ZYpb4+ +WIRYpUGeb//ZHGhlCH7CRMdABsal4wTwnzi9fW4Ax96ecJ2SlwCuKxwS7iEq2y1/ +FAfGwsE+XufHhme5p6XjKfiHx+zJMIB2NMkrm+wm4PbMTrGVnw5/41/r6XxOB8fe +iKi12Jth4dusc1vYGYfzKop9uEM6CZ6+Chqzb+Zyh/xUiZVlCX/BYnxr7yXUm9aR +PHQgxkn2Act8FgQB3Kgs3jCiCRIJrlsnybeWzQ3YO9TjC4MxygmmwODDBpsOKnEi +kXXS54+cZFjcsva4uJVwhAywRPVUkLzmTkH0tGiwCHjeQNECm+TLahkkEIXrVTb9 +c9creNXMgE6jVVz+R43HXsGvTcgMcBLyFRQJe2nVaj/dQ5JbF4uqNnQzRjAbD34K +uTpFaJ/kmlgcmeScRLnwaoYwFlmhSC+bK0dfY1Jr6AQRA6IDP7nIjqWNDCHNBB8r +Qj1v2KWoVQe3xNHaXhkbJPbA2DKlUIqffkBVtMKtt9KuG3Rccf3bVYAW6oid73/D +z7DMAF5G/OpVR8VbGh1WxXuR7zEVDUwpwsp9ek5dqN8BnBz1ppdZNIKqzszneckU +s2l/6mZBmgV1Nfy/cQU6U5s3S1Xc75UDQVLms3CIOpFTRIpecNTdfa31fYy/svy0 +M2lWTbCva0dOyuvMUhTgBL4I7Qa2dUMPXHMZatV5ooHYq/BZJA1r84C5cM5r+umE +2LLv/BlUr7RaQHhaKGn4Qhpzo5yRDE9mEqDpLVkbg8SxMsdf/pEF5/VyUwA9t8RT +fKVsInRd386tDqJSDbSFqKTvLztr/5YCyzZzvC2YB1voko/caOGd2d/G51Ij+bXU +xEN8U4fHDBsHwPUGb31uZUhTXpL37KiOqZmXFoH2usmuvx882XvyGcV0F4tstMaR +KLKzl2PwqzAYGFexLkYKMz0TYIeN6h3b86ETazPPU49nkaEU23Dx21J2Rb3UlH+I +lDQF3wuH1QlYiTnlcVa/Zu4QQg0/iP8ALkZ06mvn9e9mOtnA8gsh4B2oLqc19VLU +bcpv40dV1H3W9Lcx9B8JYUp0c/Oyno1D7Yj3tjGcwMKECmUpHi4kksehVo0/P933 +xmFmC6eyWYVdO9upvY/vKSB7b1dMt85iWr3gnMsSfRYc6jsbSxdjOPST46UsIzjx +wa1DS6+Bv5tiaC4uC6X+0tCAZo+UOQMYUbTGRR/7g/c= +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.2028.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.2028.pub new file mode 100644 index 0000000..655cc3a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass.rsa.2028.pub @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBHjANBgkqhkiG9w0BAQEFAAOCAQsAMIIBBgKB/gy7mjaWgPeFdVYDZWRCA9BN +iv3pPb0es27+FKY0hszLaOw47ExCtAWpDsH48TXAfyHBYwBLguayfk4LGIupxb+C +GMbRo3xEp0CbfY1Jby26T9vGjRC1foHDDUJG84uaRbyHqaf4i6zt4gVR+xlAEIjk +aFAAK8cOoXAT1CVqGLLljUCchL8PjaHj/yriZ/S7rdwlI3LnABxwwmLrmR/v71Wt +pmO/aNG8N+1po+QwaghTkyQ59E/ZvAuOkFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQ +aEDRbBFBmBqTv5fFGfk2WsAfKf/RG0/VFd+ZeM5251TeTvXH695nlSGauVl9AgMB +AAE= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass2.dsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass2.dsa.1024.priv new file mode 100644 index 0000000..29e3673 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass2.dsa.1024.priv @@ -0,0 +1,15 @@ +-----BEGIN DSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-128-CBC,DC173C6DFD455EBE462A35D6AB9A603A + +FoC3sxbdUFJTaNtRpooMxaX2lcQRLUz8qcRhzDBn5a1kaMHp2JM3KlHK5aauybT4 +ilmlKJ9sSm8pFLAWPKbkczSgZ+X6p/51v4zaEJSebZ98p32kQk87XJQE7aYroxYV +UfM5PSOoKWilj+LZQQEXV10qDoYGrnbSdoNSxYW5V1a1aP+ua0EO7m9MUYkoLxi3 +SJ/s2h/5KM3TOz7d7DOZuSoNm+0n6YC4aqQnR3lmEtAXEYLQqLhH2Q3FTKTHwBQw +HgMBAzcXOS1YSw6Ekwh1eZamizrOEC4I6oZEHoUBqRfbsQ8tu77kDq2ovQSyn8Fp +SeE64m3GgZOYdfcDuNZ0ccmm3shBBfTfD9AwR+1thklKO3oaaLEHb6TmnkD79rEz +9WsiVxoN7vqqWdgoeyl7REOB6WLQp8kYS4FoRG0QB/ZS8Hs/Tf17QPnrQNiMkvP7 +sJSHmlaMKXjWXK0VoN94kfZKUXwkzLD1VXuXFCnUkznWU0tahYi06b8/SVXc6EG+ +0mzylckH7UnjOQfxSFAlZ+e/PiX80tcPakxYbk+f1Nv7L0NOyhrDv18KUbv9mEpV +Ysild1m7/QSF0u1qmjmGNQ== +-----END DSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass2.dsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass2.dsa.1024.pub new file mode 100644 index 0000000..80a731e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/pass2.dsa.1024.pub @@ -0,0 +1,12 @@ +-----BEGIN PUBLIC KEY----- +MIIBtzCCASwGByqGSM44BAEwggEfAoGBAOY0KsTt5EpJ4LtlD3xRS5mDiGE1CMNp +0S9X0sK8kP8Aps8iYwMLbZYglk18GCNnCk4SjbAnZHSB3kaIv6AKQc2J8W2YV5se +3VhpKOFst7bqRtkGsl8uJtGlKTiXNclkv2jsKOrsBokSD1USGCECTNeMt3OgziRc +Z1dS+djSOZ2nAhUAzB96SpxlAak+K/QLVJ+lDe5DcY0CgYEAtxX1/HckvhlhHQyK +ZWLQsDfZBILbhc+OLDpOyT6cJS/sJzfFIYZgK5M3rOS4OmzdYfJccQAuGq+TVJQ3 +VcYOdbrIANJV8CDrn4jkkejTzJI6fCwAkPWOyxw8kbV1Hsoy6WLfSCHKpBUcrogA +qRGESqBVTawjyF/ECX667y/P49MDgYQAAoGAXYmxO4+52C1gBzh7GgTwNLJl7bLn +gOhKTFlKhT36VjMjeFfdXmBVBVbfUottKZby/gVX1IXT38PStB/dswbF45bGDdoS +zMFjYmHTtLtrU/4hReVtvb5MYmrPDFX58SwcSRRO/cH6WJPvfu4Aq0cJZA9Kb0B9 +5Wo18JxAqvPtTB8= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.1024.priv new file mode 100644 index 0000000..d3b5fda --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.1024.priv @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICVAIBAAJ/OwswbFo/uyC8ltGf/yA1A+gV5IGdnAgPbUSI3GzbHCA+x+TLG/tL +vbRw3r1smppY/jkkpiVW1ErSMuN0uixp5gb78Z9rH1XpWb5WWgp3WaY/9EHMjMdO +kQ/9LVZvRvl/M/Fi6owP+q+amJI1BEjECYfbhGL3rmlVdq4qXc40QwIDAQABAn8I +VZ0BPoAOhyF33KFMHxy8r28fsVgxJUYgM3NqQgdv4fFawCYXjhJz9duU5YJGFJGJ +WUGeHlkyYFlpi4f3m7tY7JawmQUWB0MNSoKHI3cgDX4/tfBN8ni+cO0eSoR5czBY +EsAHBU47p1awNFAHwd+ZEuv9H4RmMn7p279rQTtpAkAH3Nqs2/vrRF2cZUN4fIXf +4xHsQBByUayGq8a3J0UGaSFWv68zTUKFherr9uZotNp7NJ4jBXiARw0q8docXUG1 +AkAHgmOKHoORtAmikqpmFEJZOtsXMaLCIm4EszPo5ciYoLMBcVit09AdiQlt7ZJL +DY02svU1b0agCZ97kDkmHDkXAkACa8M9JELuDs/P/vIGYDkMVatIFfW6bWF02eFG +taWwMqCcSEsWvbw0xqYt34jURpNbCjmCyQVwYfAw/+TLhP9dAkAFwRjdwjw37qpj +ddg1mNiu37b7swFxmkiMOXZRxaNNsfb56A14RpN3zob3QdGUybGodMIKTFbmU/lu +CjqAxafJAkAG2yf6RWbwFIWfMyt7WYCh0VaGBCcgy574AinVieEo3ZZyFfC63+xm +3uoaNy4iLoJv4GCjqUBz3ZfcVaO/DDWG +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.1024.pub new file mode 100644 index 0000000..7ba0636 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.1024.pub @@ -0,0 +1,5 @@ +-----BEGIN RSA PUBLIC KEY----- +MIGGAn87CzBsWj+7ILyW0Z//IDUD6BXkgZ2cCA9tRIjcbNscID7H5Msb+0u9tHDe +vWyamlj+OSSmJVbUStIy43S6LGnmBvvxn2sfVelZvlZaCndZpj/0QcyMx06RD/0t +Vm9G+X8z8WLqjA/6r5qYkjUESMQJh9uEYveuaVV2ripdzjRDAgMBAAE= +-----END RSA PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.2028.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.2028.priv new file mode 100644 index 0000000..10e651d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.2028.priv @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEjwIBAAKB/gy7mjaWgPeFdVYDZWRCA9BNiv3pPb0es27+FKY0hszLaOw47ExC +tAWpDsH48TXAfyHBYwBLguayfk4LGIupxb+CGMbRo3xEp0CbfY1Jby26T9vGjRC1 +foHDDUJG84uaRbyHqaf4i6zt4gVR+xlAEIjkaFAAK8cOoXAT1CVqGLLljUCchL8P +jaHj/yriZ/S7rdwlI3LnABxwwmLrmR/v71WtpmO/aNG8N+1po+QwaghTkyQ59E/Z +vAuOkFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQaEDRbBFBmBqTv5fFGfk2WsAfKf/R +G0/VFd+ZeM5251TeTvXH695nlSGauVl9AgMBAAECgf4LrWHY/l54ouThZWvvbrug +pfz6sJX2g9l7yXmWlEWsPECVo/7SUbpYFpt6OZy99zSg+IKbGqWKfdhoKrTwIVtC +L0YZ0NlmdnANSIz0roxQG7ZxkL5+vHSw/PmD9x4Uwf+Cz8hATCmNBv1qc60dkyuW +4CLqe72qaTiVWRoO1iagQghNcLoo6vSy65ExLaCDTPha7yu2vw4hFZpWiEjW4dxf +rFdLiix52BC86YlAlxME/rLg8IJVvilbyo9aWdXmxOaUTLRv6PkFD1/gVdw8V9Qr +SLN9FlK2kkjiX0dzoibvZw3tMnt3yydAx0X87+sMRVahC1bp3kVPz4Hy0EWX4QJ/ +PM31vGiuITk2NCd51DXt1Ltn2OP5FaJSmCaEjh0XkU4qouYyjXWt8Bu6BTCl2vua +Fg0Uji9C+IkPLmaUMbMIOwaTk8cWqLthSxsLe70J5OkGrgfKUM/w+BHH1Pt/Pjzj +C++l0kiFaOVDVaAV9GpLPLCBoK/PC9Rb/rxMMoCCNwJ/NZuedIny2w3LMii77h/T +zSvergNGhjY6Rnva8lLXJ6dlrkcPAyps3gWwxqj4NR0T+GM0bDUPVLb7M07XV7SX +v7VJGm52JbRGwM1ss+r8XTTNemeGk+WRxG7TgtsMqYGXLfB8Qxk/f5/Mcc00Tl8u +wXFNsfxJxmt6AbsTr3g36wJ/IhOnibz9Ad+nchlBnN3QeW3CKHqzaR18voqvtVm2 +kJfHK15prH/sSGmxmiEGgrCJTZxtDbaNCO7/VBjnKudUUIhCAwsLtuq0/zub9vAd +8G1scfIpv5qaSNzmKoX8bOwArvrS6wP7yKrcTsuWIlHD8rJVI7IEDnQoTp5G8fK1 +hwJ/MIh8M5v0r5dUYEv6oIJWGcle6AH1JmsP5WIafgq72Z2288pHcCFHwNY8Dg9J +76QswVLnUhPTlmm3EOOPGEtam2iAD5r0Afytlb4lbNoQsj2szeXONDXB+6oueajh +VNELUr8HcSP5lgzRZjJW6aFIzj9LDRmQnUAOjGSXVOQtEwJ/MCQZ7N/v4dIKeDRA +8d8UExZ3+gGHumziztGRJ0tQryZH2PakP5I7V+1l7qEUnJ2c3mF+e1v41Ep9LCvh +bzrPKw9dxh18g4b+7bMpsWPnsraKh6ipxc7aaOaZV0Dxgez4zcZu0P1olO0cN3KM +nxJ0Pds3R8bAhNCDdS2JZaRp5Q== +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.2028.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.2028.pub new file mode 100644 index 0000000..b36dca4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/rsa.2028.pub @@ -0,0 +1,8 @@ +-----BEGIN RSA PUBLIC KEY----- +MIIBBgKB/gy7mjaWgPeFdVYDZWRCA9BNiv3pPb0es27+FKY0hszLaOw47ExCtAWp +DsH48TXAfyHBYwBLguayfk4LGIupxb+CGMbRo3xEp0CbfY1Jby26T9vGjRC1foHD +DUJG84uaRbyHqaf4i6zt4gVR+xlAEIjkaFAAK8cOoXAT1CVqGLLljUCchL8PjaHj +/yriZ/S7rdwlI3LnABxwwmLrmR/v71WtpmO/aNG8N+1po+QwaghTkyQ59E/ZvAuO +kFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQaEDRbBFBmBqTv5fFGfk2WsAfKf/RG0/V +Fd+ZeM5251TeTvXH695nlSGauVl9AgMBAAE= +-----END RSA PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector.js new file mode 100644 index 0000000..4b8d8cf --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector.js @@ -0,0 +1,7 @@ +module.exports = { + p: new Buffer('86F5CA03DCFEB225063FF830A0C769B9DD9D6153AD91D7CE27F787C43278B447E6533B86B18BED6E8A48B784A14C252C5BE0DBF60B86D6385BD2F12FB763ED8873ABFD3F5BA2E0A8C0A59082EAC056935E529DAF7C610467899C77ADEDFC846C881870B7B19B2B58F9BE0521A17002E3BDD6B86685EE90B3D9A1B02B782B1779', 'hex'), + q: new Buffer('996F967F6C8E388D9E28D01E205FBA957A5698B1', 'hex'), + g: new Buffer('07B0F92546150B62514BB771E2A0C0CE387F03BDA6C56B505209FF25FD3C133D89BBCD97E904E09114D9A7DEFDEADFC9078EA544D2E401AEECC40BB9FBBF78FD87995A10A1C27CB7789B594BA7EFB5C4326A9FE59A070E136DB77175464ADCA417BE5DCE2F40D10A46A3A3943F26AB7FD9C0398FF8C76EE0A56826A8A88F1DBD', 'hex'), + x: new Buffer('411602CB19A6CCC34494D79D98EF1E7ED5AF25F7', 'hex'), + y: new Buffer('5DF5E01DED31D0297E274E1691C192FE5868FEF9E19A84776454B100CF16F65392195A38B90523E2542EE61871C0440CB87C322FC4B4D2EC5E1E7EC766E1BE8D4CE935437DC11C3C8FD426338933EBFE739CB3465F4D3668C5E473508253B1E682F65CBDC4FAE93C2EA212390E54905A86E2223170B44EAA7DA5DD9FFCFB7F3B', 'hex') +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector.priv new file mode 100644 index 0000000..178bd1e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector.priv @@ -0,0 +1,12 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIBugIBAAKBgQCG9coD3P6yJQY/+DCgx2m53Z1hU62R184n94fEMni0R+ZTO4ax +i+1uiki3hKFMJSxb4Nv2C4bWOFvS8S+3Y+2Ic6v9P1ui4KjApZCC6sBWk15Sna98 +YQRniZx3re38hGyIGHC3sZsrWPm+BSGhcALjvda4ZoXukLPZobAreCsXeQIVAJlv +ln9sjjiNnijQHiBfupV6VpixAoGAB7D5JUYVC2JRS7dx4qDAzjh/A72mxWtQUgn/ +Jf08Ez2Ju82X6QTgkRTZp9796t/JB46lRNLkAa7sxAu5+794/YeZWhChwny3eJtZ +S6fvtcQyap/lmgcOE223cXVGStykF75dzi9A0QpGo6OUPyarf9nAOY/4x27gpWgm +qKiPHb0CgYBd9eAd7THQKX4nThaRwZL+WGj++eGahHdkVLEAzxb2U5IZWji5BSPi +VC7mGHHARAy4fDIvxLTS7F4efsdm4b6NTOk1Q33BHDyP1CYziTPr/nOcs0ZfTTZo +xeRzUIJTseaC9ly9xPrpPC6iEjkOVJBahuIiMXC0Tqp9pd2f/Pt/OwIUQRYCyxmm +zMNElNedmO8eftWvJfc= +-----END DSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector2.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector2.priv new file mode 100644 index 0000000..ef53f61 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/node_modules/parse-asn1/test/vector2.priv @@ -0,0 +1,19 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIDVQIBAAKCAQEAnbb7WVG2a7b+HhQPHSzlUCN0Fh/WU43xZIIYZC8LXEjI96Qa +rfoYcyS4dnT6GCKwDx7PgTaUPXxVdXJk5aGkT/4BLpk24AwdPpMQsBx9F5gF0wWL +Kp9Ltvlxa/5hF8a1s8xNm+NBEErUqArWyU4AX0uZPhTwketRdDvzMFDDjeI1Vn4b +NMPWpcDOqhoPNoITw9GYQ9C0sJ3Ln8ctOcjeQfG/FNS7RWPKKDcWIcrTMktqLTkh +Rb6/rHSIBSNvXKL+krhxzY+cNtMpK1UJyoyqd6Kt/Hv9d92m9xElp0Vv6hU+QzJW +oiYcagbtNpN5fnmV+tWqu8++PtonQeN1QEriWwIhAPLDEZN0znbJNWmQtGU3Shfy +P57TUIm9lp9hxt3pmYwfAoIBAFx/9rBvjxQ/6CiEM0k+R2nE2Yis5b4loOJICWcH +FsYT17DO5pMvj6p8RNLLJFI9pT++T27DWViS0apYxDKKBsRqFWYufqpwOh3s+Luy +0F2+LrlWwUKjOGYdEEYcDRNUcghQV/NJQwn/pzxhH3izKtu1dAw2HJ81vpCZfbIB +Ti71qmF4L1Kr64vWQyxN0Je8VCOyhdr7YNw2ToFh9KKjWso6ELHE0gPMdqRwozr9 +y92SlZhZq9i1bhclJS146sZucbqa4/HdJIcZmHQ5PNTYMhhoAGVHYOHjTAnk0VUX +n57A3ERz+Za9zm7tHKvti28Rb3rZz1Bd8PmY40qydRSw/+cCggEAZnCYxlRCbHjX ++CAerGwgPvAw1DYFAywvH6k35SN9vZSfNKCiVk/hJtyLcVxRQYAs4JecgkZGPEDm +tr2qJRP6YRcocWwuT9U7yVuJ5plJ2WUS6HO5yPjf1JnMMSiCVhreyzH2WOk0wMGX +8sTZawXLrWc4Hnt2iJHk2jhD0k2UzftRJum4vyHoNY7g4KMO8T/WpmTA3ONzH3+0 +mkhFpP2CVGh5cqLTglmcm6xODteZgZMHiRMDJVgTSXZBC4nSwXHRI6w1/ZdyGVl6p9FcGppCjlkZT3XHIevLz65EaWpJmvp04EKZ8TICZgFjjLh6t5GQ1KCYY +xXajuxlYck4mWvq3wIgacdUjCHQ3+prmlHJ6tTifDPTs/GAMW5byrkskz8OTbw= +-----END DSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/package.json new file mode 100644 index 0000000..4803292 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/package.json @@ -0,0 +1,42 @@ +{ + "name": "browserify-sign", + "version": "4.0.0", + "description": "adds node crypto signing for browsers", + "main": "index.js", + "browser": "browser.js", + "scripts": { + "unit": "node test/index.js | tspec", + "standard": "standard", + "test": "npm run standard && npm run unit" + }, + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/browserify-sign.git" + }, + "author": "", + "license": "ISC", + "dependencies": { + "bn.js": "^4.1.1", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.2", + "elliptic": "^6.0.0", + "inherits": "^2.0.1", + "parse-asn1": "^5.0.0" + }, + "devDependencies": { + "tap-spec": "^1.0.1", + "tape": "^3.0.3", + "standard": "^5.0.0" + }, + "readme": "browserify-sign [![Build Status](https://travis-ci.org/crypto-browserify/browserify-sign.svg)](https://travis-ci.org/crypto-browserify/browserify-sign)\n===\n\nA package to duplicate the functionality of node's crypto public key functions, much of this is based on [Fedor Indutny's](https://github.com/indutny) work on [tls.js](https://github.com/indutny/tls.js).\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/crypto-browserify/browserify-sign/issues" + }, + "homepage": "https://github.com/crypto-browserify/browserify-sign#readme", + "_id": "browserify-sign@4.0.0", + "_shasum": "10773910c3c206d5420a46aad8694f820b85968f", + "_resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.0.tgz", + "_from": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/sign.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/sign.js new file mode 100644 index 0000000..571f24d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/sign.js @@ -0,0 +1,185 @@ +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var createHmac = require('create-hmac') +var crt = require('browserify-rsa') +var curves = require('./curves') +var elliptic = require('elliptic') +var parseKeys = require('parse-asn1') + +var BN = require('bn.js') +var EC = elliptic.ec + +function sign (hash, key, hashType, signType) { + var priv = parseKeys(key) + if (priv.curve) { + if (signType !== 'ecdsa') throw new Error('wrong private key type') + + return ecSign(hash, priv) + } else if (priv.type === 'dsa') { + if (signType !== 'dsa') { + throw new Error('wrong private key type') + } + return dsaSign(hash, priv, hashType) + } else { + if (signType !== 'rsa') throw new Error('wrong private key type') + } + + var len = priv.modulus.byteLength() + var pad = [ 0, 1 ] + while (hash.length + pad.length + 1 < len) { + pad.push(0xff) + } + pad.push(0x00) + var i = -1 + while (++i < hash.length) { + pad.push(hash[i]) + } + + var out = crt(pad, priv) + return out +} + +function ecSign (hash, priv) { + var curveId = curves[priv.curve.join('.')] + if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')) + + var curve = new EC(curveId) + var key = curve.genKeyPair() + + key._importPrivate(priv.privateKey) + var out = key.sign(hash) + + return new Buffer(out.toDER()) +} + +function dsaSign (hash, priv, algo) { + var x = priv.params.priv_key + var p = priv.params.p + var q = priv.params.q + var g = priv.params.g + var r = new BN(0) + var k + var H = bits2int(hash, q).mod(q) + var s = false + var kv = getKey(x, q, hash, algo) + while (s === false) { + k = makeKey(q, kv, algo) + r = makeR(g, k, p, q) + s = k.invm(q).imul(H.add(x.mul(r))).mod(q) + if (!s.cmpn(0)) { + s = false + r = new BN(0) + } + } + return toDER(r, s) +} + +function toDER (r, s) { + r = r.toArray() + s = s.toArray() + + // Pad values + if (r[0] & 0x80) { + r = [ 0 ].concat(r) + } + // Pad values + if (s[0] & 0x80) { + s = [0].concat(s) + } + + var total = r.length + s.length + 4 + var res = [ 0x30, total, 0x02, r.length ] + res = res.concat(r, [ 0x02, s.length ], s) + return new Buffer(res) +} + +function getKey (x, q, hash, algo) { + x = new Buffer(x.toArray()) + if (x.length < q.byteLength()) { + var zeros = new Buffer(q.byteLength() - x.length) + zeros.fill(0) + x = Buffer.concat([zeros, x]) + } + var hlen = hash.length + var hbits = bits2octets(hash, q) + var v = new Buffer(hlen) + v.fill(1) + var k = new Buffer(hlen) + k.fill(0) + k = createHmac(algo, k) + .update(v) + .update(new Buffer([0])) + .update(x) + .update(hbits) + .digest() + v = createHmac(algo, k) + .update(v) + .digest() + k = createHmac(algo, k) + .update(v) + .update(new Buffer([1])) + .update(x) + .update(hbits) + .digest() + v = createHmac(algo, k) + .update(v) + .digest() + return { + k: k, + v: v + } +} + +function bits2int (obits, q) { + var bits = new BN(obits) + var shift = (obits.length << 3) - q.bitLength() + if (shift > 0) { + bits.ishrn(shift) + } + return bits +} + +function bits2octets (bits, q) { + bits = bits2int(bits, q) + bits = bits.mod(q) + var out = new Buffer(bits.toArray()) + if (out.length < q.byteLength()) { + var zeros = new Buffer(q.byteLength() - out.length) + zeros.fill(0) + out = Buffer.concat([zeros, out]) + } + return out +} + +function makeKey (q, kv, algo) { + var t, k + + do { + t = new Buffer('') + + while (t.length * 8 < q.bitLength()) { + kv.v = createHmac(algo, kv.k) + .update(kv.v) + .digest() + t = Buffer.concat([t, kv.v]) + } + + k = bits2int(t, q) + kv.k = createHmac(algo, kv.k) + .update(kv.v) + .update(new Buffer([0])) + .digest() + kv.v = createHmac(algo, kv.k) + .update(kv.v) + .digest() + } while (k.cmp(q) !== -1) + + return k +} + +function makeR (g, k, p, q) { + return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q) +} + +module.exports = sign +module.exports.getKey = getKey +module.exports.makeKey = makeKey diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/verify.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/verify.js new file mode 100644 index 0000000..cc5e7fe --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/browserify-sign/verify.js @@ -0,0 +1,103 @@ +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var curves = require('./curves') +var elliptic = require('elliptic') +var parseKeys = require('parse-asn1') + +var BN = require('bn.js') +var EC = elliptic.ec + +function verify (sig, hash, key, signType) { + var pub = parseKeys(key) + if (pub.type === 'ec') { + if (signType !== 'ecdsa') { + throw new Error('wrong public key type') + } + return ecVerify(sig, hash, pub) + } else if (pub.type === 'dsa') { + if (signType !== 'dsa') { + throw new Error('wrong public key type') + } + return dsaVerify(sig, hash, pub) + } else { + if (signType !== 'rsa') { + throw new Error('wrong public key type') + } + } + var len = pub.modulus.byteLength() + var pad = [ 1 ] + var padNum = 0 + while (hash.length + pad.length + 2 < len) { + pad.push(0xff) + padNum++ + } + pad.push(0x00) + var i = -1 + while (++i < hash.length) { + pad.push(hash[i]) + } + pad = new Buffer(pad) + var red = BN.mont(pub.modulus) + sig = new BN(sig).toRed(red) + + sig = sig.redPow(new BN(pub.publicExponent)) + + sig = new Buffer(sig.fromRed().toArray()) + var out = 0 + if (padNum < 8) { + out = 1 + } + len = Math.min(sig.length, pad.length) + if (sig.length !== pad.length) { + out = 1 + } + + i = -1 + while (++i < len) { + out |= (sig[i] ^ pad[i]) + } + return out === 0 +} + +function ecVerify (sig, hash, pub) { + var curveId = curves[pub.data.algorithm.curve.join('.')] + if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')) + + var curve = new EC(curveId) + var pubkey = pub.data.subjectPrivateKey.data + + return curve.verify(hash, sig, pubkey) +} + +function dsaVerify (sig, hash, pub) { + var p = pub.data.p + var q = pub.data.q + var g = pub.data.g + var y = pub.data.pub_key + var unpacked = parseKeys.signature.decode(sig, 'der') + var s = unpacked.s + var r = unpacked.r + checkValue(s, q) + checkValue(r, q) + var montp = BN.mont(p) + var w = s.invm(q) + var v = g.toRed(montp) + .redPow(new BN(hash).mul(w).mod(q)) + .fromRed() + .mul( + y.toRed(montp) + .redPow(r.mul(w).mod(q)) + .fromRed() + ).mod(p).mod(q) + return !v.cmp(r) +} + +function checkValue (b, q) { + if (b.cmpn(0) <= 0) { + throw new Error('invalid sig') + } + if (b.cmp(q) >= q) { + throw new Error('invalid sig') + } +} + +module.exports = verify diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/.npmignore new file mode 100644 index 0000000..daa6029 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/.npmignore @@ -0,0 +1 @@ +test.js diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/.travis.yml new file mode 100644 index 0000000..254335b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/.travis.yml @@ -0,0 +1,7 @@ +language: node_js + +node_js: + - "0.10" + - "0.11" + - "0.12" + - "iojs" \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/browser.js new file mode 100644 index 0000000..c24c975 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/browser.js @@ -0,0 +1,122 @@ +var elliptic = require('elliptic'); +var BN = require('bn.js'); + +module.exports = function createECDH(curve) { + return new ECDH(curve); +}; + +var aliases = { + secp256k1: { + name: 'secp256k1', + byteLength: 32 + }, + secp224r1: { + name: 'p224', + byteLength: 28 + }, + prime256v1: { + name: 'p256', + byteLength: 32 + }, + prime192v1: { + name: 'p192', + byteLength: 24 + }, + ed25519: { + name: 'ed25519', + byteLength: 32 + }, + secp384r1: { + name: 'p384', + byteLength: 48 + }, + secp521r1: { + name: 'p521', + byteLength: 66 + } +}; + +aliases.p224 = aliases.secp224r1; +aliases.p256 = aliases.secp256r1 = aliases.prime256v1; +aliases.p192 = aliases.secp192r1 = aliases.prime192v1; +aliases.p384 = aliases.secp384r1; +aliases.p521 = aliases.secp521r1; + +function ECDH(curve) { + this.curveType = aliases[curve]; + if (!this.curveType ) { + this.curveType = { + name: curve + }; + } + this.curve = new elliptic.ec(this.curveType.name); + this.keys = void 0; +} + +ECDH.prototype.generateKeys = function (enc, format) { + this.keys = this.curve.genKeyPair(); + return this.getPublicKey(enc, format); +}; + +ECDH.prototype.computeSecret = function (other, inenc, enc) { + inenc = inenc || 'utf8'; + if (!Buffer.isBuffer(other)) { + other = new Buffer(other, inenc); + } + var otherPub = this.curve.keyFromPublic(other).getPublic(); + var out = otherPub.mul(this.keys.getPrivate()).getX(); + return formatReturnValue(out, enc, this.curveType.byteLength); +}; + +ECDH.prototype.getPublicKey = function (enc, format) { + var key = this.keys.getPublic(format === 'compressed', true); + if (format === 'hybrid') { + if (key[key.length - 1] % 2) { + key[0] = 7; + } else { + key [0] = 6; + } + } + return formatReturnValue(key, enc); +}; + +ECDH.prototype.getPrivateKey = function (enc) { + return formatReturnValue(this.keys.getPrivate(), enc); +}; + +ECDH.prototype.setPublicKey = function (pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this.keys._importPublic(pub); + return this; +}; + +ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + var _priv = new BN(priv); + _priv = _priv.toString(16); + this.keys._importPrivate(_priv); + return this; +}; + +function formatReturnValue(bn, enc, len) { + if (!Array.isArray(bn)) { + bn = bn.toArray(); + } + var buf = new Buffer(bn); + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length); + zeros.fill(0); + buf = Buffer.concat([zeros, buf]); + } + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/index.js new file mode 100644 index 0000000..90857b7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/index.js @@ -0,0 +1,3 @@ +var createECDH = require('crypto').createECDH; + +module.exports = createECDH || require('./browser'); \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/.npmignore new file mode 100644 index 0000000..6d1eebb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/.npmignore @@ -0,0 +1,6 @@ +benchmarks/ +coverage/ +node_modules/ +npm-debug.log +1.js +logo.png diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/.travis.yml new file mode 100644 index 0000000..936b7b7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "5" +env: + matrix: + - TEST_SUITE=unit +matrix: + include: + - node_js: "4" + env: TEST_SUITE=lint +script: npm run $TEST_SUITE diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/README.md new file mode 100644 index 0000000..fee65ba --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/README.md @@ -0,0 +1,219 @@ +# bn.js + +> BigNum in pure javascript + +[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) + +## Install +`npm install --save bn.js` + +## Usage + +```js +const BN = require('bn.js'); + +var a = new BN('dead', 16); +var b = new BN('101010', 2); + +var res = a.add(b); +console.log(res.toString(10)); // 57047 +``` + +**Note**: decimals are not supported in this library. + +## Notation + +### Prefixes + +There are several prefixes to instructions that affect the way the work. Here +is the list of them in the order of appearance in the function name: + +* `i` - perform operation in-place, storing the result in the host object (on + which the method was invoked). Might be used to avoid number allocation costs +* `u` - unsigned, ignore the sign of operands when performing operation, or + always return positive value. Second case applies to reduction operations + like `mod()`. In such cases if the result will be negative - modulo will be + added to the result to make it positive + +### Postfixes + +The only available postfix at the moment is: + +* `n` - which means that the argument of the function must be a plain JavaScript + number + +### Examples + +* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` +* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value +* `a.iushln(13)` - shift bits of `a` left by 13 + +## Instructions + +Prefixes/postfixes are put in parens at the of the line. `endian` - could be +either `le` (little-endian) or `be` (big-endian). + +### Utilities + +* `a.clone()` - clone number +* `a.toString(base, length)` - convert to base-string and pad with zeroes +* `a.toNumber()` - convert to Javascript Number (limited to 53 bits) +* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) +* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero + pad to length, throwing if already exceeding +* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, + which must behave like an `Array` +* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available) +* `a.bitLength()` - get number of bits occupied +* `a.zeroBits()` - return number of less-significant consequent zero bits + (example: `1010000` has 4 zero bits) +* `a.byteLength()` - return number of bytes occupied +* `a.isNeg()` - true if the number is negative +* `a.isEven()` - no comments +* `a.isOdd()` - no comments +* `a.isZero()` - no comments +* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) + depending on the comparison result (`ucmp`, `cmpn`) +* `a.lt(b)` - `a` less than `b` (`n`) +* `a.lte(b)` - `a` less than or equals `b` (`n`) +* `a.gt(b)` - `a` greater than `b` (`n`) +* `a.gte(b)` - `a` greater than or equals `b` (`n`) +* `a.eq(b)` - `a` equals `b` (`n`) +* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width +* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width +* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance + +### Arithmetics + +* `a.neg()` - negate sign (`i`) +* `a.abs()` - absolute value (`i`) +* `a.add(b)` - addition (`i`, `n`, `in`) +* `a.sub(b)` - subtraction (`i`, `n`, `in`) +* `a.mul(b)` - multiply (`i`, `n`, `in`) +* `a.sqr()` - square (`i`) +* `a.pow(b)` - raise `a` to the power of `b` +* `a.div(b)` - divide (`divn`, `idivn`) +* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) +* `a.divRound(b)` - rounded division + +### Bit operations + +* `a.or(b)` - or (`i`, `u`, `iu`) +* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced + with `andn` in future) +* `a.xor(b)` - xor (`i`, `u`, `iu`) +* `a.setn(b)` - set specified bit to `1` +* `a.shln(b)` - shift left (`i`, `u`, `iu`) +* `a.shrn(b)` - shift right (`i`, `u`, `iu`) +* `a.testn(b)` - test if specified bit is set +* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) +* `a.bincn(b)` - add `1 << b` to the number +* `a.notn(w)` - not (for the width specified by `w`) (`i`) + +### Reduction + +* `a.gcd(b)` - GCD +* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) +* `a.invm(b)` - inverse `a` modulo `b` + +## Fast reduction + +When doing lots of reductions using the same modulo, it might be beneficial to +use some tricks: like [Montgomery multiplication][0], or using special algorithm +for [Mersenne Prime][1]. + +### Reduction context + +To enable this tricks one should create a reduction context: + +```js +var red = BN.red(num); +``` +where `num` is just a BN instance. + +Or: + +```js +var red = BN.red(primeName); +``` + +Where `primeName` is either of these [Mersenne Primes][1]: + +* `'k256'` +* `'p224'` +* `'p192'` +* `'p25519'` + +Or: + +```js +var red = BN.mont(num); +``` + +To reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than +`.red(num)`, but slower than `BN.red(primeName)`. + +### Converting numbers + +Before performing anything in reduction context - numbers should be converted +to it. Usually, this means that one should: + +* Convert inputs to reducted ones +* Operate on them in reduction context +* Convert outputs back from the reduction context + +Here is how one may convert numbers to `red`: + +```js +var redA = a.toRed(red); +``` +Where `red` is a reduction context created using instructions above + +Here is how to convert them back: + +```js +var a = redA.fromRed(); +``` + +### Red instructions + +Most of the instructions from the very start of this readme have their +counterparts in red context: + +* `a.redAdd(b)`, `a.redIAdd(b)` +* `a.redSub(b)`, `a.redISub(b)` +* `a.redShl(num)` +* `a.redMul(b)`, `a.redIMul(b)` +* `a.redSqr()`, `a.redISqr()` +* `a.redSqrt()` - square root modulo reduction context's prime +* `a.redInvm()` - modular inverse of the number +* `a.redNeg()` +* `a.redPow(b)` - modular exponentiation + +## LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2015. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + +[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication +[1]: https://en.wikipedia.org/wiki/Mersenne_prime diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/lib/bn.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/lib/bn.js new file mode 100644 index 0000000..3ca1646 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/lib/bn.js @@ -0,0 +1,3420 @@ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buf' + 'fer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + return num !== null && typeof num === 'object' && + num.constructor.name === 'BN' && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var length = this.bitLength(); + var ret; + if (length <= 26) { + ret = this.words[0]; + } else if (length <= 52) { + ret = (this.words[1] * 0x4000000) + this.words[0]; + } else if (length === 53) { + // NOTE: at this stage it is known that the top bit is set + ret = 0x10000000000000 + (this.words[1] * 0x4000000) + this.words[0]; + } else { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid += Math.imul(ah0, bl0); + hi = Math.imul(ah0, bh0); + var w0 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w0 >>> 26); + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid += Math.imul(ah1, bl0); + hi = Math.imul(ah1, bh0); + lo += Math.imul(al0, bl1); + mid += Math.imul(al0, bh1); + mid += Math.imul(ah0, bl1); + hi += Math.imul(ah0, bh1); + var w1 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w1 >>> 26); + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid += Math.imul(ah2, bl0); + hi = Math.imul(ah2, bh0); + lo += Math.imul(al1, bl1); + mid += Math.imul(al1, bh1); + mid += Math.imul(ah1, bl1); + hi += Math.imul(ah1, bh1); + lo += Math.imul(al0, bl2); + mid += Math.imul(al0, bh2); + mid += Math.imul(ah0, bl2); + hi += Math.imul(ah0, bh2); + var w2 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w2 >>> 26); + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid += Math.imul(ah3, bl0); + hi = Math.imul(ah3, bh0); + lo += Math.imul(al2, bl1); + mid += Math.imul(al2, bh1); + mid += Math.imul(ah2, bl1); + hi += Math.imul(ah2, bh1); + lo += Math.imul(al1, bl2); + mid += Math.imul(al1, bh2); + mid += Math.imul(ah1, bl2); + hi += Math.imul(ah1, bh2); + lo += Math.imul(al0, bl3); + mid += Math.imul(al0, bh3); + mid += Math.imul(ah0, bl3); + hi += Math.imul(ah0, bh3); + var w3 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w3 >>> 26); + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid += Math.imul(ah4, bl0); + hi = Math.imul(ah4, bh0); + lo += Math.imul(al3, bl1); + mid += Math.imul(al3, bh1); + mid += Math.imul(ah3, bl1); + hi += Math.imul(ah3, bh1); + lo += Math.imul(al2, bl2); + mid += Math.imul(al2, bh2); + mid += Math.imul(ah2, bl2); + hi += Math.imul(ah2, bh2); + lo += Math.imul(al1, bl3); + mid += Math.imul(al1, bh3); + mid += Math.imul(ah1, bl3); + hi += Math.imul(ah1, bh3); + lo += Math.imul(al0, bl4); + mid += Math.imul(al0, bh4); + mid += Math.imul(ah0, bl4); + hi += Math.imul(ah0, bh4); + var w4 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w4 >>> 26); + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid += Math.imul(ah5, bl0); + hi = Math.imul(ah5, bh0); + lo += Math.imul(al4, bl1); + mid += Math.imul(al4, bh1); + mid += Math.imul(ah4, bl1); + hi += Math.imul(ah4, bh1); + lo += Math.imul(al3, bl2); + mid += Math.imul(al3, bh2); + mid += Math.imul(ah3, bl2); + hi += Math.imul(ah3, bh2); + lo += Math.imul(al2, bl3); + mid += Math.imul(al2, bh3); + mid += Math.imul(ah2, bl3); + hi += Math.imul(ah2, bh3); + lo += Math.imul(al1, bl4); + mid += Math.imul(al1, bh4); + mid += Math.imul(ah1, bl4); + hi += Math.imul(ah1, bh4); + lo += Math.imul(al0, bl5); + mid += Math.imul(al0, bh5); + mid += Math.imul(ah0, bl5); + hi += Math.imul(ah0, bh5); + var w5 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w5 >>> 26); + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid += Math.imul(ah6, bl0); + hi = Math.imul(ah6, bh0); + lo += Math.imul(al5, bl1); + mid += Math.imul(al5, bh1); + mid += Math.imul(ah5, bl1); + hi += Math.imul(ah5, bh1); + lo += Math.imul(al4, bl2); + mid += Math.imul(al4, bh2); + mid += Math.imul(ah4, bl2); + hi += Math.imul(ah4, bh2); + lo += Math.imul(al3, bl3); + mid += Math.imul(al3, bh3); + mid += Math.imul(ah3, bl3); + hi += Math.imul(ah3, bh3); + lo += Math.imul(al2, bl4); + mid += Math.imul(al2, bh4); + mid += Math.imul(ah2, bl4); + hi += Math.imul(ah2, bh4); + lo += Math.imul(al1, bl5); + mid += Math.imul(al1, bh5); + mid += Math.imul(ah1, bl5); + hi += Math.imul(ah1, bh5); + lo += Math.imul(al0, bl6); + mid += Math.imul(al0, bh6); + mid += Math.imul(ah0, bl6); + hi += Math.imul(ah0, bh6); + var w6 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w6 >>> 26); + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid += Math.imul(ah7, bl0); + hi = Math.imul(ah7, bh0); + lo += Math.imul(al6, bl1); + mid += Math.imul(al6, bh1); + mid += Math.imul(ah6, bl1); + hi += Math.imul(ah6, bh1); + lo += Math.imul(al5, bl2); + mid += Math.imul(al5, bh2); + mid += Math.imul(ah5, bl2); + hi += Math.imul(ah5, bh2); + lo += Math.imul(al4, bl3); + mid += Math.imul(al4, bh3); + mid += Math.imul(ah4, bl3); + hi += Math.imul(ah4, bh3); + lo += Math.imul(al3, bl4); + mid += Math.imul(al3, bh4); + mid += Math.imul(ah3, bl4); + hi += Math.imul(ah3, bh4); + lo += Math.imul(al2, bl5); + mid += Math.imul(al2, bh5); + mid += Math.imul(ah2, bl5); + hi += Math.imul(ah2, bh5); + lo += Math.imul(al1, bl6); + mid += Math.imul(al1, bh6); + mid += Math.imul(ah1, bl6); + hi += Math.imul(ah1, bh6); + lo += Math.imul(al0, bl7); + mid += Math.imul(al0, bh7); + mid += Math.imul(ah0, bl7); + hi += Math.imul(ah0, bh7); + var w7 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w7 >>> 26); + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid += Math.imul(ah8, bl0); + hi = Math.imul(ah8, bh0); + lo += Math.imul(al7, bl1); + mid += Math.imul(al7, bh1); + mid += Math.imul(ah7, bl1); + hi += Math.imul(ah7, bh1); + lo += Math.imul(al6, bl2); + mid += Math.imul(al6, bh2); + mid += Math.imul(ah6, bl2); + hi += Math.imul(ah6, bh2); + lo += Math.imul(al5, bl3); + mid += Math.imul(al5, bh3); + mid += Math.imul(ah5, bl3); + hi += Math.imul(ah5, bh3); + lo += Math.imul(al4, bl4); + mid += Math.imul(al4, bh4); + mid += Math.imul(ah4, bl4); + hi += Math.imul(ah4, bh4); + lo += Math.imul(al3, bl5); + mid += Math.imul(al3, bh5); + mid += Math.imul(ah3, bl5); + hi += Math.imul(ah3, bh5); + lo += Math.imul(al2, bl6); + mid += Math.imul(al2, bh6); + mid += Math.imul(ah2, bl6); + hi += Math.imul(ah2, bh6); + lo += Math.imul(al1, bl7); + mid += Math.imul(al1, bh7); + mid += Math.imul(ah1, bl7); + hi += Math.imul(ah1, bh7); + lo += Math.imul(al0, bl8); + mid += Math.imul(al0, bh8); + mid += Math.imul(ah0, bl8); + hi += Math.imul(ah0, bh8); + var w8 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w8 >>> 26); + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid += Math.imul(ah9, bl0); + hi = Math.imul(ah9, bh0); + lo += Math.imul(al8, bl1); + mid += Math.imul(al8, bh1); + mid += Math.imul(ah8, bl1); + hi += Math.imul(ah8, bh1); + lo += Math.imul(al7, bl2); + mid += Math.imul(al7, bh2); + mid += Math.imul(ah7, bl2); + hi += Math.imul(ah7, bh2); + lo += Math.imul(al6, bl3); + mid += Math.imul(al6, bh3); + mid += Math.imul(ah6, bl3); + hi += Math.imul(ah6, bh3); + lo += Math.imul(al5, bl4); + mid += Math.imul(al5, bh4); + mid += Math.imul(ah5, bl4); + hi += Math.imul(ah5, bh4); + lo += Math.imul(al4, bl5); + mid += Math.imul(al4, bh5); + mid += Math.imul(ah4, bl5); + hi += Math.imul(ah4, bh5); + lo += Math.imul(al3, bl6); + mid += Math.imul(al3, bh6); + mid += Math.imul(ah3, bl6); + hi += Math.imul(ah3, bh6); + lo += Math.imul(al2, bl7); + mid += Math.imul(al2, bh7); + mid += Math.imul(ah2, bl7); + hi += Math.imul(ah2, bh7); + lo += Math.imul(al1, bl8); + mid += Math.imul(al1, bh8); + mid += Math.imul(ah1, bl8); + hi += Math.imul(ah1, bh8); + lo += Math.imul(al0, bl9); + mid += Math.imul(al0, bh9); + mid += Math.imul(ah0, bl9); + hi += Math.imul(ah0, bh9); + var w9 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w9 >>> 26); + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid += Math.imul(ah9, bl1); + hi = Math.imul(ah9, bh1); + lo += Math.imul(al8, bl2); + mid += Math.imul(al8, bh2); + mid += Math.imul(ah8, bl2); + hi += Math.imul(ah8, bh2); + lo += Math.imul(al7, bl3); + mid += Math.imul(al7, bh3); + mid += Math.imul(ah7, bl3); + hi += Math.imul(ah7, bh3); + lo += Math.imul(al6, bl4); + mid += Math.imul(al6, bh4); + mid += Math.imul(ah6, bl4); + hi += Math.imul(ah6, bh4); + lo += Math.imul(al5, bl5); + mid += Math.imul(al5, bh5); + mid += Math.imul(ah5, bl5); + hi += Math.imul(ah5, bh5); + lo += Math.imul(al4, bl6); + mid += Math.imul(al4, bh6); + mid += Math.imul(ah4, bl6); + hi += Math.imul(ah4, bh6); + lo += Math.imul(al3, bl7); + mid += Math.imul(al3, bh7); + mid += Math.imul(ah3, bl7); + hi += Math.imul(ah3, bh7); + lo += Math.imul(al2, bl8); + mid += Math.imul(al2, bh8); + mid += Math.imul(ah2, bl8); + hi += Math.imul(ah2, bh8); + lo += Math.imul(al1, bl9); + mid += Math.imul(al1, bh9); + mid += Math.imul(ah1, bl9); + hi += Math.imul(ah1, bh9); + var w10 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w10 >>> 26); + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid += Math.imul(ah9, bl2); + hi = Math.imul(ah9, bh2); + lo += Math.imul(al8, bl3); + mid += Math.imul(al8, bh3); + mid += Math.imul(ah8, bl3); + hi += Math.imul(ah8, bh3); + lo += Math.imul(al7, bl4); + mid += Math.imul(al7, bh4); + mid += Math.imul(ah7, bl4); + hi += Math.imul(ah7, bh4); + lo += Math.imul(al6, bl5); + mid += Math.imul(al6, bh5); + mid += Math.imul(ah6, bl5); + hi += Math.imul(ah6, bh5); + lo += Math.imul(al5, bl6); + mid += Math.imul(al5, bh6); + mid += Math.imul(ah5, bl6); + hi += Math.imul(ah5, bh6); + lo += Math.imul(al4, bl7); + mid += Math.imul(al4, bh7); + mid += Math.imul(ah4, bl7); + hi += Math.imul(ah4, bh7); + lo += Math.imul(al3, bl8); + mid += Math.imul(al3, bh8); + mid += Math.imul(ah3, bl8); + hi += Math.imul(ah3, bh8); + lo += Math.imul(al2, bl9); + mid += Math.imul(al2, bh9); + mid += Math.imul(ah2, bl9); + hi += Math.imul(ah2, bh9); + var w11 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w11 >>> 26); + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid += Math.imul(ah9, bl3); + hi = Math.imul(ah9, bh3); + lo += Math.imul(al8, bl4); + mid += Math.imul(al8, bh4); + mid += Math.imul(ah8, bl4); + hi += Math.imul(ah8, bh4); + lo += Math.imul(al7, bl5); + mid += Math.imul(al7, bh5); + mid += Math.imul(ah7, bl5); + hi += Math.imul(ah7, bh5); + lo += Math.imul(al6, bl6); + mid += Math.imul(al6, bh6); + mid += Math.imul(ah6, bl6); + hi += Math.imul(ah6, bh6); + lo += Math.imul(al5, bl7); + mid += Math.imul(al5, bh7); + mid += Math.imul(ah5, bl7); + hi += Math.imul(ah5, bh7); + lo += Math.imul(al4, bl8); + mid += Math.imul(al4, bh8); + mid += Math.imul(ah4, bl8); + hi += Math.imul(ah4, bh8); + lo += Math.imul(al3, bl9); + mid += Math.imul(al3, bh9); + mid += Math.imul(ah3, bl9); + hi += Math.imul(ah3, bh9); + var w12 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w12 >>> 26); + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid += Math.imul(ah9, bl4); + hi = Math.imul(ah9, bh4); + lo += Math.imul(al8, bl5); + mid += Math.imul(al8, bh5); + mid += Math.imul(ah8, bl5); + hi += Math.imul(ah8, bh5); + lo += Math.imul(al7, bl6); + mid += Math.imul(al7, bh6); + mid += Math.imul(ah7, bl6); + hi += Math.imul(ah7, bh6); + lo += Math.imul(al6, bl7); + mid += Math.imul(al6, bh7); + mid += Math.imul(ah6, bl7); + hi += Math.imul(ah6, bh7); + lo += Math.imul(al5, bl8); + mid += Math.imul(al5, bh8); + mid += Math.imul(ah5, bl8); + hi += Math.imul(ah5, bh8); + lo += Math.imul(al4, bl9); + mid += Math.imul(al4, bh9); + mid += Math.imul(ah4, bl9); + hi += Math.imul(ah4, bh9); + var w13 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w13 >>> 26); + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid += Math.imul(ah9, bl5); + hi = Math.imul(ah9, bh5); + lo += Math.imul(al8, bl6); + mid += Math.imul(al8, bh6); + mid += Math.imul(ah8, bl6); + hi += Math.imul(ah8, bh6); + lo += Math.imul(al7, bl7); + mid += Math.imul(al7, bh7); + mid += Math.imul(ah7, bl7); + hi += Math.imul(ah7, bh7); + lo += Math.imul(al6, bl8); + mid += Math.imul(al6, bh8); + mid += Math.imul(ah6, bl8); + hi += Math.imul(ah6, bh8); + lo += Math.imul(al5, bl9); + mid += Math.imul(al5, bh9); + mid += Math.imul(ah5, bl9); + hi += Math.imul(ah5, bh9); + var w14 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w14 >>> 26); + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid += Math.imul(ah9, bl6); + hi = Math.imul(ah9, bh6); + lo += Math.imul(al8, bl7); + mid += Math.imul(al8, bh7); + mid += Math.imul(ah8, bl7); + hi += Math.imul(ah8, bh7); + lo += Math.imul(al7, bl8); + mid += Math.imul(al7, bh8); + mid += Math.imul(ah7, bl8); + hi += Math.imul(ah7, bh8); + lo += Math.imul(al6, bl9); + mid += Math.imul(al6, bh9); + mid += Math.imul(ah6, bl9); + hi += Math.imul(ah6, bh9); + var w15 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w15 >>> 26); + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid += Math.imul(ah9, bl7); + hi = Math.imul(ah9, bh7); + lo += Math.imul(al8, bl8); + mid += Math.imul(al8, bh8); + mid += Math.imul(ah8, bl8); + hi += Math.imul(ah8, bh8); + lo += Math.imul(al7, bl9); + mid += Math.imul(al7, bh9); + mid += Math.imul(ah7, bl9); + hi += Math.imul(ah7, bh9); + var w16 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w16 >>> 26); + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid += Math.imul(ah9, bl8); + hi = Math.imul(ah9, bh8); + lo += Math.imul(al8, bl9); + mid += Math.imul(al8, bh9); + mid += Math.imul(ah8, bl9); + hi += Math.imul(ah8, bh9); + var w17 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w17 >>> 26); + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid += Math.imul(ah9, bl9); + hi = Math.imul(ah9, bh9); + var w18 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w18 >>> 26); + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})(typeof module === 'undefined' || module, this); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/package.json new file mode 100644 index 0000000..63ecf80 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/package.json @@ -0,0 +1,42 @@ +{ + "name": "bn.js", + "version": "4.11.1", + "description": "Big number implementation in pure javascript", + "main": "lib/bn.js", + "scripts": { + "lint": "semistandard", + "unit": "mocha --reporter=spec test/*-test.js", + "test": "npm run lint && npm run unit" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/bn.js.git" + }, + "keywords": [ + "BN", + "BigNum", + "Big number", + "Modulo", + "Montgomery" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/bn.js/issues" + }, + "homepage": "https://github.com/indutny/bn.js", + "devDependencies": { + "istanbul": "^0.3.5", + "mocha": "^2.1.0", + "semistandard": "^7.0.4" + }, + "readme": "# \"bn.js\"\n\n> BigNum in pure javascript\n\n[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js)\n\n## Install\n`npm install --save bn.js`\n\n## Usage\n\n```js\nconst BN = require('bn.js');\n\nvar a = new BN('dead', 16);\nvar b = new BN('101010', 2);\n\nvar res = a.add(b);\nconsole.log(res.toString(10)); // 57047\n```\n\n**Note**: decimals are not supported in this library.\n\n## Notation\n\n### Prefixes\n\nThere are several prefixes to instructions that affect the way the work. Here\nis the list of them in the order of appearance in the function name:\n\n* `i` - perform operation in-place, storing the result in the host object (on\n which the method was invoked). Might be used to avoid number allocation costs\n* `u` - unsigned, ignore the sign of operands when performing operation, or\n always return positive value. Second case applies to reduction operations\n like `mod()`. In such cases if the result will be negative - modulo will be\n added to the result to make it positive\n\n### Postfixes\n\nThe only available postfix at the moment is:\n\n* `n` - which means that the argument of the function must be a plain JavaScript\n number\n\n### Examples\n\n* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a`\n* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value\n* `a.iushln(13)` - shift bits of `a` left by 13\n\n## Instructions\n\nPrefixes/postfixes are put in parens at the of the line. `endian` - could be\neither `le` (little-endian) or `be` (big-endian).\n\n### Utilities\n\n* `a.clone()` - clone number\n* `a.toString(base, length)` - convert to base-string and pad with zeroes\n* `a.toNumber()` - convert to Javascript Number (limited to 53 bits)\n* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`)\n* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero\n pad to length, throwing if already exceeding\n* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`,\n which must behave like an `Array`\n* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available)\n* `a.bitLength()` - get number of bits occupied\n* `a.zeroBits()` - return number of less-significant consequent zero bits\n (example: `1010000` has 4 zero bits)\n* `a.byteLength()` - return number of bytes occupied\n* `a.isNeg()` - true if the number is negative\n* `a.isEven()` - no comments\n* `a.isOdd()` - no comments\n* `a.isZero()` - no comments\n* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b)\n depending on the comparison result (`ucmp`, `cmpn`)\n* `a.lt(b)` - `a` less than `b` (`n`)\n* `a.lte(b)` - `a` less than or equals `b` (`n`)\n* `a.gt(b)` - `a` greater than `b` (`n`)\n* `a.gte(b)` - `a` greater than or equals `b` (`n`)\n* `a.eq(b)` - `a` equals `b` (`n`)\n* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width\n* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width\n* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance\n\n### Arithmetics\n\n* `a.neg()` - negate sign (`i`)\n* `a.abs()` - absolute value (`i`)\n* `a.add(b)` - addition (`i`, `n`, `in`)\n* `a.sub(b)` - subtraction (`i`, `n`, `in`)\n* `a.mul(b)` - multiply (`i`, `n`, `in`)\n* `a.sqr()` - square (`i`)\n* `a.pow(b)` - raise `a` to the power of `b`\n* `a.div(b)` - divide (`divn`, `idivn`)\n* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`)\n* `a.divRound(b)` - rounded division\n\n### Bit operations\n\n* `a.or(b)` - or (`i`, `u`, `iu`)\n* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced\n with `andn` in future)\n* `a.xor(b)` - xor (`i`, `u`, `iu`)\n* `a.setn(b)` - set specified bit to `1`\n* `a.shln(b)` - shift left (`i`, `u`, `iu`)\n* `a.shrn(b)` - shift right (`i`, `u`, `iu`)\n* `a.testn(b)` - test if specified bit is set\n* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`)\n* `a.bincn(b)` - add `1 << b` to the number\n* `a.notn(w)` - not (for the width specified by `w`) (`i`)\n\n### Reduction\n\n* `a.gcd(b)` - GCD\n* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`)\n* `a.invm(b)` - inverse `a` modulo `b`\n\n## Fast reduction\n\nWhen doing lots of reductions using the same modulo, it might be beneficial to\nuse some tricks: like [Montgomery multiplication][0], or using special algorithm\nfor [Mersenne Prime][1].\n\n### Reduction context\n\nTo enable this tricks one should create a reduction context:\n\n```js\nvar red = BN.red(num);\n```\nwhere `num` is just a BN instance.\n\nOr:\n\n```js\nvar red = BN.red(primeName);\n```\n\nWhere `primeName` is either of these [Mersenne Primes][1]:\n\n* `'k256'`\n* `'p224'`\n* `'p192'`\n* `'p25519'`\n\nOr:\n\n```js\nvar red = BN.mont(num);\n```\n\nTo reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than\n`.red(num)`, but slower than `BN.red(primeName)`.\n\n### Converting numbers\n\nBefore performing anything in reduction context - numbers should be converted\nto it. Usually, this means that one should:\n\n* Convert inputs to reducted ones\n* Operate on them in reduction context\n* Convert outputs back from the reduction context\n\nHere is how one may convert numbers to `red`:\n\n```js\nvar redA = a.toRed(red);\n```\nWhere `red` is a reduction context created using instructions above\n\nHere is how to convert them back:\n\n```js\nvar a = redA.fromRed();\n```\n\n### Red instructions\n\nMost of the instructions from the very start of this readme have their\ncounterparts in red context:\n\n* `a.redAdd(b)`, `a.redIAdd(b)`\n* `a.redSub(b)`, `a.redISub(b)`\n* `a.redShl(num)`\n* `a.redMul(b)`, `a.redIMul(b)`\n* `a.redSqr()`, `a.redISqr()`\n* `a.redSqrt()` - square root modulo reduction context's prime\n* `a.redInvm()` - modular inverse of the number\n* `a.redNeg()`\n* `a.redPow(b)` - modular exponentiation\n\n## LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2015.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication\n[1]: https://en.wikipedia.org/wiki/Mersenne_prime\n", + "readmeFilename": "README.md", + "_id": "bn.js@4.11.1", + "_shasum": "ff1c52c52fd371e9d91419439bac5cfba2b41798", + "_resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz", + "_from": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/arithmetic-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/arithmetic-test.js new file mode 100644 index 0000000..3f336ac --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/arithmetic-test.js @@ -0,0 +1,635 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; +var fixtures = require('./fixtures'); + +describe('BN.js/Arithmetic', function () { + describe('.add()', function () { + it('should add numbers', function () { + assert.equal(new BN(14).add(new BN(26)).toString(16), '28'); + var k = new BN(0x1234); + var r = k; + + for (var i = 0; i < 257; i++) { + r = r.add(k); + } + + assert.equal(r.toString(16), '125868'); + }); + + it('should handle carry properly (in-place)', function () { + var k = new BN('abcdefabcdefabcdef', 16); + var r = new BN('deadbeef', 16); + + for (var i = 0; i < 257; i++) { + r.iadd(k); + } + + assert.equal(r.toString(16), 'ac79bd9b79be7a277bde'); + }); + + it('should properly do positive + negative', function () { + var a = new BN('abcd', 16); + var b = new BN('-abce', 16); + + assert.equal(a.iadd(b).toString(16), '-1'); + + a = new BN('abcd', 16); + b = new BN('-abce', 16); + + assert.equal(a.add(b).toString(16), '-1'); + assert.equal(b.add(a).toString(16), '-1'); + }); + }); + + describe('.iaddn()', function () { + it('should allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should add negative number', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(-200); + + assert.equal(a.toString(), '-300'); + }); + + it('should allow neg + pos with big number', function () { + var a = new BN('-1000000000', 10); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.toString(), '-999999800'); + }); + + it('should carry limb', function () { + var a = new BN('3ffffff', 16); + + assert.equal(a.iaddn(1).toString(16), '4000000'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).iaddn(0x4000000); + }); + }); + }); + + describe('.sub()', function () { + it('should subtract small numbers', function () { + assert.equal(new BN(26).sub(new BN(14)).toString(16), 'c'); + assert.equal(new BN(14).sub(new BN(26)).toString(16), '-c'); + assert.equal(new BN(26).sub(new BN(26)).toString(16), '0'); + assert.equal(new BN(-26).sub(new BN(26)).toString(16), '-34'); + }); + + var a = new BN( + '31ff3c61db2db84b9823d320907a573f6ad37c437abe458b1802cda041d6384' + + 'a7d8daef41395491e2', + 16); + var b = new BN( + '6f0e4d9f1d6071c183677f601af9305721c91d31b0bbbae8fb790000', + 16); + var r = new BN( + '31ff3c61db2db84b9823d3208989726578fd75276287cd9516533a9acfb9a67' + + '76281f34583ddb91e2', + 16); + + it('should subtract big numbers', function () { + assert.equal(a.sub(b).cmp(r), 0); + }); + + it('should subtract numbers in place', function () { + assert.equal(b.clone().isub(a).neg().cmp(r), 0); + }); + + it('should subtract with carry', function () { + // Carry and copy + var a = new BN('12345', 16); + var b = new BN('1000000000000', 16); + assert.equal(a.isub(b).toString(16), '-fffffffedcbb'); + + a = new BN('12345', 16); + b = new BN('1000000000000', 16); + assert.equal(b.isub(a).toString(16), 'fffffffedcbb'); + }); + }); + + describe('.isubn()', function () { + it('should subtract negative number', function () { + var r = new BN( + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b', 16); + assert.equal(r.isubn(-1).toString(16), + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681c'); + }); + + it('should work for positive numbers', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(200); + assert.equal(a.negative, 1); + assert.equal(a.toString(), '-300'); + }); + + it('should not allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(-200); + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should change sign on small numbers at 0', function () { + var a = new BN(0).subn(2); + assert.equal(a.toString(), '-2'); + }); + + it('should change sign on small numbers at 1', function () { + var a = new BN(1).subn(2); + assert.equal(a.toString(), '-1'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).isubn(0x4000000); + }); + }); + }); + + function testMethod (name, mul) { + describe(name, function () { + it('should multiply numbers of different signs', function () { + var offsets = [ + 1, // smallMulTo + 250, // comb10MulTo + 1000, // bigMulTo + 15000 // jumboMulTo + ]; + + for (var i = 0; i < offsets.length; ++i) { + var x = new BN(1).ishln(offsets[i]); + + assert.equal(mul(x, x).isNeg(), false); + assert.equal(mul(x, x.neg()).isNeg(), true); + assert.equal(mul(x.neg(), x).isNeg(), true); + assert.equal(mul(x.neg(), x.neg()).isNeg(), false); + } + }); + + it('should multiply with carry', function () { + var n = new BN(0x1001); + var r = n; + + for (var i = 0; i < 4; i++) { + r = mul(r, n); + } + + assert.equal(r.toString(16), '100500a00a005001'); + }); + + it('should correctly multiply big numbers', function () { + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal( + mul(n, n).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40'); + assert.equal( + mul(mul(n, n), n).toString(16), + '1b888e01a06e974017a28a5b4da436169761c9730b7aeedf75fc60f687b' + + '46e0cf2cb11667f795d5569482640fe5f628939467a01a612b02350' + + '0d0161e9730279a7561043af6197798e41b7432458463e64fa81158' + + '907322dc330562697d0d600'); + }); + + it('should multiply neg number on 0', function () { + assert.equal( + mul(new BN('-100000000000'), new BN('3').div(new BN('4'))) + .toString(16), + '0' + ); + }); + + it('should regress mul big numbers', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + assert.equal(mul(q, q).toString(16), qs); + }); + }); + } + + testMethod('.mul()', function (x, y) { + return BN.prototype.mul.apply(x, [ y ]); + }); + + testMethod('.mulf()', function (x, y) { + return BN.prototype.mulf.apply(x, [ y ]); + }); + + describe('.imul()', function () { + it('should multiply numbers in-place', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('deadbeefa551edebabba8', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + + a = new BN('abcdef01234567890abcd214a25123f512361e6d236', 16); + b = new BN('deadbeefa551edebabba8121234fd21bac0341324dd', 16); + c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should multiply by 0', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('0', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should regress mul big numbers in-place', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + + assert.equal(q.isqr().toString(16), qs); + }); + }); + + describe('.muln()', function () { + it('should multiply number by small number', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('dead', 16); + var c = a.mul(b); + + assert.equal(a.muln(0xdead).toString(16), c.toString(16)); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).imuln(0x4000000); + }); + }); + }); + + describe('.pow()', function () { + it('should raise number to the power', function () { + var a = new BN('ab', 16); + var b = new BN('13', 10); + var c = a.pow(b); + + assert.equal(c.toString(16), '15963da06977df51909c9ba5b'); + }); + }); + + describe('.div()', function () { + it('should divide small numbers (<=26 bits)', function () { + assert.equal(new BN('256').div(new BN(10)).toString(10), + '25'); + assert.equal(new BN('-256').div(new BN(10)).toString(10), + '-25'); + assert.equal(new BN('256').div(new BN(-10)).toString(10), + '-25'); + assert.equal(new BN('-256').div(new BN(-10)).toString(10), + '25'); + + assert.equal(new BN('10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('10').div(new BN(-256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(-256)).toString(10), + '0'); + }); + + it('should divide large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').div(new BN('611111124969028')) + .toString(10), '1'); + assert.equal(new BN('-1222222225255589').div(new BN('611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('1222222225255589').div(new BN('-611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('-1222222225255589').div(new BN('-611111124969028')) + .toString(10), '1'); + + assert.equal(new BN('611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + }); + + it('should divide numbers', function () { + assert.equal(new BN('69527932928').div(new BN('16974594')).toString(16), + 'fff'); + assert.equal(new BN('-69527932928').div(new BN('16974594')).toString(16), + '-fff'); + + var b = new BN( + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40', + 16); + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal(b.div(n).toString(16), n.toString(16)); + + assert.equal(new BN('1').div(new BN('-5')).toString(10), '0'); + }); + + it('should not fail on regression after moving to _wordDiv', function () { + // Regression after moving to word div + var p = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', + 16); + var a = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16); + var as = a.sqr(); + assert.equal( + as.div(p).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729e58090b9'); + + p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.div(p).toString(16), + 'ffffffff00000002000000000000000000000001000000000000000000000001'); + }); + }); + + describe('.idivn()', function () { + it('should divide numbers in-place', function () { + assert.equal(new BN('10', 16).idivn(3).toString(16), '5'); + assert.equal(new BN('12', 16).idivn(3).toString(16), '6'); + assert.equal(new BN('10000000000000000').idivn(3).toString(10), + '3333333333333333'); + assert.equal( + new BN('100000000000000000000000000000').idivn(3).toString(10), + '33333333333333333333333333333'); + + var t = new BN(3); + assert.equal( + new BN('12345678901234567890123456', 16).idivn(3).toString(16), + new BN('12345678901234567890123456', 16).div(t).toString(16)); + }); + }); + + describe('.divRound()', function () { + it('should divide numbers with rounding', function () { + assert.equal(new BN(9).divRound(new BN(20)).toString(10), + '0'); + assert.equal(new BN(10).divRound(new BN(20)).toString(10), + '1'); + assert.equal(new BN(150).divRound(new BN(20)).toString(10), + '8'); + assert.equal(new BN(149).divRound(new BN(20)).toString(10), + '7'); + assert.equal(new BN(149).divRound(new BN(17)).toString(10), + '9'); + assert.equal(new BN(144).divRound(new BN(17)).toString(10), + '8'); + assert.equal(new BN(-144).divRound(new BN(17)).toString(10), + '-8'); + }); + + it('should return 1 on exact division', function () { + assert.equal(new BN(144).divRound(new BN(144)).toString(10), '1'); + }); + }); + + describe('.mod()', function () { + it('should modulo small numbers (<=26 bits)', function () { + assert.equal(new BN('256').mod(new BN(10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(10)).toString(10), + '-6'); + assert.equal(new BN('256').mod(new BN(-10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(-10)).toString(10), + '-6'); + + assert.equal(new BN('10').mod(new BN(256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(256)).toString(10), + '-10'); + assert.equal(new BN('10').mod(new BN(-256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(-256)).toString(10), + '-10'); + }); + + it('should modulo large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').mod(new BN('611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('611111124969028')) + .toString(10), '-611111100286561'); + assert.equal(new BN('1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '-611111100286561'); + + assert.equal(new BN('611111124969028').mod(new BN('1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('1222222225255589')) + .toString(10), '-611111124969028'); + assert.equal(new BN('611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '-611111124969028'); + }); + + it('should mod numbers', function () { + assert.equal(new BN('10').mod(new BN(256)).toString(16), + 'a'); + assert.equal(new BN('69527932928').mod(new BN('16974594')).toString(16), + '102f302'); + + // 178 = 10 * 17 + 8 + assert.equal(new BN(178).div(new BN(10)).toNumber(), 17); + assert.equal(new BN(178).mod(new BN(10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(10)).toNumber(), 8); + + // -178 = 10 * (-17) + (-8) + assert.equal(new BN(-178).div(new BN(10)).toNumber(), -17); + assert.equal(new BN(-178).mod(new BN(10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(10)).toNumber(), 2); + + // 178 = -10 * (-17) + 8 + assert.equal(new BN(178).div(new BN(-10)).toNumber(), -17); + assert.equal(new BN(178).mod(new BN(-10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(-10)).toNumber(), 8); + + // -178 = -10 * (17) + (-8) + assert.equal(new BN(-178).div(new BN(-10)).toNumber(), 17); + assert.equal(new BN(-178).mod(new BN(-10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(-10)).toNumber(), 2); + + // -4 = 1 * (-3) + -1 + assert.equal(new BN(-4).div(new BN(-3)).toNumber(), 1); + assert.equal(new BN(-4).mod(new BN(-3)).toNumber(), -1); + + // -4 = -1 * (3) + -1 + assert.equal(new BN(-4).mod(new BN(3)).toNumber(), -1); + // -4 = 1 * (-3) + (-1 + 3) + assert.equal(new BN(-4).umod(new BN(-3)).toNumber(), 2); + + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.mod(p).toString(16), + '0'); + }); + + it('should properly carry the sign inside division', function () { + var a = new BN('945304eb96065b2a98b57a48a06ae28d285a71b5', 'hex'); + var b = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe', + 'hex'); + + assert.equal(a.mul(b).mod(a).cmpn(0), 0); + }); + }); + + describe('.modn()', function () { + it('should act like .mod() on small numbers', function () { + assert.equal(new BN('10', 16).modn(256).toString(16), '10'); + assert.equal(new BN('100', 16).modn(256).toString(16), '0'); + assert.equal(new BN('1001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(257).toString(16), + new BN('100000000001', 16).mod(new BN(257)).toString(16)); + assert.equal(new BN('123456789012', 16).modn(3).toString(16), + new BN('123456789012', 16).mod(new BN(3)).toString(16)); + }); + }); + + describe('.abs()', function () { + it('should return absolute value', function () { + assert.equal(new BN(0x1001).abs().toString(), '4097'); + assert.equal(new BN(-0x1001).abs().toString(), '4097'); + assert.equal(new BN('ffffffff', 16).abs().toString(), '4294967295'); + }); + }); + + describe('.invm()', function () { + it('should invert relatively-prime numbers', function () { + var p = new BN(257); + var a = new BN(3); + var b = a.invm(p); + assert.equal(a.mul(b).mod(p).toString(16), '1'); + + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + a = new BN('deadbeef', 16); + b = a.invm(p192); + assert.equal(a.mul(b).mod(p192).toString(16), '1'); + + // Even base + var phi = new BN('872d9b030ba368706b68932cf07a0e0c', 16); + var e = new BN(65537); + var d = e.invm(phi); + assert.equal(e.mul(d).mod(phi).toString(16), '1'); + + // Even base (take #2) + a = new BN('5'); + b = new BN('6'); + var r = a.invm(b); + assert.equal(r.mul(a).mod(b).toString(16), '1'); + }); + }); + + describe('.gcd()', function () { + it('should return GCD', function () { + assert.equal(new BN(3).gcd(new BN(2)).toString(10), '1'); + assert.equal(new BN(18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(-12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(0)).toString(10), '18'); + assert.equal(new BN(0).gcd(new BN(-18)).toString(10), '18'); + assert.equal(new BN(2).gcd(new BN(0)).toString(10), '2'); + assert.equal(new BN(0).gcd(new BN(3)).toString(10), '3'); + assert.equal(new BN(0).gcd(new BN(0)).toString(10), '0'); + }); + }); + + describe('.egcd()', function () { + it('should return EGCD', function () { + assert.equal(new BN(3).egcd(new BN(2)).gcd.toString(10), '1'); + assert.equal(new BN(18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(-18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(0).egcd(new BN(12)).gcd.toString(10), '12'); + }); + it('should not allow 0 input', function () { + assert.throws(function () { + BN(1).egcd(0); + }); + }); + it('should not allow negative input', function () { + assert.throws(function () { + BN(1).egcd(-1); + }); + }); + }); + + describe('BN.max(a, b)', function () { + it('should return maximum', function () { + assert.equal(BN.max(new BN(3), new BN(2)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(3)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.max(new BN(2), new BN(-2)).toString(16), '2'); + }); + }); + + describe('BN.min(a, b)', function () { + it('should return minimum', function () { + assert.equal(BN.min(new BN(3), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(3)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(-2)).toString(16), '-2'); + }); + }); + + describe('BN.ineg', function () { + it('shouldn\'t change sign for zero', function () { + assert.equal(new BN(0).ineg().toString(10), '0'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/binary-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/binary-test.js new file mode 100644 index 0000000..b73242c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/binary-test.js @@ -0,0 +1,228 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Binary', function () { + describe('.shl()', function () { + it('should shl numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').shln(45).toString(16), + '206060200000000000000'); + }); + + it('should ushl numbers', function () { + assert.equal(new BN('69527932928').ushln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').ushln(45).toString(16), + '206060200000000000000'); + }); + }); + + describe('.shr()', function () { + it('should shr numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').shrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').shrn(256).toString(16), + '0'); + }); + + it('should ushr numbers', function () { + assert.equal(new BN('69527932928').ushrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').ushrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').ushrn(256).toString(16), + '0'); + }); + }); + + describe('.bincn()', function () { + it('should increment bit', function () { + assert.equal(new BN(0).bincn(1).toString(16), '2'); + assert.equal(new BN(2).bincn(1).toString(16), '4'); + assert.equal(new BN(2).bincn(1).bincn(1).toString(16), + new BN(2).bincn(2).toString(16)); + assert.equal(new BN(0xffffff).bincn(1).toString(16), '1000001'); + assert.equal(new BN(2).bincn(63).toString(16), + '8000000000000002'); + }); + }); + + describe('.imaskn()', function () { + it('should mask bits in-place', function () { + assert.equal(new BN(0).imaskn(1).toString(16), '0'); + assert.equal(new BN(3).imaskn(1).toString(16), '1'); + assert.equal(new BN('123456789', 16).imaskn(4).toString(16), '9'); + assert.equal(new BN('123456789', 16).imaskn(16).toString(16), '6789'); + assert.equal(new BN('123456789', 16).imaskn(28).toString(16), '3456789'); + }); + }); + + describe('.testn()', function () { + it('should support test specific bit', function () { + [ + 'ff', + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' + ].forEach(function (hex) { + var bn = new BN(hex, 16); + var bl = bn.bitLength(); + + for (var i = 0; i < bl; ++i) { + assert.equal(bn.testn(i), true); + } + + // test off the end + assert.equal(bn.testn(bl), false); + }); + + var xbits = '01111001010111001001000100011101' + + '11010011101100011000111001011101' + + '10010100111000000001011000111101' + + '01011111001111100100011110000010' + + '01011010100111010001010011000100' + + '01101001011110100001001111100110' + + '001110010111'; + + var x = new BN( + '23478905234580795234378912401239784125643978256123048348957342' + ); + for (var i = 0; i < x.bitLength(); ++i) { + assert.equal(x.testn(i), (xbits.charAt(i) === '1'), 'Failed @ bit ' + i); + } + }); + + it('should have short-cuts', function () { + var x = new BN('abcd', 16); + assert(!x.testn(128)); + }); + }); + + describe('.and()', function () { + it('should and numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .and(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .and(new BN('abcd', 16)).toString(16), + 'abcd'); + }); + }); + + describe('.iand()', function () { + it('should iand numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .iand(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + assert.equal(new BN('1000000000000000000000000000000000000001', 2) + .iand(new BN('1', 2)) + .toString(2), '1'); + assert.equal(new BN('1', 2) + .iand(new BN('1000000000000000000000000000000000000001', 2)) + .toString(2), '1'); + }); + }); + + describe('.or()', function () { + it('should or numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .or(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + }); + + it('should or numbers of different limb-length', function () { + assert.equal( + new BN('abcd00000000', 16) + .or(new BN('abcd', 16)).toString(16), + 'abcd0000abcd'); + }); + }); + + describe('.ior()', function () { + it('should ior numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .ior(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + assert.equal(new BN('1000000000000000000000000000000000000000', 2) + .ior(new BN('1', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + assert.equal(new BN('1', 2) + .ior(new BN('1000000000000000000000000000000000000000', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + }); + }); + + describe('.xor()', function () { + it('should xor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .xor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + }); + }); + + describe('.ixor()', function () { + it('should ixor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1', 2)) + .toString(2), '11001100110011001100110011001101'); + assert.equal(new BN('1', 2) + .ixor(new BN('11001100110011001100110011001100', 2)) + .toString(2), '11001100110011001100110011001101'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .xor(new BN('abcd', 16)).toString(16), + 'abcd00005432'); + }); + }); + + describe('.setn()', function () { + it('should allow single bits to be set', function () { + assert.equal(new BN(0).setn(2, true).toString(2), '100'); + assert.equal(new BN(0).setn(27, true).toString(2), + '1000000000000000000000000000'); + assert.equal(new BN(0).setn(63, true).toString(16), + new BN(1).iushln(63).toString(16)); + assert.equal(new BN('1000000000000000000000000001', 2).setn(27, false) + .toString(2), '1'); + assert.equal(new BN('101', 2).setn(2, false).toString(2), '1'); + }); + }); + + describe('.notn()', function () { + it('should allow bitwise negation', function () { + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(32).toString(2), + '11111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(32).toString(2), + '11111111111111111111111111000111'); + assert.equal(new BN('111000111', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111111000111'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/constructor-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/constructor-test.js new file mode 100644 index 0000000..bad412b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/constructor-test.js @@ -0,0 +1,149 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Constructor', function () { + describe('with Smi input', function () { + it('should accept one limb number', function () { + assert.equal(new BN(12345).toString(16), '3039'); + }); + + it('should accept two-limb number', function () { + assert.equal(new BN(0x4123456).toString(16), '4123456'); + }); + + it('should accept 52 bits of precision', function () { + var num = Math.pow(2, 52); + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should accept max safe integer', function () { + var num = Math.pow(2, 53) - 1; + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should not accept an unsafe integer', function () { + var num = Math.pow(2, 53); + + assert.throws(function () { + BN(num, 10); + }); + }); + + it('should accept two-limb LE number', function () { + assert.equal(new BN(0x4123456, null, 'le').toString(16), '56341204'); + }); + }); + + describe('with String input', function () { + it('should accept base-16', function () { + assert.equal(new BN('1A6B765D8CDF', 16).toString(16), '1a6b765d8cdf'); + assert.equal(new BN('1A6B765D8CDF', 16).toString(), '29048849665247'); + }); + + it('should accept base-hex', function () { + assert.equal(new BN('FF', 'hex').toString(), '255'); + }); + + it('should accept base-16 with spaces', function () { + var num = 'a89c e5af8724 c0a23e0e 0ff77500'; + assert.equal(new BN(num, 16).toString(16), num.replace(/ /g, '')); + }); + + it('should accept long base-16', function () { + var num = '123456789abcdef123456789abcdef123456789abcdef'; + assert.equal(new BN(num, 16).toString(16), num); + }); + + it('should accept positive base-10', function () { + assert.equal(new BN('10654321').toString(), '10654321'); + assert.equal(new BN('29048849665247').toString(16), '1a6b765d8cdf'); + }); + + it('should accept negative base-10', function () { + assert.equal(new BN('-29048849665247').toString(16), '-1a6b765d8cdf'); + }); + + it('should accept long base-10', function () { + var num = '10000000000000000'; + assert.equal(new BN(num).toString(10), num); + }); + + it('should accept base-2', function () { + var base2 = '11111111111111111111111111111111111111111111111111111'; + assert.equal(new BN(base2, 2).toString(2), base2); + }); + + it('should accept base-36', function () { + var base36 = 'zzZzzzZzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'; + assert.equal(new BN(base36, 36).toString(36), base36.toLowerCase()); + }); + + it('should not overflow limbs during base-10', function () { + var num = '65820182292848241686198767302293' + + '20890292528855852623664389292032'; + assert(new BN(num).words[0] < 0x4000000); + }); + + it('should accept base-16 LE integer', function () { + assert.equal(new BN('1A6B765D8CDF', 16, 'le').toString(16), + 'df8c5d766b1a'); + }); + }); + + describe('with Array input', function () { + it('should not fail on empty array', function () { + assert.equal(new BN([]).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN([ 1, 2, 3 ]).toString(16), '10203'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toString(16), '1020304'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ]).toString(16), '102030405'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toString(16), + '102030405060708'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray().join(','), '1,2,3,4'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray().join(','), + '1,2,3,4,5,6,7,8'); + }); + + it('should import little endian', function () { + assert.equal(new BN([ 1, 2, 3 ], 10, 'le').toString(16), '30201'); + assert.equal(new BN([ 1, 2, 3, 4 ], 10, 'le').toString(16), '4030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 10, 'le').toString(16), + '504030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ], 'le').toString(16), + '807060504030201'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray('le').join(','), '4,3,2,1'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray('le').join(','), + '8,7,6,5,4,3,2,1'); + }); + + it('should import big endian with implicit base', function () { + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 'le').toString(16), '504030201'); + }); + }); + + // the Array code is able to handle Buffer + describe('with Buffer input', function () { + it('should not fail on empty Buffer', function () { + assert.equal(new BN(new Buffer(0)).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex')).toString(16), '10203'); + }); + + it('should import little endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex'), 'le').toString(16), '30201'); + }); + }); + + describe('with BN input', function () { + it('should clone BN', function () { + var num = new BN(12345); + assert.equal(new BN(num).toString(10), '12345'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/fixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/fixtures.js new file mode 100644 index 0000000..39fd661 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/fixtures.js @@ -0,0 +1,264 @@ +exports.dhGroups = { + p16: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199' + + 'ffffffffffffffff', + priv: '6d5923e6449122cbbcc1b96093e0b7e4fd3e469f58daddae' + + '53b49b20664f4132675df9ce98ae0cfdcac0f4181ccb643b' + + '625f98104dcf6f7d8e81961e2cab4b5014895260cb977c7d' + + '2f981f8532fb5da60b3676dfe57f293f05d525866053ac7e' + + '65abfd19241146e92e64f309a97ef3b529af4d6189fa416c' + + '9e1a816c3bdf88e5edf48fbd8233ef9038bb46faa95122c0' + + '5a426be72039639cd2d53d37254b3d258960dcb33c255ede' + + '20e9d7b4b123c8b4f4b986f53cdd510d042166f7dd7dca98' + + '7c39ab36381ba30a5fdd027eb6128d2ef8e5802a2194d422' + + 'b05fe6e1cb4817789b923d8636c1ec4b7601c90da3ddc178' + + '52f59217ae070d87f2e75cbfb6ff92430ad26a71c8373452' + + 'ae1cc5c93350e2d7b87e0acfeba401aaf518580937bf0b6c' + + '341f8c49165a47e49ce50853989d07171c00f43dcddddf72' + + '94fb9c3f4e1124e98ef656b797ef48974ddcd43a21fa06d0' + + '565ae8ce494747ce9e0ea0166e76eb45279e5c6471db7df8' + + 'cc88764be29666de9c545e72da36da2f7a352fb17bdeb982' + + 'a6dc0193ec4bf00b2e533efd6cd4d46e6fb237b775615576' + + 'dd6c7c7bbc087a25e6909d1ebc6e5b38e5c8472c0fc429c6' + + 'f17da1838cbcd9bbef57c5b5522fd6053e62ba21fe97c826' + + 'd3889d0cc17e5fa00b54d8d9f0f46fb523698af965950f4b' + + '941369e180f0aece3870d9335f2301db251595d173902cad' + + '394eaa6ffef8be6c', + pub: 'd53703b7340bc89bfc47176d351e5cf86d5a18d9662eca3c' + + '9759c83b6ccda8859649a5866524d77f79e501db923416ca' + + '2636243836d3e6df752defc0fb19cc386e3ae48ad647753f' + + 'bf415e2612f8a9fd01efe7aca249589590c7e6a0332630bb' + + '29c5b3501265d720213790556f0f1d114a9e2071be3620bd' + + '4ee1e8bb96689ac9e226f0a4203025f0267adc273a43582b' + + '00b70b490343529eaec4dcff140773cd6654658517f51193' + + '13f21f0a8e04fe7d7b21ffeca85ff8f87c42bb8d9cb13a72' + + 'c00e9c6e9dfcedda0777af951cc8ccab90d35e915e707d8e' + + '4c2aca219547dd78e9a1a0730accdc9ad0b854e51edd1e91' + + '4756760bab156ca6e3cb9c625cf0870def34e9ac2e552800' + + 'd6ce506d43dbbc75acfa0c8d8fb12daa3c783fb726f187d5' + + '58131779239c912d389d0511e0f3a81969d12aeee670e48f' + + 'ba41f7ed9f10705543689c2506b976a8ffabed45e33795b0' + + '1df4f6b993a33d1deab1316a67419afa31fbb6fdd252ee8c' + + '7c7d1d016c44e3fcf6b41898d7f206aa33760b505e4eff2e' + + 'c624bc7fe636b1d59e45d6f904fc391419f13d1f0cdb5b6c' + + '2378b09434159917dde709f8a6b5dc30994d056e3f964371' + + '11587ac7af0a442b8367a7bd940f752ddabf31cf01171e24' + + 'd78df136e9681cd974ce4f858a5fb6efd3234a91857bb52d' + + '9e7b414a8bc66db4b5a73bbeccfb6eb764b4f0cbf0375136' + + 'b024b04e698d54a5' + }, + p17: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934028492' + + '36c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bd' + + 'f8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831' + + '179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1b' + + 'db7f1447e6cc254b332051512bd7af426fb8f401378cd2bf' + + '5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6' + + 'd55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f3' + + '23a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aa' + + 'cc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be328' + + '06a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55c' + + 'da56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee' + + '12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff', + priv: '6017f2bc23e1caff5b0a8b4e1fc72422b5204415787801dc' + + '025762b8dbb98ab57603aaaa27c4e6bdf742b4a1726b9375' + + 'a8ca3cf07771779589831d8bd18ddeb79c43e7e77d433950' + + 'e652e49df35b11fa09644874d71d62fdaffb580816c2c88c' + + '2c4a2eefd4a660360316741b05a15a2e37f236692ad3c463' + + 'fff559938fc6b77176e84e1bb47fb41af691c5eb7bb81bd8' + + 'c918f52625a1128f754b08f5a1403b84667231c4dfe07ed4' + + '326234c113931ce606037e960f35a2dfdec38a5f057884d3' + + '0af8fab3be39c1eeb390205fd65982191fc21d5aa30ddf51' + + 'a8e1c58c0c19fc4b4a7380ea9e836aaf671c90c29bc4bcc7' + + '813811aa436a7a9005de9b507957c56a9caa1351b6efc620' + + '7225a18f6e97f830fb6a8c4f03b82f4611e67ab9497b9271' + + 'd6ac252793cc3e5538990dbd894d2dbc2d152801937d9f74' + + 'da4b741b50b4d40e4c75e2ac163f7b397fd555648b249f97' + + 'ffe58ffb6d096aa84534c4c5729cff137759bd34e80db4ab' + + '47e2b9c52064e7f0bf677f72ac9e5d0c6606943683f9d12f' + + '180cf065a5cb8ec3179a874f358847a907f8471d15f1e728' + + '7023249d6d13c82da52628654438f47b8b5cdf4761fbf6ad' + + '9219eceac657dbd06cf2ab776ad4c968f81c3d039367f0a4' + + 'd77c7ec4435c27b6c147071665100063b5666e06eb2fb2cc' + + '3159ba34bc98ca346342195f6f1fb053ddc3bc1873564d40' + + '1c6738cdf764d6e1ff25ca5926f80102ea6593c17170966b' + + 'b5d7352dd7fb821230237ea3ebed1f920feaadbd21be295a' + + '69f2083deae9c5cdf5f4830eb04b7c1f80cc61c17232d79f' + + '7ecc2cc462a7965f804001c89982734e5abba2d31df1b012' + + '152c6b226dff34510b54be8c2cd68d795def66c57a3abfb6' + + '896f1d139e633417f8c694764974d268f46ece3a8d6616ea' + + 'a592144be48ee1e0a1595d3e5edfede5b27cec6c48ceb2ff' + + 'b42cb44275851b0ebf87dfc9aa2d0cb0805e9454b051dfe8' + + 'a29fadd82491a4b4c23f2d06ba45483ab59976da1433c9ce' + + '500164b957a04cf62dd67595319b512fc4b998424d1164dd' + + 'bbe5d1a0f7257cbb04ec9b5ed92079a1502d98725023ecb2', + pub: '3bf836229c7dd874fe37c1790d201e82ed8e192ed61571ca' + + '7285264974eb2a0171f3747b2fc23969a916cbd21e14f7e2' + + 'f0d72dcd2247affba926f9e7bb99944cb5609aed85e71b89' + + 'e89d2651550cb5bd8281bd3144066af78f194032aa777739' + + 'cccb7862a1af401f99f7e5c693f25ddce2dedd9686633820' + + 'd28d0f5ed0c6b5a094f5fe6170b8e2cbc9dff118398baee6' + + 'e895a6301cb6e881b3cae749a5bdf5c56fc897ff68bc73f2' + + '4811bb108b882872bade1f147d886a415cda2b93dd90190c' + + 'be5c2dd53fe78add5960e97f58ff2506afe437f4cf4c912a' + + '397c1a2139ac6207d3ab76e6b7ffd23bb6866dd7f87a9ae5' + + '578789084ff2d06ea0d30156d7a10496e8ebe094f5703539' + + '730f5fdbebc066de417be82c99c7da59953071f49da7878d' + + 'a588775ff2a7f0084de390f009f372af75cdeba292b08ea8' + + '4bd13a87e1ca678f9ad148145f7cef3620d69a891be46fbb' + + 'cad858e2401ec0fd72abdea2f643e6d0197b7646fbb83220' + + '0f4cf7a7f6a7559f9fb0d0f1680822af9dbd8dec4cd1b5e1' + + '7bc799e902d9fe746ddf41da3b7020350d3600347398999a' + + 'baf75d53e03ad2ee17de8a2032f1008c6c2e6618b62f225b' + + 'a2f350179445debe68500fcbb6cae970a9920e321b468b74' + + '5fb524fb88abbcacdca121d737c44d30724227a99745c209' + + 'b970d1ff93bbc9f28b01b4e714d6c9cbd9ea032d4e964d8e' + + '8fff01db095160c20b7646d9fcd314c4bc11bcc232aeccc0' + + 'fbedccbc786951025597522eef283e3f56b44561a0765783' + + '420128638c257e54b972a76e4261892d81222b3e2039c61a' + + 'ab8408fcaac3d634f848ab3ee65ea1bd13c6cd75d2e78060' + + 'e13cf67fbef8de66d2049e26c0541c679fff3e6afc290efe' + + '875c213df9678e4a7ec484bc87dae5f0a1c26d7583e38941' + + 'b7c68b004d4df8b004b666f9448aac1cc3ea21461f41ea5d' + + 'd0f7a9e6161cfe0f58bcfd304bdc11d78c2e9d542e86c0b5' + + '6985cc83f693f686eaac17411a8247bf62f5ccc7782349b5' + + 'cc1f20e312fa2acc0197154d1bfee507e8db77e8f2732f2d' + + '641440ccf248e8643b2bd1e1f9e8239356ab91098fcb431d', + q: 'a899c59999bf877d96442d284359783bdc64b5f878b688fe' + + '51407f0526e616553ad0aaaac4d5bed3046f10a1faaf42bb' + + '2342dc4b7908eea0c46e4c4576897675c2bfdc4467870d3d' + + 'cd90adaed4359237a4bc6924bfb99aa6bf5f5ede15b574ea' + + 'e977eac096f3c67d09bda574c6306c6123fa89d2f086b8dc' + + 'ff92bc570c18d83fe6c810ccfd22ce4c749ef5e6ead3fffe' + + 'c63d95e0e3fde1df9db6a35fa1d107058f37e41957769199' + + 'd945dd7a373622c65f0af3fd9eb1ddc5c764bbfaf7a3dc37' + + '2548e683b970dac4aa4b9869080d2376c9adecebb84e172c' + + '09aeeb25fb8df23e60033260c4f8aac6b8b98ab894b1fb84' + + 'ebb83c0fb2081c3f3eee07f44e24d8fabf76f19ed167b0d7' + + 'ff971565aa4efa3625fce5a43ceeaa3eebb3ce88a00f597f' + + '048c69292b38dba2103ecdd5ec4ccfe3b2d87fa6202f334b' + + 'c1cab83b608dfc875b650b69f2c7e23c0b2b4adf149a6100' + + 'db1b6dbad4679ecb1ea95eafaba3bd00db11c2134f5a8686' + + '358b8b2ab49a1b2e85e1e45caeac5cd4dc0b3b5fffba8871' + + '1c6baf399edd48dad5e5c313702737a6dbdcede80ca358e5' + + '1d1c4fe42e8948a084403f61baed38aa9a1a5ce2918e9f33' + + '100050a430b47bc592995606440272a4994677577a6aaa1b' + + 'a101045dbec5a4e9566dab5445d1af3ed19519f07ac4e2a8' + + 'bd0a84b01978f203a9125a0be020f71fab56c2c9e344d4f4' + + '12d53d3cd8eb74ca5122002e931e3cb0bd4b7492436be17a' + + 'd7ebe27148671f59432c36d8c56eb762655711cfc8471f70' + + '83a8b7283bcb3b1b1d47d37c23d030288cfcef05fbdb4e16' + + '652ee03ee7b77056a808cd700bc3d9ef826eca9a59be959c' + + '947c865d6b372a1ca2d503d7df6d7611b12111665438475a' + + '1c64145849b3da8c2d343410df892d958db232617f9896f1' + + 'de95b8b5a47132be80dd65298c7f2047858409bf762dbc05' + + 'a62ca392ac40cfb8201a0607a2cae07d99a307625f2b2d04' + + 'fe83fbd3ab53602263410f143b73d5b46fc761882e78c782' + + 'd2c36e716a770a7aefaf7f76cea872db7bffefdbc4c2f9e0' + + '39c19adac915e7a63dcb8c8c78c113f29a3e0bc10e100ce0', + qs: '6f0a2fb763eaeb8eb324d564f03d4a55fdcd709e5f1b65e9' + + '5702b0141182f9f945d71bc3e64a7dfdae7482a7dd5a4e58' + + 'bc38f78de2013f2c468a621f08536969d2c8d011bb3bc259' + + '2124692c91140a5472cad224acdacdeae5751dadfdf068b8' + + '77bfa7374694c6a7be159fc3d24ff9eeeecaf62580427ad8' + + '622d48c51a1c4b1701d768c79d8c819776e096d2694107a2' + + 'f3ec0c32224795b59d32894834039dacb369280afb221bc0' + + '90570a93cf409889b818bb30cccee98b2aa26dbba0f28499' + + '08e1a3cd43fa1f1fb71049e5c77c3724d74dc351d9989057' + + '37bbda3805bd6b1293da8774410fb66e3194e18cdb304dd9' + + 'a0b59b583dcbc9fc045ac9d56aea5cfc9f8a0b95da1e11b7' + + '574d1f976e45fe12294997fac66ca0b83fc056183549e850' + + 'a11413cc4abbe39a211e8c8cbf82f2a23266b3c10ab9e286' + + '07a1b6088909cddff856e1eb6b2cde8bdac53fa939827736' + + 'ca1b892f6c95899613442bd02dbdb747f02487718e2d3f22' + + 'f73734d29767ed8d0e346d0c4098b6fdcb4df7d0c4d29603' + + '5bffe80d6c65ae0a1b814150d349096baaf950f2caf298d2' + + 'b292a1d48cf82b10734fe8cedfa16914076dfe3e9b51337b' + + 'ed28ea1e6824bb717b641ca0e526e175d3e5ed7892aebab0' + + 'f207562cc938a821e2956107c09b6ce4049adddcd0b7505d' + + '49ae6c69a20122461102d465d93dc03db026be54c303613a' + + 'b8e5ce3fd4f65d0b6162ff740a0bf5469ffd442d8c509cd2' + + '3b40dab90f6776ca17fc0678774bd6eee1fa85ababa52ec1' + + 'a15031eb677c6c488661dddd8b83d6031fe294489ded5f08' + + '8ad1689a14baeae7e688afa3033899c81f58de39b392ca94' + + 'af6f15a46f19fa95c06f9493c8b96a9be25e78b9ea35013b' + + 'caa76de6303939299d07426a88a334278fc3d0d9fa71373e' + + 'be51d3c1076ab93a11d3d0d703366ff8cde4c11261d488e5' + + '60a2bdf3bfe2476032294800d6a4a39d306e65c6d7d8d66e' + + '5ec63eee94531e83a9bddc458a2b508285c0ee10b7bd94da' + + '2815a0c5bd5b2e15cbe66355e42f5af8955cdfc0b3a4996d' + + '288db1f4b32b15643b18193e378cb7491f3c3951cdd044b1' + + 'a519571bffac2da986f5f1d506c66530a55f70751e24fa8e' + + 'd83ac2347f4069fb561a5565e78c6f0207da24e889a93a96' + + '65f717d9fe8a2938a09ab5f81be7ccecf466c0397fc15a57' + + '469939793f302739765773c256a3ca55d0548afd117a7cae' + + '98ca7e0d749a130c7b743d376848e255f8fdbe4cb4480b63' + + 'cd2c015d1020cf095d175f3ca9dcdfbaf1b2a6e6468eee4c' + + 'c750f2132a77f376bd9782b9d0ff4da98621b898e251a263' + + '4301ba2214a8c430b2f7a79dbbfd6d7ff6e9b0c137b025ff' + + '587c0bf912f0b19d4fff96b1ecd2ca990c89b386055c60f2' + + '3b94214bd55096f17a7b2c0fa12b333235101cd6f28a128c' + + '782e8a72671adadebbd073ded30bd7f09fb693565dcf0bf3' + + '090c21d13e5b0989dd8956f18f17f4f69449a13549c9d80a' + + '77e5e61b5aeeee9528634100e7bc390672f0ded1ca53555b' + + 'abddbcf700b9da6192255bddf50a76b709fbed251dce4c7e' + + '1ca36b85d1e97c1bc9d38c887a5adf140f9eeef674c31422' + + 'e65f63cae719f8c1324e42fa5fd8500899ef5aa3f9856aa7' + + 'ce10c85600a040343204f36bfeab8cfa6e9deb8a2edd2a8e' + + '018d00c7c9fa3a251ad0f57183c37e6377797653f382ec7a' + + '2b0145e16d3c856bc3634b46d90d7198aff12aff88a30e34' + + 'e2bfaf62705f3382576a9d3eeb0829fca2387b5b654af46e' + + '5cf6316fb57d59e5ea6c369061ac64d99671b0e516529dd5' + + 'd9c48ea0503e55fee090d36c5ea8b5954f6fcc0060794e1c' + + 'b7bc24aa1e5c0142fd4ce6e8fd5aa92a7bf84317ea9e1642' + + 'b6995bac6705adf93cbce72433ed0871139970d640f67b78' + + 'e63a7a6d849db2567df69ac7d79f8c62664ac221df228289' + + 'd0a4f9ebd9acb4f87d49da64e51a619fd3f3baccbd9feb12' + + '5abe0cc2c8d17ed1d8546da2b6c641f4d3020a5f9b9f26ac' + + '16546c2d61385505612275ea344c2bbf1ce890023738f715' + + '5e9eba6a071678c8ebd009c328c3eb643679de86e69a9fa5' + + '67a9e146030ff03d546310a0a568c5ba0070e0da22f2cef8' + + '54714b04d399bbc8fd261f9e8efcd0e83bdbc3f5cfb2d024' + + '3e398478cc598e000124eb8858f9df8f52946c2a1ca5c400' + } +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/pummel/dh-group-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/pummel/dh-group-test.js new file mode 100644 index 0000000..37a259f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/pummel/dh-group-test.js @@ -0,0 +1,23 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../../').BN; +var fixtures = require('../fixtures'); + +describe('BN.js/Slow DH test', function () { + var groups = fixtures.dhGroups; + Object.keys(groups).forEach(function (name) { + it('should match public key for ' + name + ' group', function () { + var group = groups[name]; + + this.timeout(3600 * 1000); + + var base = new BN(2); + var mont = BN.red(new BN(group.prime, 16)); + var priv = new BN(group.priv, 16); + var multed = base.toRed(mont).redPow(priv).fromRed(); + var actual = new Buffer(multed.toArray()); + assert.equal(actual.toString('hex'), group.pub); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/red-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/red-test.js new file mode 100644 index 0000000..5f78b83 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/red-test.js @@ -0,0 +1,249 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Reduction context', function () { + function testMethod (name, fn) { + describe(name + ' method', function () { + it('should support add, iadd, sub, isub operations', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(123).toRed(m); + var b = new BN(231).toRed(m); + + assert.equal(a.redAdd(b).fromRed().toString(10), '97'); + assert.equal(a.redSub(b).fromRed().toString(10), '149'); + assert.equal(b.redSub(a).fromRed().toString(10), '108'); + + assert.equal(a.clone().redIAdd(b).fromRed().toString(10), '97'); + assert.equal(a.clone().redISub(b).fromRed().toString(10), '149'); + assert.equal(b.clone().redISub(a).fromRed().toString(10), '108'); + }); + + it('should support pow and mul operations', function () { + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p192); + var a = new BN(123); + var b = new BN(231); + var c = a.toRed(m).redMul(b.toRed(m)).fromRed(); + assert(c.cmp(a.mul(b).mod(p192)) === 0); + + assert.equal(a.toRed(m).redPow(new BN(3)).fromRed() + .cmp(a.sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(4)).fromRed() + .cmp(a.sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(8)).fromRed() + .cmp(a.sqr().sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(9)).fromRed() + .cmp(a.sqr().sqr().sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(17)).fromRed() + .cmp(a.sqr().sqr().sqr().sqr().mul(a)), 0); + assert.equal( + a.toRed(m).redPow(new BN('deadbeefabbadead', 16)).fromRed() + .toString(16), + '3aa0e7e304e320b68ef61592bcb00341866d6fa66e11a4d6'); + }); + + it('should sqrtm numbers', function () { + var p = new BN(263); + var m = fn(p); + var q = new BN(11).toRed(m); + + var qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + m = fn(p); + + q = new BN(13).toRed(m); + qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + // Tonelli-shanks + p = new BN(13); + m = fn(p); + q = new BN(10).toRed(m); + assert.equal(q.redSqrt().fromRed().toString(10), '7'); + }); + + it('should invm numbers', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(3).toRed(m); + var b = a.redInvm(); + assert.equal(a.redMul(b).fromRed().toString(16), '1'); + }); + + it('should invm numbers (regression)', function () { + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'e1d969b8192fbac73ea5b7921896d6a2263d4d4077bb8e5055361d1f7f8163f3', + 16); + + var m = fn(p); + a = a.toRed(m); + + assert.equal(a.redInvm().fromRed().negative, 0); + }); + + it('should imul numbers', function () { + var p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p); + + var a = new BN('deadbeefabbadead', 16); + var b = new BN('abbadeadbeefdead', 16); + var c = a.mul(b).mod(p); + + assert.equal(a.toRed(m).redIMul(b.toRed(m)).fromRed().toString(16), + c.toString(16)); + }); + + it('should pow(base, 0) == 1', function () { + var base = new BN(256).toRed(BN.red('k256')); + var exponent = new BN(0); + var result = base.redPow(exponent); + assert.equal(result.toString(), '1'); + }); + + it('should shl numbers', function () { + var base = new BN(256).toRed(BN.red('k256')); + var result = base.redShl(1); + assert.equal(result.toString(), '512'); + }); + + it('should reduce when converting to red', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(5).toRed(m); + + assert.doesNotThrow(function () { + var b = a.redISub(new BN(512).toRed(m)); + b.redISub(new BN(512).toRed(m)); + }); + }); + + it('redNeg and zero value', function () { + var a = new BN(0).toRed(BN.red('k256')).redNeg(); + assert.equal(a.isZero(), true); + }); + }); + } + + testMethod('Plain', BN.red); + testMethod('Montgomery', BN.mont); + + describe('Pseudo-Mersenne Primes', function () { + it('should reduce numbers mod k256', function () { + var p = BN._prime('k256'); + + assert.equal(p.ireduce(new BN(0xdead)).toString(16), 'dead'); + assert.equal(p.ireduce(new BN('deadbeef', 16)).toString(16), 'deadbeef'); + + var num = new BN('fedcba9876543210fedcba9876543210dead' + + 'fedcba9876543210fedcba9876543210dead', + 16); + var exp = num.mod(p.p).toString(16); + assert.equal(p.ireduce(num).toString(16), exp); + + var regr = new BN('f7e46df64c1815962bf7bc9c56128798' + + '3f4fcef9cb1979573163b477eab93959' + + '335dfb29ef07a4d835d22aa3b6797760' + + '70a8b8f59ba73d56d01a79af9', + 16); + exp = regr.mod(p.p).toString(16); + + assert.equal(p.ireduce(regr).toString(16), exp); + }); + + it('should not fail to invm number mod k256', function () { + var regr2 = new BN( + '6c150c4aa9a8cf1934485d40674d4a7cd494675537bda36d49405c5d2c6f496f', 16); + regr2 = regr2.toRed(BN.red('k256')); + assert.equal(regr2.redInvm().redMul(regr2).fromRed().cmpn(1), 0); + }); + + it('should correctly square the number', function () { + var p = BN._prime('k256').p; + var red = BN.red('k256'); + + var n = new BN('9cd8cb48c3281596139f147c1364a3ed' + + 'e88d3f310fdb0eb98c924e599ca1b3c9', + 16); + var expected = n.sqr().mod(p); + var actual = n.toRed(red).redSqr().fromRed(); + + assert.equal(actual.toString(16), expected.toString(16)); + }); + + it('redISqr should return right result', function () { + var n = new BN('30f28939', 16); + var actual = n.toRed(BN.red('k256')).redISqr().fromRed(); + assert.equal(actual.toString(16), '95bd93d19520eb1'); + }); + }); + + it('should avoid 4.1.0 regresion', function () { + function bits2int (obits, q) { + var bits = new BN(obits); + var shift = (obits.length << 3) - q.bitLength(); + if (shift > 0) { + bits.ishrn(shift); + } + return bits; + } + var t = new Buffer('aff1651e4cd6036d57aa8b2a05ccf1a9d5a40166340ecbbdc55' + + 'be10b568aa0aa3d05ce9a2fcec9df8ed018e29683c6051cb83e' + + '46ce31ba4edb045356a8d0d80b', 'hex'); + var g = new BN('5c7ff6b06f8f143fe8288433493e4769c4d988ace5be25a0e24809670' + + '716c613d7b0cee6932f8faa7c44d2cb24523da53fbe4f6ec3595892d1' + + 'aa58c4328a06c46a15662e7eaa703a1decf8bbb2d05dbe2eb956c142a' + + '338661d10461c0d135472085057f3494309ffa73c611f78b32adbb574' + + '0c361c9f35be90997db2014e2ef5aa61782f52abeb8bd6432c4dd097b' + + 'c5423b285dafb60dc364e8161f4a2a35aca3a10b1c4d203cc76a470a3' + + '3afdcbdd92959859abd8b56e1725252d78eac66e71ba9ae3f1dd24871' + + '99874393cd4d832186800654760e1e34c09e4d155179f9ec0dc4473f9' + + '96bdce6eed1cabed8b6f116f7ad9cf505df0f998e34ab27514b0ffe7', + 16); + var p = new BN('9db6fb5951b66bb6fe1e140f1d2ce5502374161fd6538df1648218642' + + 'f0b5c48c8f7a41aadfa187324b87674fa1822b00f1ecf8136943d7c55' + + '757264e5a1a44ffe012e9936e00c1d3e9310b01c7d179805d3058b2a9' + + 'f4bb6f9716bfe6117c6b5b3cc4d9be341104ad4a80ad6c94e005f4b99' + + '3e14f091eb51743bf33050c38de235567e1b34c3d6a5c0ceaa1a0f368' + + '213c3d19843d0b4b09dcb9fc72d39c8de41f1bf14d4bb4563ca283716' + + '21cad3324b6a2d392145bebfac748805236f5ca2fe92b871cd8f9c36d' + + '3292b5509ca8caa77a2adfc7bfd77dda6f71125a7456fea153e433256' + + 'a2261c6a06ed3693797e7995fad5aabbcfbe3eda2741e375404ae25b', + 16); + var q = new BN('f2c3119374ce76c9356990b465374a17f23f9ed35089bd969f61c6dde' + + '9998c1f', 16); + var k = bits2int(t, q); + var expectedR = '89ec4bb1400eccff8e7d9aa515cd1de7803f2daff09693ee7fd1353e' + + '90a68307'; + var r = g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); + assert.equal(r.toString(16), expectedR); + }); + + it('K256.split for 512 bits number should return equal numbers', function () { + var red = BN.red('k256'); + var input = new BN(1).iushln(512).subn(1); + assert.equal(input.bitLength(), 512); + var output = new BN(0); + red.prime.split(input, output); + assert.equal(input.cmp(output), 0); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/utils-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/utils-test.js new file mode 100644 index 0000000..f51ce4b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/test/utils-test.js @@ -0,0 +1,345 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Utils', function () { + describe('.toString()', function () { + describe('binary padding', function () { + it('should have a length of 256', function () { + var a = new BN(0); + + assert.equal(a.toString(2, 256).length, 256); + }); + }); + describe('hex padding', function () { + it('should have length of 8 from leading 15', function () { + var a = new BN('ffb9602', 16); + + assert.equal(a.toString('hex', 2).length, 8); + }); + + it('should have length of 8 from leading zero', function () { + var a = new BN('fb9604', 16); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 8 from leading zeros', function () { + var a = new BN(0); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 64 from leading 15', function () { + var a = new BN( + 'ffb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 2).length, 64); + }); + + it('should have length of 64 from leading zero', function () { + var a = new BN( + 'fb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 64).length, 64); + }); + }); + }); + + describe('.isNeg()', function () { + it('should return true for negative numbers', function () { + assert.equal(new BN(-1).isNeg(), true); + assert.equal(new BN(1).isNeg(), false); + assert.equal(new BN(0).isNeg(), false); + assert.equal(new BN('-0', 10).isNeg(), false); + }); + }); + + describe('.isOdd()', function () { + it('should return true for odd numbers', function () { + assert.equal(new BN(0).isOdd(), false); + assert.equal(new BN(1).isOdd(), true); + assert.equal(new BN(2).isOdd(), false); + assert.equal(new BN('-0', 10).isOdd(), false); + assert.equal(new BN('-1', 10).isOdd(), true); + assert.equal(new BN('-2', 10).isOdd(), false); + }); + }); + + describe('.isEven()', function () { + it('should return true for even numbers', function () { + assert.equal(new BN(0).isEven(), true); + assert.equal(new BN(1).isEven(), false); + assert.equal(new BN(2).isEven(), true); + assert.equal(new BN('-0', 10).isEven(), true); + assert.equal(new BN('-1', 10).isEven(), false); + assert.equal(new BN('-2', 10).isEven(), true); + }); + }); + + describe('.isZero()', function () { + it('should return true for zero', function () { + assert.equal(new BN(0).isZero(), true); + assert.equal(new BN(1).isZero(), false); + assert.equal(new BN(0xffffffff).isZero(), false); + }); + }); + + describe('.bitLength()', function () { + it('should return proper bitLength', function () { + assert.equal(new BN(0).bitLength(), 0); + assert.equal(new BN(0x1).bitLength(), 1); + assert.equal(new BN(0x2).bitLength(), 2); + assert.equal(new BN(0x3).bitLength(), 2); + assert.equal(new BN(0x4).bitLength(), 3); + assert.equal(new BN(0x8).bitLength(), 4); + assert.equal(new BN(0x10).bitLength(), 5); + assert.equal(new BN(0x100).bitLength(), 9); + assert.equal(new BN(0x123456).bitLength(), 21); + assert.equal(new BN('123456789', 16).bitLength(), 33); + assert.equal(new BN('8023456789', 16).bitLength(), 40); + }); + }); + + describe('.byteLength()', function () { + it('should return proper byteLength', function () { + assert.equal(new BN(0).byteLength(), 0); + assert.equal(new BN(0x1).byteLength(), 1); + assert.equal(new BN(0x2).byteLength(), 1); + assert.equal(new BN(0x3).byteLength(), 1); + assert.equal(new BN(0x4).byteLength(), 1); + assert.equal(new BN(0x8).byteLength(), 1); + assert.equal(new BN(0x10).byteLength(), 1); + assert.equal(new BN(0x100).byteLength(), 2); + assert.equal(new BN(0x123456).byteLength(), 3); + assert.equal(new BN('123456789', 16).byteLength(), 5); + assert.equal(new BN('8023456789', 16).byteLength(), 5); + }); + }); + + describe('.toArray()', function () { + it('should return [ 0 ] for `0`', function () { + var n = new BN(0); + assert.deepEqual(n.toArray('be'), [ 0 ]); + assert.deepEqual(n.toArray('le'), [ 0 ]); + }); + + it('should zero pad to desired lengths', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toArray('be', 5), [ 0x00, 0x00, 0x12, 0x34, 0x56 ]); + assert.deepEqual(n.toArray('le', 5), [ 0x56, 0x34, 0x12, 0x00, 0x00 ]); + }); + + it('should throw when naturally larger than desired length', function () { + var n = new BN(0x123456); + assert.throws(function () { + n.toArray('be', 2); + }); + }); + }); + + describe('.toBuffer', function () { + it('should return proper Buffer', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toBuffer('be', 5).toString('hex'), '0000123456'); + assert.deepEqual(n.toBuffer('le', 5).toString('hex'), '5634120000'); + }); + }); + + describe('.toNumber()', function () { + it('should return proper Number if below the limit', function () { + assert.deepEqual(new BN(0x123456).toNumber(), 0x123456); + assert.deepEqual(new BN(0x3ffffff).toNumber(), 0x3ffffff); + assert.deepEqual(new BN(0x4000000).toNumber(), 0x4000000); + assert.deepEqual(new BN(0x10000000000000).toNumber(), 0x10000000000000); + assert.deepEqual(new BN(0x10040004004000).toNumber(), 0x10040004004000); + assert.deepEqual(new BN(-0x123456).toNumber(), -0x123456); + assert.deepEqual(new BN(-0x3ffffff).toNumber(), -0x3ffffff); + assert.deepEqual(new BN(-0x4000000).toNumber(), -0x4000000); + assert.deepEqual(new BN(-0x10000000000000).toNumber(), -0x10000000000000); + assert.deepEqual(new BN(-0x10040004004000).toNumber(), -0x10040004004000); + }); + + it('should throw when number exceeds 53 bits', function () { + var n = new BN(1).iushln(54); + assert.throws(function () { + n.toNumber(); + }); + }); + }); + + describe('.zeroBits()', function () { + it('should return proper zeroBits', function () { + assert.equal(new BN(0).zeroBits(), 0); + assert.equal(new BN(0x1).zeroBits(), 0); + assert.equal(new BN(0x2).zeroBits(), 1); + assert.equal(new BN(0x3).zeroBits(), 0); + assert.equal(new BN(0x4).zeroBits(), 2); + assert.equal(new BN(0x8).zeroBits(), 3); + assert.equal(new BN(0x10).zeroBits(), 4); + assert.equal(new BN(0x100).zeroBits(), 8); + assert.equal(new BN(0x1000000).zeroBits(), 24); + assert.equal(new BN(0x123456).zeroBits(), 1); + }); + }); + + describe('.toJSON', function () { + it('should return hex string', function () { + assert.equal(new BN(0x123).toJSON(), '123'); + }); + }); + + describe('.cmpn', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmpn(42), 0); + assert.equal(new BN(42).cmpn(43), -1); + assert.equal(new BN(42).cmpn(41), 1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffe), 0); + assert.equal(new BN(0x3fffffe).cmpn(0x3ffffff), -1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffd), 1); + assert.throws(function () { + new BN(0x3fffffe).cmpn(0x4000000); + }); + assert.equal(new BN(42).cmpn(-42), 1); + assert.equal(new BN(-42).cmpn(42), -1); + assert.equal(new BN(-42).cmpn(-42), 0); + assert.equal(1 / new BN(-42).cmpn(-42), Infinity); + }); + }); + + describe('.cmp', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmp(new BN(42)), 0); + assert.equal(new BN(42).cmp(new BN(43)), -1); + assert.equal(new BN(42).cmp(new BN(41)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffe)), 0); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3ffffff)), -1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffd)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x4000000)), -1); + assert.equal(new BN(42).cmp(new BN(-42)), 1); + assert.equal(new BN(-42).cmp(new BN(42)), -1); + assert.equal(new BN(-42).cmp(new BN(-42)), 0); + assert.equal(1 / new BN(-42).cmp(new BN(-42)), Infinity); + }); + }); + + describe('comparison shorthands', function () { + it('.gtn greater than', function () { + assert.equal(new BN(3).gtn(2), true); + assert.equal(new BN(3).gtn(3), false); + assert.equal(new BN(3).gtn(4), false); + }); + it('.gt greater than', function () { + assert.equal(new BN(3).gt(new BN(2)), true); + assert.equal(new BN(3).gt(new BN(3)), false); + assert.equal(new BN(3).gt(new BN(4)), false); + }); + it('.gten greater than or equal', function () { + assert.equal(new BN(3).gten(3), true); + assert.equal(new BN(3).gten(2), true); + assert.equal(new BN(3).gten(4), false); + }); + it('.gte greater than or equal', function () { + assert.equal(new BN(3).gte(new BN(3)), true); + assert.equal(new BN(3).gte(new BN(2)), true); + assert.equal(new BN(3).gte(new BN(4)), false); + }); + it('.ltn less than', function () { + assert.equal(new BN(2).ltn(3), true); + assert.equal(new BN(2).ltn(2), false); + assert.equal(new BN(2).ltn(1), false); + }); + it('.lt less than', function () { + assert.equal(new BN(2).lt(new BN(3)), true); + assert.equal(new BN(2).lt(new BN(2)), false); + assert.equal(new BN(2).lt(new BN(1)), false); + }); + it('.lten less than or equal', function () { + assert.equal(new BN(3).lten(3), true); + assert.equal(new BN(3).lten(2), false); + assert.equal(new BN(3).lten(4), true); + }); + it('.lte less than or equal', function () { + assert.equal(new BN(3).lte(new BN(3)), true); + assert.equal(new BN(3).lte(new BN(2)), false); + assert.equal(new BN(3).lte(new BN(4)), true); + }); + it('.eqn equal', function () { + assert.equal(new BN(3).eqn(3), true); + assert.equal(new BN(3).eqn(2), false); + assert.equal(new BN(3).eqn(4), false); + }); + it('.eq equal', function () { + assert.equal(new BN(3).eq(new BN(3)), true); + assert.equal(new BN(3).eq(new BN(2)), false); + assert.equal(new BN(3).eq(new BN(4)), false); + }); + }); + + describe('.fromTwos', function () { + it('should convert from two\'s complement to negative number', function () { + assert.equal(new BN('00000000', 16).fromTwos(32).toNumber(), 0); + assert.equal(new BN('00000001', 16).fromTwos(32).toNumber(), 1); + assert.equal(new BN('7fffffff', 16).fromTwos(32).toNumber(), 2147483647); + assert.equal(new BN('80000000', 16).fromTwos(32).toNumber(), -2147483648); + assert.equal(new BN('f0000000', 16).fromTwos(32).toNumber(), -268435456); + assert.equal(new BN('f1234567', 16).fromTwos(32).toNumber(), -249346713); + assert.equal(new BN('ffffffff', 16).fromTwos(32).toNumber(), -1); + assert.equal(new BN('fffffffe', 16).fromTwos(32).toNumber(), -2); + assert.equal(new BN('fffffffffffffffffffffffffffffffe', 16) + .fromTwos(128).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'fffffffffffffffffffffffffffffffe', 16).fromTwos(256).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toNumber(), -1); + assert.equal(new BN('7fffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toString(10), + new BN('5789604461865809771178549250434395392663499' + + '2332820282019728792003956564819967', 10).toString(10)); + assert.equal(new BN('80000000000000000000000000000000' + + '00000000000000000000000000000000', 16).fromTwos(256).toString(10), + new BN('-578960446186580977117854925043439539266349' + + '92332820282019728792003956564819968', 10).toString(10)); + }); + }); + + describe('.toTwos', function () { + it('should convert from negative number to two\'s complement', function () { + assert.equal(new BN(0).toTwos(32).toString(16), '0'); + assert.equal(new BN(1).toTwos(32).toString(16), '1'); + assert.equal(new BN(2147483647).toTwos(32).toString(16), '7fffffff'); + assert.equal(new BN('-2147483648', 10).toTwos(32).toString(16), '80000000'); + assert.equal(new BN('-268435456', 10).toTwos(32).toString(16), 'f0000000'); + assert.equal(new BN('-249346713', 10).toTwos(32).toString(16), 'f1234567'); + assert.equal(new BN('-1', 10).toTwos(32).toString(16), 'ffffffff'); + assert.equal(new BN('-2', 10).toTwos(32).toString(16), 'fffffffe'); + assert.equal(new BN('-2', 10).toTwos(128).toString(16), + 'fffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-2', 10).toTwos(256).toString(16), + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-1', 10).toTwos(256).toString(16), + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('5789604461865809771178549250434395392663' + + '4992332820282019728792003956564819967', 10).toTwos(256).toString(16), + '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('-578960446186580977117854925043439539266' + + '34992332820282019728792003956564819968', 10).toTwos(256).toString(16), + '8000000000000000000000000000000000000000000000000000000000000000'); + }); + }); + + describe('.isBN', function () { + it('should return true for BN', function () { + assert.equal(BN.isBN(new BN()), true); + }); + + it('should return false for everything else', function () { + assert.equal(BN.isBN(1), false); + assert.equal(BN.isBN([]), false); + assert.equal(BN.isBN({}), false); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/util/genCombMulTo.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/util/genCombMulTo.js new file mode 100644 index 0000000..8b456c7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/util/genCombMulTo.js @@ -0,0 +1,65 @@ +'use strict'; + +// NOTE: This could be potentionally used to generate loop-less multiplications +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('var w' + k + ' = c;'); + src.push('c = 0;'); + for (var j = minJ; j <= maxJ; j++) { + i = k - j; + + src.push('lo = Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid = Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;'); + src.push('hi = Math.imul(ah' + i + ', bh' + j + ');'); + + src.push('w' + k + ' = (w' + k + ' + lo) | 0;'); + src.push('w' + k + ' = (w' + k + ' + ((mid & 0x1fff) << 13)) | 0;'); + src.push('c = (c + hi) | 0;'); + src.push('c = (c + (mid >>> 13)) | 0;'); + src.push('c = (c + (w' + k + ' >>> 26)) | 0;'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/util/genCombMulTo10.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/util/genCombMulTo10.js new file mode 100644 index 0000000..4214ffd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/bn.js/util/genCombMulTo10.js @@ -0,0 +1,64 @@ +'use strict'; + +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('lo = Math.imul(al' + (k - minJ) + ', bl' + minJ + ');'); + src.push('mid = Math.imul(al' + (k - minJ) + ', bh' + minJ + ');'); + src.push('mid += Math.imul(ah' + (k - minJ) + ', bl' + minJ + ');'); + src.push('hi = Math.imul(ah' + (k - minJ) + ', bh' + minJ + ');'); + + for (var j = minJ + 1; j <= maxJ; j++) { + i = k - j; + + src.push('lo += Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid += Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid += Math.imul(ah' + i + ', bl' + j + ');'); + src.push('hi += Math.imul(ah' + i + ', bh' + j + ');'); + } + + src.push('var w' + k + ' = c + lo + ((mid & 0x1fff) << 13);'); + src.push('c = hi + (mid >>> 13) + (w' + k + ' >>> 26);'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/README.md new file mode 100644 index 0000000..038b709 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/README.md @@ -0,0 +1,170 @@ +# Elliptic [![Build Status](https://secure.travis-ci.org/indutny/elliptic.png)](http://travis-ci.org/indutny/elliptic) [![Coverage Status](https://coveralls.io/repos/indutny/elliptic/badge.svg?branch=master&service=github)](https://coveralls.io/github/indutny/elliptic?branch=master) + +Fast elliptic-curve cryptography in a plain javascript implementation. + +NOTE: Please take a look at http://safecurves.cr.yp.to/ before choosing a curve +for your cryptography operations. + +## Incentive + +ECC is much slower than regular RSA cryptography, the JS implementations are +even more slower. + +## Benchmarks + +```bash +$ node benchmarks/index.js +Benchmarking: sign +elliptic#sign x 262 ops/sec ±0.51% (177 runs sampled) +eccjs#sign x 55.91 ops/sec ±0.90% (144 runs sampled) +------------------------ +Fastest is elliptic#sign +======================== +Benchmarking: verify +elliptic#verify x 113 ops/sec ±0.50% (166 runs sampled) +eccjs#verify x 48.56 ops/sec ±0.36% (125 runs sampled) +------------------------ +Fastest is elliptic#verify +======================== +Benchmarking: gen +elliptic#gen x 294 ops/sec ±0.43% (176 runs sampled) +eccjs#gen x 62.25 ops/sec ±0.63% (129 runs sampled) +------------------------ +Fastest is elliptic#gen +======================== +Benchmarking: ecdh +elliptic#ecdh x 136 ops/sec ±0.85% (156 runs sampled) +------------------------ +Fastest is elliptic#ecdh +======================== +``` + +## API + +### ECDSA + +```javascript +var EC = require('elliptic').ec; + +// Create and initialize EC context +// (better do it once and reuse it) +var ec = new EC('secp256k1'); + +// Generate keys +var key = ec.genKeyPair(); + +// Sign message (must be an array, or it'll be treated as a hex sequence) +var msg = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; +var signature = key.sign(msg); + +// Export DER encoded signature in Array +var derSign = signature.toDER(); + +// Verify signature +console.log(key.verify(msg, derSign)); + +// CHECK WITH NO PRIVATE KEY + +// Public key as '04 + x + y' +var pub = '04bb1fa3...'; + +// Signature MUST be either: +// 1) hex-string of DER-encoded signature; or +// 2) DER-encoded signature as buffer; or +// 3) object with two hex-string properties (r and s) + +var signature = 'b102ac...'; // case 1 +var signature = new Buffer('...'); // case 2 +var signature = { r: 'b1fc...', s: '9c42...' }; // case 3 + +// Import public key +var key = ec.keyFromPublic(pub, 'hex'); + +// Verify signature +console.log(key.verify(msg, signature)); +``` + +### ECDH + +```javascript +// Generate keys +var key1 = ec.genKeyPair(); +var key2 = ec.genKeyPair(); + +var shared1 = key1.derive(key2.getPublic()); +var shared2 = key2.derive(key1.getPublic()); + +console.log('Both shared secrets are BN instances'); +console.log(shared1.toString(16)); +console.log(shared2.toString(16)); +``` + +NOTE: `.derive()` returns a [BN][1] instance. + +## Supported curves + +Elliptic.js support following curve types: + +* Short Weierstrass +* Montgomery +* Edwards +* Twisted Edwards + +Following curve 'presets' are embedded into the library: + +* `secp256k1` +* `p192` +* `p224` +* `p256` +* `p384` +* `p521` +* `curve25519` +* `ed25519` + +NOTE: That `curve25519` could not be used for ECDSA, use `ed25519` instead. + +### Implementation details + +ECDSA is using deterministic `k` value generation as per [RFC6979][0]. Most of +the curve operations are performed on non-affine coordinates (either projective +or extended), various windowing techniques are used for different cases. + +All operations are performed in reduction context using [bn.js][1], hashing is +provided by [hash.js][2] + +### Related projects + +* [eccrypto][3]: isomorphic implementation of ECDSA, ECDH and ECIES for both + browserify and node (uses `elliptic` for browser and [secp256k1-node][4] for + node) + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + +[0]: http://tools.ietf.org/html/rfc6979 +[1]: https://github.com/indutny/bn.js +[2]: https://github.com/indutny/hash.js +[3]: https://github.com/bitchan/eccrypto +[4]: https://github.com/wanderer/secp256k1-node diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic.js new file mode 100644 index 0000000..2291200 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic.js @@ -0,0 +1,14 @@ +'use strict'; + +var elliptic = exports; + +elliptic.version = require('../package.json').version; +elliptic.utils = require('./elliptic/utils'); +elliptic.rand = require('brorand'); +elliptic.hmacDRBG = require('./elliptic/hmac-drbg'); +elliptic.curve = require('./elliptic/curve'); +elliptic.curves = require('./elliptic/curves'); + +// Protocols +elliptic.ec = require('./elliptic/ec'); +elliptic.eddsa = require('./elliptic/eddsa'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/base.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/base.js new file mode 100644 index 0000000..3f84016 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/base.js @@ -0,0 +1,351 @@ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var getNAF = utils.getNAF; +var getJSF = utils.getJSF; +var assert = utils.assert; + +function BaseCurve(type, conf) { + this.type = type; + this.p = new BN(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); + + // Useful for many curves + this.zero = new BN(0).toRed(this.red); + this.one = new BN(1).toRed(this.red); + this.two = new BN(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); +} +module.exports = BaseCurve; + +BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + for (var j = 0; j < naf.length; j += doubles.step) { + var nafW = 0; + for (var k = j + doubles.step - 1; k >= j; k--) + nafW = (nafW << 1) + naf[k]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (var j = 0; j < repr.length; j++) { + var nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; + +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var k = 0; i >= 0 && naf[i] === 0; i--) + k++; + if (i >= 0) + k++; + acc = acc.dblp(k); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; +}; + +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + for (var i = 0; i < len; i++) { + var p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (var i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a]); + naf[b] = getNAF(coeffs[b], wndWidth[b]); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b] /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3 /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (var j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (var i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (var j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (var j = 0; j < len; j++) { + var z = tmp[j]; + var p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (var i = 0; i < len; i++) + wnd[i] = null; + return acc.toP(); +}; + +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} +BaseCurve.BasePoint = BasePoint; + +BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); +}; + +BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); +}; + +BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + if (bytes[0] === 0x04 && bytes.length - 1 === 2 * len) { + return this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); +}; + +BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); +}; + +BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; +}; + +BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); +}; + +BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; +}; + +BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); +}; + +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles + }; +}; + +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res + }; +}; + +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; + +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/edwards.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/edwards.js new file mode 100644 index 0000000..a9889d9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/edwards.js @@ -0,0 +1,410 @@ +'use strict'; + +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var assert = elliptic.utils.assert; + +function EdwardsCurve(conf) { + // NOTE: Important as we are creating point in Base.call() + this.twisted = (conf.a | 0) !== 1; + this.mOneA = this.twisted && (conf.a | 0) === -1; + this.extended = this.mOneA; + + Base.call(this, 'edwards', conf); + + this.a = new BN(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; +} +inherits(EdwardsCurve, Base); +module.exports = EdwardsCurve; + +EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); +}; + +EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); +}; + +// Just for compatibility with Short curve +EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); +}; + +EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN(y, 16); + if (!y.red) + y = y.toRed(this.red); + + // x^2 = (y^2 - 1) / (d y^2 + 1) + var y2 = y.redSqr(); + var lhs = y2.redSub(this.one); + var rhs = y2.redMul(this.d).redAdd(this.one); + var x2 = lhs.redMul(rhs.redInvm()); + + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } + + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + if (x.isOdd() !== odd) + x = x.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); + + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + + return lhs.cmp(rhs) === 0; +}; + +function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } +} +inherits(Point, Base.BasePoint); + +EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + this.y.cmp(this.z) === 0; +}; + +Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + if (this.curve.twisted) { + // E = a * C + var e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + var h = this.z.redSqr(); + // J = F - 2 * H + var j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + var e = c.redAdd(d); + // H = (c * Z1)^2 + var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); + // J = E - 2 * H + var j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); +}; + +Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); +}; + +Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2); +}; + +Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; +}; + +Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); +}; + +Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); +}; + +Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; +}; + +// Compatibility with BaseCurve +Point.prototype.toP = Point.prototype.normalize; +Point.prototype.mixedAdd = Point.prototype.add; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/index.js new file mode 100644 index 0000000..c589281 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var curve = exports; + +curve.base = require('./base'); +curve.short = require('./short'); +curve.mont = require('./mont'); +curve.edwards = require('./edwards'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/mont.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/mont.js new file mode 100644 index 0000000..36207e0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/mont.js @@ -0,0 +1,176 @@ +'use strict'; + +var curve = require('../curve'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; + +function MontCurve(conf) { + Base.call(this, 'mont', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.i4 = new BN(4).toRed(this.red).redInvm(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); +} +inherits(MontCurve, Base); +module.exports = MontCurve; + +MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; +}; + +function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } +} +inherits(Point, Base.BasePoint); + +MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); +}; + +MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); +}; + +MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +Point.prototype.precompute = function precompute() { + // No-op +}; + +Point.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); +}; + +Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); +}; + +Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; +}; + +Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; +}; + +Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; +}; + +Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/short.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/short.js new file mode 100644 index 0000000..dfe25d0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curve/short.js @@ -0,0 +1,909 @@ +'use strict'; + +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var assert = elliptic.utils.assert; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; +}; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + } ]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curves.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curves.js new file mode 100644 index 0000000..1d8015b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/curves.js @@ -0,0 +1,205 @@ +'use strict'; + +var curves = exports; + +var hash = require('hash.js'); +var elliptic = require('../elliptic'); + +var assert = elliptic.utils.assert; + +function PresetCurve(options) { + if (options.type === 'short') + this.curve = new elliptic.curve.short(options); + else if (options.type === 'edwards') + this.curve = new elliptic.curve.edwards(options); + else + this.curve = new elliptic.curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); +} +curves.PresetCurve = PresetCurve; + +function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); +} + +defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' + ] +}); + +defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' + ] +}); + +defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' + ] +}); + +defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' + ] +}); + +defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650' + ] +}); + +defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '0', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9' + ] +}); + +defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658' + ] +}); + +var pre; +try { + pre = require('./precomputed/secp256k1'); +} catch (e) { + pre = undefined; +} + +defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3' + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15' + } + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre + ] +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/index.js new file mode 100644 index 0000000..aec8ef4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/index.js @@ -0,0 +1,222 @@ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +var KeyPair = require('./key'); +var Signature = require('./signature'); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); + + options = elliptic.curves[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof elliptic.curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash for function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(options) { + return new KeyPair(this, options); +}; + +EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); +}; + +EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair.fromPublic(this, pub, enc); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new elliptic.hmacDRBG({ + hash: this.hash, + pers: options.pers, + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + nonce: this.n.toArray() + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + do { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } while (true); +}; + +EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new elliptic.hmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; true; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } +}; + +EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; +}; + +EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var eNeg = n.sub(e); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + var rInv = signature.r.invm(n); + return this.g.mulAdd(eNeg, r, s).mul(rInv); +}; + +EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/key.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/key.js new file mode 100644 index 0000000..8d075fb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/key.js @@ -0,0 +1,107 @@ +'use strict'; + +var BN = require('bn.js'); + +function KeyPair(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; + + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); +} +module.exports = KeyPair; + +KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc + }); +}; + +KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc + }); +}; + +KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; +}; + +KeyPair.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); +}; + +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; +}; + +KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); +}; + +KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); +}; + +// ECDH +KeyPair.prototype.derive = function derive(pub) { + return pub.mul(this.priv).getX(); +}; + +// ECDSA +KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); +}; + +KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); +}; + +KeyPair.prototype.inspect = function inspect() { + return ''; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/signature.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/signature.js new file mode 100644 index 0000000..165b179 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/ec/signature.js @@ -0,0 +1,135 @@ +'use strict'; + +var BN = require('bn.js'); + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +function Signature(options, enc) { + if (options instanceof Signature) + return options; + + if (this._importDER(options, enc)) + return; + + assert(options.r && options.s, 'Signature without r or s'); + this.r = new BN(options.r, 16); + this.s = new BN(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; +} +module.exports = Signature; + +function Position() { + this.place = 0; +} + +function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + } + p.place = off; + return val; +} + +function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); +} + +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0 && (r[1] & 0x80)) { + r = r.slice(1); + } + if (s[0] === 0 && (s[1] & 0x80)) { + s = s.slice(1); + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; +}; + +function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); +} + +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/index.js new file mode 100644 index 0000000..b218a16 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/index.js @@ -0,0 +1,118 @@ +'use strict'; + +var hash = require('hash.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var KeyPair = require('./key'); +var Signature = require('./signature'); + +function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + var curve = elliptic.curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; +} + +module.exports = EDDSA; + +/** +* @param {Array|String} message - message bytes +* @param {Array|String|KeyPair} secret - secret bytes or a keypair +* @returns {Signature} - signature +*/ +EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); +}; + +/** +* @param {Array} message - message bytes +* @param {Array|String|Signature} sig - sig bytes +* @param {Array|String|Point|KeyPair} pub - public key +* @returns {Boolean} - true if public key matches sig of message +*/ +EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); +}; + +EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); +}; + +EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); +}; + +EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); +}; + +EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); +}; + +/** +* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 +* +* EDDSA defines methods for encoding and decoding points and integers. These are +* helper convenience methods, that pass along to utility functions implied +* parameters. +* +*/ +EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; +}; + +EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); +}; + +EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); +}; + +EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); +}; + +EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/key.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/key.js new file mode 100644 index 0000000..64dafe0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/key.js @@ -0,0 +1,96 @@ +'use strict'; + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var cachedProperty = utils.cachedProperty; + +/** +* @param {EDDSA} eddsa - instance +* @param {Object} params - public/private key parameters +* +* @param {Array} [params.secret] - secret seed bytes +* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) +* @param {Array} [params.pub] - public key point encoded as bytes +* +*/ +function KeyPair(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); +} + +KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); +}; + +KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); +}; + +KeyPair.prototype.secret = function secret() { + return this._secret; +}; + +cachedProperty(KeyPair, function pubBytes() { + return this.eddsa.encodePoint(this.pub()); +}); + +cachedProperty(KeyPair, function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); +}); + +cachedProperty(KeyPair, function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; +}); + +cachedProperty(KeyPair, function priv() { + return this.eddsa.decodeInt(this.privBytes()); +}); + +cachedProperty(KeyPair, function hash() { + return this.eddsa.hash().update(this.secret()).digest(); +}); + +cachedProperty(KeyPair, function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); +}); + +KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); +}; + +KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); +}; + +KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); +}; + +KeyPair.prototype.getPublic = function getPublic(enc) { + return utils.encode(this.pubBytes(), enc); +}; + +module.exports = KeyPair; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/signature.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/signature.js new file mode 100644 index 0000000..cd5f2b1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/eddsa/signature.js @@ -0,0 +1,66 @@ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var cachedProperty = utils.cachedProperty; +var parseBytes = utils.parseBytes; + +/** +* @param {EDDSA} eddsa - eddsa instance +* @param {Array|Object} sig - +* @param {Array|Point} [sig.R] - R point as Point or bytes +* @param {Array|bn} [sig.S] - S scalar as bn or bytes +* @param {Array} [sig.Rencoded] - R point encoded +* @param {Array} [sig.Sencoded] - S scalar encoded +*/ +function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength) + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; +} + +cachedProperty(Signature, function S() { + return this.eddsa.decodeInt(this.Sencoded()); +}); + +cachedProperty(Signature, function R() { + return this.eddsa.decodePoint(this.Rencoded()); +}); + +cachedProperty(Signature, function Rencoded() { + return this.eddsa.encodePoint(this.R()); +}); + +cachedProperty(Signature, function Sencoded() { + return this.eddsa.encodeInt(this.S()); +}); + +Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); +}; + +Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); +}; + +module.exports = Signature; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/hmac-drbg.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/hmac-drbg.js new file mode 100644 index 0000000..ff63d2a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/hmac-drbg.js @@ -0,0 +1,114 @@ +'use strict'; + +var hash = require('hash.js'); +var elliptic = require('../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + + this.reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + + var entropy = utils.toArray(options.entropy, options.entropyEnc); + var nonce = utils.toArray(options.nonce, options.nonceEnc); + var pers = utils.toArray(options.pers, options.persEnc); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); +} +module.exports = HmacDRBG; + +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this.reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 +}; + +HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); +}; + +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); +}; + +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toBuffer(entropy, entropyEnc); + add = utils.toBuffer(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this.reseed = 1; +}; + +HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this.reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this.reseed++; + return utils.encode(res, enc); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js new file mode 100644 index 0000000..e4c91e5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js @@ -0,0 +1,780 @@ +module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' + ] + ] + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] + } +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/utils.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/utils.js new file mode 100644 index 0000000..d465d93 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/lib/elliptic/utils.js @@ -0,0 +1,173 @@ +'use strict'; + +var utils = exports; +var BN = require('bn.js'); + +utils.assert = function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +}; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + return res; +} +utils.toArray = toArray; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; + +// Represent num in a w-NAF form +function getNAF(num, w) { + var naf = []; + var ws = 1 << (w + 1); + var k = num.clone(); + while (k.cmpn(1) >= 0) { + var z; + if (k.isOdd()) { + var mod = k.andln(ws - 1); + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + naf.push(z); + + // Optimization, shift by word if possible + var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; + for (var i = 1; i < shift; i++) + naf.push(0); + k.iushrn(shift); + } + + return naf; +} +utils.getNAF = getNAF; + +// Represent k1, k2 in a Joint Sparse Form +function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + var m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + var m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; +} +utils.getJSF = getJSF; + +function cachedProperty(obj, computer) { + var name = computer.name; + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; +} +utils.cachedProperty = cachedProperty; + +function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; +} +utils.parseBytes = parseBytes; + +function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); +} +utils.intFromLE = intFromLE; + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/.npmignore new file mode 100644 index 0000000..1ca9571 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/README.md new file mode 100644 index 0000000..f80437d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/README.md @@ -0,0 +1,26 @@ +# Brorand + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/index.js new file mode 100644 index 0000000..436f040 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/index.js @@ -0,0 +1,57 @@ +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +if (typeof window === 'object') { + if (window.crypto && window.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.crypto.getRandomValues(arr); + return arr; + }; + } else if (window.msCrypto && window.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.msCrypto.getRandomValues(arr); + return arr; + }; + } else { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker + try { + var crypto = require('cry' + 'pto'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + // Emulate crypto API using randy + Rand.prototype._rand = function _rand(n) { + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; + }; + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/package.json new file mode 100644 index 0000000..52d4305 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/package.json @@ -0,0 +1,37 @@ +{ + "name": "brorand", + "version": "1.0.5", + "description": "Random number generator for browsers and node.js", + "main": "index.js", + "scripts": { + "test": "mocha --reporter=spec test/**/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/brorand.git" + }, + "keywords": [ + "Random", + "RNG", + "browser", + "crypto" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/brorand/issues" + }, + "homepage": "https://github.com/indutny/brorand", + "devDependencies": { + "mocha": "^2.0.1" + }, + "readme": "# Brorand\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "brorand@1.0.5", + "_shasum": "07b54ca30286abd1718a0e2a830803efdc9bfa04", + "_resolved": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz", + "_from": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/test/api-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/test/api-test.js new file mode 100644 index 0000000..b6c876d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/brorand/test/api-test.js @@ -0,0 +1,8 @@ +var brorand = require('../'); +var assert = require('assert'); + +describe('Brorand', function() { + it('should generate random numbers', function() { + assert.equal(brorand(100).length, 100); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/.npmignore new file mode 100644 index 0000000..1ca9571 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/.travis.yml new file mode 100644 index 0000000..92a990f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "0.10" + - "0.11" +branches: + only: + - master diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/README.md new file mode 100644 index 0000000..63107cb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/README.md @@ -0,0 +1,28 @@ +# hash.js [![Build Status](https://secure.travis-ci.org/indutny/hash.js.png)](http://travis-ci.org/indutny/hash.js) + +Just a bike-shed. + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash.js new file mode 100644 index 0000000..f59b673 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash.js @@ -0,0 +1,15 @@ +var hash = exports; + +hash.utils = require('./hash/utils'); +hash.common = require('./hash/common'); +hash.sha = require('./hash/sha'); +hash.ripemd = require('./hash/ripemd'); +hash.hmac = require('./hash/hmac'); + +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.sha384 = hash.sha.sha384; +hash.sha512 = hash.sha.sha512; +hash.ripemd160 = hash.ripemd.ripemd160; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/common.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/common.js new file mode 100644 index 0000000..a052c55 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/common.js @@ -0,0 +1,91 @@ +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/hmac.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/hmac.js new file mode 100644 index 0000000..3a3da97 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/hmac.js @@ -0,0 +1,48 @@ +var hmac = exports; + +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (var i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (var i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); +}; + +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/ripemd.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/ripemd.js new file mode 100644 index 0000000..cd55bfc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/ripemd.js @@ -0,0 +1,144 @@ +var hash = require('../hash'); +var utils = hash.utils; + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = hash.common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; + +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/sha.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/sha.js new file mode 100644 index 0000000..a7837aa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/sha.js @@ -0,0 +1,564 @@ +var hash = require('../hash'); +var utils = hash.utils; +var assert = utils.assert; + +var rotr32 = utils.rotr32; +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var rotr64_hi = utils.rotr64_hi; +var rotr64_lo = utils.rotr64_lo; +var shr64_hi = utils.shr64_hi; +var shr64_lo = utils.shr64_lo; +var sum64 = utils.sum64; +var sum64_hi = utils.sum64_hi; +var sum64_lo = utils.sum64_lo; +var sum64_4_hi = utils.sum64_4_hi; +var sum64_4_lo = utils.sum64_4_lo; +var sum64_5_hi = utils.sum64_5_hi; +var sum64_5_lo = utils.sum64_5_lo; +var BlockHash = hash.common.BlockHash; + +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; + +var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash); +exports.sha256 = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; + +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +exports.sha224 = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + +function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); +} +utils.inherits(SHA512, BlockHash); +exports.sha512 = SHA512; + +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; + +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi(c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo(c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } +}; + +SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi(c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo(c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + var c0_hi = s0_512_hi(ah, al); + var c0_lo = s0_512_lo(ah, al); + var c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + var c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); +}; + +SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512.call(this); + this.h = [ 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; +} +utils.inherits(SHA384, SHA512); +exports.sha384 = SHA384; + +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; + +SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); +}; + +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash.call(this); + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); +} + +utils.inherits(SHA1, BlockHash); +exports.sha1 = SHA1; + +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; + +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + + for (var i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; + +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} + +function p32(x, y, z) { + return x ^ y ^ z; +} + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} + +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); +} + +function ch64_hi(xh, xl, yh, yl, zh, zl) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_hi(xh, xl, yh, yl, zh, zl) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/utils.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/utils.js new file mode 100644 index 0000000..00ed5fb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/lib/hash/utils.js @@ -0,0 +1,257 @@ +var utils = exports; +var inherits = require('inherits'); + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +utils.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; +} +utils.htonl = htonl; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; +} +utils.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +utils.zero8 = zero8; + +function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; +} +utils.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +utils.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +utils.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +utils.rotl32 = rotl32; + +function sum32(a, b) { + return (a + b) >>> 0; +} +utils.sum32 = sum32; + +function sum32_3(a, b, c) { + return (a + b + c) >>> 0; +} +utils.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; +} +utils.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; +} +utils.sum32_5 = sum32_5; + +function assert(cond, msg) { + if (!cond) + throw new Error(msg || 'Assertion failed'); +} +utils.assert = assert; + +utils.inherits = inherits; + +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +exports.sum64 = sum64; + +function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +}; +exports.sum64_hi = sum64_hi; + +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +}; +exports.sum64_lo = sum64_lo; + +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +}; +exports.sum64_4_hi = sum64_4_hi; + +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +}; +exports.sum64_4_lo = sum64_4_lo; + +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +}; +exports.sum64_5_hi = sum64_5_hi; + +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; +}; +exports.sum64_5_lo = sum64_5_lo; + +function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; +}; +exports.rotr64_hi = rotr64_hi; + +function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +}; +exports.rotr64_lo = rotr64_lo; + +function shr64_hi(ah, al, num) { + return ah >>> num; +}; +exports.shr64_hi = shr64_hi; + +function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +}; +exports.shr64_lo = shr64_lo; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/package.json new file mode 100644 index 0000000..6d79251 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/package.json @@ -0,0 +1,40 @@ +{ + "name": "hash.js", + "version": "1.0.3", + "description": "Various hash functions that could be run by both browser and node", + "main": "lib/hash.js", + "scripts": { + "test": "mocha --reporter=spec test/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/hash.js.git" + }, + "keywords": [ + "hash", + "sha256", + "sha224", + "hmac" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/hash.js/issues" + }, + "homepage": "https://github.com/indutny/hash.js", + "dependencies": { + "inherits": "^2.0.1" + }, + "devDependencies": { + "mocha": "^1.18.2" + }, + "readme": "# hash.js [![Build Status](https://secure.travis-ci.org/indutny/hash.js.png)](http://travis-ci.org/indutny/hash.js)\n\nJust a bike-shed.\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "hash.js@1.0.3", + "_shasum": "1332ff00156c0a0ffdd8236013d07b77a0451573", + "_resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.0.3.tgz", + "_from": "https://registry.npmjs.org/hash.js/-/hash.js-1.0.3.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/test/hash-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/test/hash-test.js new file mode 100644 index 0000000..97347a2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/test/hash-test.js @@ -0,0 +1,119 @@ +var assert = require('assert'); +var hash = require('../'); + +describe('Hash', function() { + function test(fn, cases) { + for (var i = 0; i < cases.length; i++) { + var msg = cases[i][0]; + var res = cases[i][1]; + var enc = cases[i][2]; + + var dgst = fn().update(msg, enc).digest('hex'); + assert.equal(dgst, res); + + // Split message + var dgst = fn().update(msg.slice(0, 2), enc) + .update(msg.slice(2), enc) + .digest('hex'); + assert.equal(dgst, res); + } + } + + it('should support sha256', function() { + assert.equal(hash.sha256.blockSize, 512); + assert.equal(hash.sha256.outSize, 256); + + test(hash.sha256, [ + [ 'abc', + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad' ], + [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1' ], + [ 'deadbeef', + '5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953', + 'hex' ], + ]); + }); + + it('should support sha224', function() { + assert.equal(hash.sha224.blockSize, 512); + assert.equal(hash.sha224.outSize, 224); + + test(hash.sha224, [ + [ 'abc', + '23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7' ], + [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + '75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525' ], + [ 'deadbeef', + '55b9eee5f60cc362ddc07676f620372611e22272f60fdbec94f243f8', + 'hex' ], + ]); + }); + + it('should support ripemd160', function() { + assert.equal(hash.ripemd160.blockSize, 512); + assert.equal(hash.ripemd160.outSize, 160); + + test(hash.ripemd160, [ + [ '', '9c1185a5c5e9fc54612808977ee8f548b2258d31'], + [ 'abc', + '8eb208f7e05d987a9b044a8e98c6b087f15a0bfc' ], + [ 'message digest', + '5d0689ef49d2fae572b881b123a85ffa21595f36' ], + [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + '12a053384a9c0c88e405a06c27dcf49ada62eb2b' ], + [ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', + 'b0e20b6e3116640286ed3a87a5713079b21f5189' ], + ]); + }); + + it('should support sha1', function() { + assert.equal(hash.sha1.blockSize, 512); + assert.equal(hash.sha1.outSize, 160); + + test(hash.sha1, [ + [ '', + 'da39a3ee5e6b4b0d3255bfef95601890afd80709' ], + [ 'abc', + 'a9993e364706816aba3e25717850c26c9cd0d89d' ], + [ 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + '84983e441c3bd26ebaae4aa1f95129e5e54670f1' ], + [ 'deadbeef', + 'd78f8bb992a56a597f6c7a1fb918bb78271367eb', + 'hex' ], + ]); + }); + + it('should support sha512', function() { + assert.equal(hash.sha512.blockSize, 1024); + assert.equal(hash.sha512.outSize, 512); + + test(hash.sha512, [ + [ 'abc', + 'ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a' + + '2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f' + ], + [ 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn' + + 'hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', + '8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018' + + '501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909' + ] + ]); + }); + + it('should support sha384', function() { + assert.equal(hash.sha384.blockSize, 1024); + assert.equal(hash.sha384.outSize, 384); + + test(hash.sha384, [ + [ 'abc', + 'cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed' + + '8086072ba1e7cc2358baeca134c825a7' + ], + [ 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn' + + 'hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu', + '09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712' + + 'fcc7c71a557e2db966c3e9fa91746039' + ] + ]); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/test/hmac-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/test/hmac-test.js new file mode 100644 index 0000000..0a9647e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/node_modules/elliptic/node_modules/hash.js/test/hmac-test.js @@ -0,0 +1,59 @@ +var assert = require('assert'); +var hash = require('../'); +var utils = hash.utils; + +describe('Hmac', function() { + describe('mixed test vector', function() { + test({ + name: 'nist 1', + key: '00010203 04050607 08090A0B 0C0D0E0F' + + '10111213 14151617 18191A1B 1C1D1E1F 20212223 24252627' + + '28292A2B 2C2D2E2F 30313233 34353637 38393A3B 3C3D3E3F', + msg: 'Sample message for keylen=blocklen', + res: '8bb9a1db9806f20df7f77b82138c7914d174d59e13dc4d0169c9057b133e1d62' + }); + test({ + name: 'nist 2', + key: '00010203 04050607' + + '08090A0B 0C0D0E0F 10111213 14151617 18191A1B 1C1D1E1F', + msg: 'Sample message for keylen= 0.11 this module is just a shortcut to crypto.createECDH. In node <= 0.11 or the browser this is a pure JavaScript implimentation, more specifically a wrapper around [elliptic](https://github.com/indutny/elliptic), to give it the same API as node. `secp256k1`, `secp224r1` (aka p224), `prime256v1` (aka p256, secp256r1), `prime192v1` (aka p192, secp192r1), `secp384r1` (aka p384), `secp521r1` (aka p521) curves all work in both this library and node (though only the highlighted name will work in node).\n", + "readmeFilename": "readme.md", + "_id": "create-ecdh@4.0.0", + "_shasum": "888c723596cdf7612f6498233eebd7a35301737d", + "_resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.0.tgz", + "_from": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/readme.md new file mode 100644 index 0000000..7e5ce47 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-ecdh/readme.md @@ -0,0 +1,4 @@ +createECDH [![Build Status](https://travis-ci.org/crypto-browserify/createECDH.svg)](https://travis-ci.org/crypto-browserify/createECDH) +==== + +In io.js or node >= 0.11 this module is just a shortcut to crypto.createECDH. In node <= 0.11 or the browser this is a pure JavaScript implimentation, more specifically a wrapper around [elliptic](https://github.com/indutny/elliptic), to give it the same API as node. `secp256k1`, `secp224r1` (aka p224), `prime256v1` (aka p256, secp256r1), `prime192v1` (aka p192, secp192r1), `secp384r1` (aka p384), `secp521r1` (aka p521) curves all work in both this library and node (though only the highlighted name will work in node). diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/.travis.yml new file mode 100644 index 0000000..1416d60 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.10" + - "0.11" \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/browser.js new file mode 100644 index 0000000..e9add1e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/browser.js @@ -0,0 +1,52 @@ +'use strict'; +var inherits = require('inherits') +var md5 = require('./md5') +var rmd160 = require('ripemd160') +var sha = require('sha.js') + +var Base = require('cipher-base') + +function HashNoConstructor(hash) { + Base.call(this, 'digest') + + this._hash = hash + this.buffers = [] +} + +inherits(HashNoConstructor, Base) + +HashNoConstructor.prototype._update = function (data) { + this.buffers.push(data) +} + +HashNoConstructor.prototype._final = function () { + var buf = Buffer.concat(this.buffers) + var r = this._hash(buf) + this.buffers = null + + return r +} + +function Hash(hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if ('md5' === alg) return new HashNoConstructor(md5) + if ('rmd160' === alg || 'ripemd160' === alg) return new HashNoConstructor(rmd160) + + return new Hash(sha(alg)) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/helpers.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/helpers.js new file mode 100644 index 0000000..33b463d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/helpers.js @@ -0,0 +1,34 @@ +'use strict'; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; + +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } + + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; +} + +function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); + } + return buf; +} + +function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); +} +exports.hash = hash; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/index.js new file mode 100644 index 0000000..9d2d26f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').createHash; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/md5.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/md5.js new file mode 100644 index 0000000..d2135f4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/md5.js @@ -0,0 +1,156 @@ +'use strict'; +/* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +var helpers = require('./helpers'); + +/* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ +function core_md5(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << ((len) % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); + d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); + d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); + d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i+10], 17, -42063); + b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); + d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); + d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); + c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); + d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); + c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); + d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); + c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); + d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); + c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); + d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); + d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); + d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); + d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); + d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); + d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); + d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); + d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + +} + +/* + * These functions implement the four basic operations the algorithm uses. + */ +function md5_cmn(q, a, b, x, s, t) +{ + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); +} +function md5_ff(a, b, c, d, x, s, t) +{ + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5_gg(a, b, c, d, x, s, t) +{ + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5_hh(a, b, c, d, x, s, t) +{ + return md5_cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5_ii(a, b, c, d, x, s, t) +{ + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function bit_rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); +}; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/.bin/sha.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/.bin/sha.js new file mode 100644 index 0000000..5b09194 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/.bin/sha.js @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../sha.js/bin.js" "$@" + ret=$? +else + node "$basedir/../sha.js/bin.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/.bin/sha.js.cmd b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/.bin/sha.js.cmd new file mode 100644 index 0000000..e089a20 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/.bin/sha.js.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\sha.js\bin.js" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\sha.js\bin.js" %* +) \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/.eslintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/.eslintrc new file mode 100644 index 0000000..a755cdb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": ["standard"] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/index.js new file mode 100644 index 0000000..34fcae2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/index.js @@ -0,0 +1,90 @@ +var Transform = require('stream').Transform +var inherits = require('inherits') +var StringDecoder = require('string_decoder').StringDecoder +module.exports = CipherBase +inherits(CipherBase, Transform) +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + this._decoder = null + this._encoding = null +} +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = new Buffer(data, inputEnc) + } + var outData = this._update(data) + if (this.hashMode) { + return this + } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} + +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this._final()) + } catch (e) { + err = e + } finally { + done(err) + } +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this._final() || new Buffer('') + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, final) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + if (this._encoding !== enc) { + throw new Error('can\'t switch encodings') + } + var out = this._decoder.write(value) + if (final) { + out += this._decoder.end() + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/package.json new file mode 100644 index 0000000..1e71e16 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/package.json @@ -0,0 +1,39 @@ +{ + "name": "cipher-base", + "version": "1.0.2", + "description": "abstract base class for crypto-streams", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/cipher-base.git" + }, + "keywords": [ + "cipher", + "stream" + ], + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/cipher-base/issues" + }, + "homepage": "https://github.com/crypto-browserify/cipher-base#readme", + "dependencies": { + "inherits": "^2.0.1" + }, + "devDependencies": { + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "cipher-base\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base)\n\nAbstract base class to inherit from if you want to create streams implementing\nthe same api as node crypto streams.\n\nRequires you to implement 2 methods `_final` and `_update`. `_update` takes a\nbuffer and should return a buffer, `_final` takes no arguments and should return\na buffer.\n\n\nThe constructor takes one argument and that is a string which if present switches\nit into hash mode, i.e. the object you get from crypto.createHash or\ncrypto.createSign, this switches the name of the final method to be the string\nyou passed instead of `final` and returns `this` from update.\n", + "readmeFilename": "readme.md", + "_id": "cipher-base@1.0.2", + "_shasum": "54ac1d1ebdf6a1bcd3559e6f369d72697f2cab8f", + "_resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz", + "_from": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/readme.md new file mode 100644 index 0000000..db9a781 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/readme.md @@ -0,0 +1,17 @@ +cipher-base +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) + +Abstract base class to inherit from if you want to create streams implementing +the same api as node crypto streams. + +Requires you to implement 2 methods `_final` and `_update`. `_update` takes a +buffer and should return a buffer, `_final` takes no arguments and should return +a buffer. + + +The constructor takes one argument and that is a string which if present switches +it into hash mode, i.e. the object you get from crypto.createHash or +crypto.createSign, this switches the name of the final method to be the string +you passed instead of `final` and returns `this` from update. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/test.js new file mode 100644 index 0000000..57d144a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/cipher-base/test.js @@ -0,0 +1,108 @@ +var test = require('tape') +var CipherBase = require('./') +var inherits = require('inherits') + +test('basic version', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + return input + } + Cipher.prototype._final = function () { + // noop + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8', 'base64') + cipher.final('base64') + var string = (new Buffer(update, 'base64')).toString() + t.equals(utf8, string) + t.end() +}) +test('hash mode', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8').finalName('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('hash mode as stream', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + cipher.on('error', function (e) { + t.notOk(e) + }) + var utf8 = 'abc123abcd' + cipher.end(utf8, 'utf8') + var update = cipher.read().toString('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('encodings', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + return input + } + Cipher.prototype._final = function () { + // noop + } + t.test('mix and match encoding', function (t) { + t.plan(2) + + var cipher = new Cipher() + cipher.update('foo', 'utf8', 'utf8') + t.throws(function () { + cipher.update('foo', 'utf8', 'base64') + }) + cipher = new Cipher() + cipher.update('foo', 'utf8', 'base64') + t.doesNotThrow(function () { + cipher.update('foo', 'utf8') + cipher.final('base64') + }) + }) + t.test('handle long uft8 plaintexts', function (t) { + t.plan(1) + var txt = 'ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん' + + var cipher = new Cipher() + var decipher = new Cipher() + var enc = decipher.update(cipher.update(txt, 'utf8', 'base64'), 'base64', 'utf8') + enc += decipher.update(cipher.final('base64'), 'base64', 'utf8') + enc += decipher.final('utf8') + + t.equals(txt, enc) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/.npmignore new file mode 100644 index 0000000..a091fb1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/.npmignore @@ -0,0 +1,5 @@ +.gitignore +test/ +.DS_Store +.min-wd +Makefile diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/CHANGELOG.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/CHANGELOG.md new file mode 100644 index 0000000..9e1e6df --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/CHANGELOG.md @@ -0,0 +1,36 @@ +1.0.1 / 2015-05-05 +------------------ +- standard formatting + +1.0.0 / 2015-01-14 +------------------ +- updated dev deps +- added more test fixtures +- updated readme with usage, testing, etc +- moved from https://github.com/cryptocoinjs/ripemd160 to https://github.com/crypto-browserify/ripemd160 + +0.2.1 / 2014-12-31 +------------------ +- made license clear in `package.json` +- deleted `Makefile`, moved targets to `package.json` +- removed `terst` for `assert` + +0.2.0 / 2014-03-09 +------------------ +* removed bower.json and component.json +* changed 4 spacing to 2 +* returns `Buffer` type now, input must be Array, Uint8Array, Buffer, or string +* remove deps: `convert-hex` and `convert-string` + +0.1.0 / 2013-11-20 +------------------ +* changed package name +* removed AMD support + +0.0.2 / 2013-11-06 +------------------ +* fixed component.json file + +0.0.1 / 2013-11-03 +------------------ +* initial release diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/README.md new file mode 100644 index 0000000..c09f50b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/README.md @@ -0,0 +1,100 @@ +ripemd160 +========= + +JavaScript component to compute the RIPEMD-160 hash of strings or bytes. This hash is commonly used in crypto currencies +like Bitcoin. + +Usage +----- + +### Install + + npm install --save ripemd160 + + +### ripemd160(input) + +`input` should be either a `string`, `Buffer`, or an `Array`. It returns a `Buffer`. + +**example 1**: + +```js +var ripemd16 = require('ripemd160') + +var data = 'hello' +var result = ripemd160(data) +console.log(result.toString('hex')) +// => 108f07b8382412612c048d07d13f814118445acd +``` + +**example 2**: + +```js +var ripemd16 = require('ripemd160') + +var data = new Buffer('hello', 'utf8') +var result = ripemd160(data) +console.log(result.toString('hex')) +// => 108f07b8382412612c048d07d13f814118445acd +``` + + +#### Converting Buffers + +If you're not familiar with the Node.js ecosystem, type `Buffer` is a common way that a developer can pass around +binary data. `Buffer` also exists in the [Browserify](http://browserify.org/) environment. Converting to and from Buffers is very easy. + +##### To buffer + +```js +// from string +var buf = new Buffer('some string', 'utf8') + +// from hex string +var buf = new Buffer('3f5a4c22', 'hex') + +// from array +var buf = new Buffer([1, 2, 3, 4]) +``` + +#### From buffer + +```js +// to string +var str = buf.toString('utf8') + +// to hex string +var hex = buf.toString('hex') + +// to array +var arr = [].slice.call(buf) +``` + + +Testing +------- + +### Install dev deps: + + npm install --development + +### Test in Node.js: + + npm run test + +### Test in a Browser: + +Testing in the browser uses the excellent [Mochify](https://github.com/mantoni/mochify.js). Mochify can use either PhantomJS +or an actual browser. You must have Selenium installed if you want to use an actual browser. The easiest way is to +`npm install -g start-selenium` and then run `start-selenium`. + +Then run: + + npm run browser-test + + + +License +------- + +Licensed: BSD3-Clause diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/lib/ripemd160.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/lib/ripemd160.js new file mode 100644 index 0000000..a96ac5b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/lib/ripemd160.js @@ -0,0 +1,210 @@ +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/** @preserve +(c) 2012 by Cédric Mesnil. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// constants table +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E] +var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000] + +function bytesToWords (bytes) { + var words = [] + for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { + words[b >>> 5] |= bytes[i] << (24 - b % 32) + } + return words +} + +function wordsToBytes (words) { + var bytes = [] + for (var b = 0; b < words.length * 32; b += 8) { + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) + } + return bytes +} + +function processBlock (H, M, offset) { + // swap endian + for (var i = 0; i < 16; i++) { + var offset_i = offset + i + var M_offset_i = M[offset_i] + + // Swap + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ) + } + + // Working variables + var al, bl, cl, dl, el + var ar, br, cr, dr, er + + ar = al = H[0] + br = bl = H[1] + cr = cl = H[2] + dr = dl = H[3] + er = el = H[4] + + // computation + var t + for (i = 0; i < 80; i += 1) { + t = (al + M[offset + zl[i]]) | 0 + if (i < 16) { + t += f1(bl, cl, dl) + hl[0] + } else if (i < 32) { + t += f2(bl, cl, dl) + hl[1] + } else if (i < 48) { + t += f3(bl, cl, dl) + hl[2] + } else if (i < 64) { + t += f4(bl, cl, dl) + hl[3] + } else {// if (i<80) { + t += f5(bl, cl, dl) + hl[4] + } + t = t | 0 + t = rotl(t, sl[i]) + t = (t + el) | 0 + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = t + + t = (ar + M[offset + zr[i]]) | 0 + if (i < 16) { + t += f5(br, cr, dr) + hr[0] + } else if (i < 32) { + t += f4(br, cr, dr) + hr[1] + } else if (i < 48) { + t += f3(br, cr, dr) + hr[2] + } else if (i < 64) { + t += f2(br, cr, dr) + hr[3] + } else {// if (i<80) { + t += f1(br, cr, dr) + hr[4] + } + + t = t | 0 + t = rotl(t, sr[i]) + t = (t + er) | 0 + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = t + } + + // intermediate hash value + t = (H[1] + cl + dr) | 0 + H[1] = (H[2] + dl + er) | 0 + H[2] = (H[3] + el + ar) | 0 + H[3] = (H[4] + al + br) | 0 + H[4] = (H[0] + bl + cr) | 0 + H[0] = t +} + +function f1 (x, y, z) { + return ((x) ^ (y) ^ (z)) +} + +function f2 (x, y, z) { + return (((x) & (y)) | ((~x) & (z))) +} + +function f3 (x, y, z) { + return (((x) | (~(y))) ^ (z)) +} + +function f4 (x, y, z) { + return (((x) & (z)) | ((y) & (~(z)))) +} + +function f5 (x, y, z) { + return ((x) ^ ((y) | (~(z)))) +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function ripemd160 (message) { + var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] + + if (typeof message === 'string') { + message = new Buffer(message, 'utf8') + } + + var m = bytesToWords(message) + + var nBitsLeft = message.length * 8 + var nBitsTotal = message.length * 8 + + // Add padding + m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) + m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | + (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) + ) + + for (var i = 0; i < m.length; i += 16) { + processBlock(H, m, i) + } + + // swap endian + for (i = 0; i < 5; i++) { + // shortcut + var H_i = H[i] + + // Swap + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00) + } + + var digestbytes = wordsToBytes(H) + return new Buffer(digestbytes) +} + +module.exports = ripemd160 diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/package.json new file mode 100644 index 0000000..a8eacb5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/ripemd160/package.json @@ -0,0 +1,40 @@ +{ + "name": "ripemd160", + "version": "1.0.1", + "description": "Compute ripemd160 of bytes or strings.", + "keywords": [ + "string", + "strings", + "ripemd160", + "ripe160", + "bitcoin", + "bytes", + "cryptography" + ], + "license": "BSD-3-Clause", + "devDependencies": { + "mocha": "^2.1.0", + "mochify": "^2.1.1", + "standard": "3.x" + }, + "repository": { + "url": "git+https://github.com/crypto-browserify/ripemd160.git", + "type": "git" + }, + "main": "./lib/ripemd160.js", + "dependencies": {}, + "scripts": { + "test": "mocha test", + "browser-test": "mochify --wd -R spec" + }, + "readme": "ripemd160\n=========\n\nJavaScript component to compute the RIPEMD-160 hash of strings or bytes. This hash is commonly used in crypto currencies\nlike Bitcoin.\n\nUsage\n-----\n\n### Install\n\n npm install --save ripemd160\n\n\n### ripemd160(input)\n\n`input` should be either a `string`, `Buffer`, or an `Array`. It returns a `Buffer`. \n\n**example 1**:\n\n```js\nvar ripemd16 = require('ripemd160')\n\nvar data = 'hello'\nvar result = ripemd160(data)\nconsole.log(result.toString('hex'))\n// => 108f07b8382412612c048d07d13f814118445acd\n```\n\n**example 2**:\n\n```js\nvar ripemd16 = require('ripemd160')\n\nvar data = new Buffer('hello', 'utf8')\nvar result = ripemd160(data)\nconsole.log(result.toString('hex'))\n// => 108f07b8382412612c048d07d13f814118445acd\n```\n\n\n#### Converting Buffers\n\nIf you're not familiar with the Node.js ecosystem, type `Buffer` is a common way that a developer can pass around\nbinary data. `Buffer` also exists in the [Browserify](http://browserify.org/) environment. Converting to and from Buffers is very easy.\n\n##### To buffer\n\n```js\n// from string\nvar buf = new Buffer('some string', 'utf8')\n\n// from hex string\nvar buf = new Buffer('3f5a4c22', 'hex')\n\n// from array\nvar buf = new Buffer([1, 2, 3, 4])\n```\n\n#### From buffer\n\n```js\n// to string\nvar str = buf.toString('utf8')\n\n// to hex string\nvar hex = buf.toString('hex')\n\n// to array\nvar arr = [].slice.call(buf)\n```\n\n\nTesting\n-------\n\n### Install dev deps:\n\n npm install --development\n\n### Test in Node.js:\n\n npm run test\n\n### Test in a Browser:\n\nTesting in the browser uses the excellent [Mochify](https://github.com/mantoni/mochify.js). Mochify can use either PhantomJS \nor an actual browser. You must have Selenium installed if you want to use an actual browser. The easiest way is to \n`npm install -g start-selenium` and then run `start-selenium`.\n\nThen run:\n\n npm run browser-test\n\n\n\nLicense\n-------\n\nLicensed: BSD3-Clause\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/crypto-browserify/ripemd160/issues" + }, + "homepage": "https://github.com/crypto-browserify/ripemd160#readme", + "_id": "ripemd160@1.0.1", + "_shasum": "93a4bbd4942bc574b69a8fa57c71de10ecca7d6e", + "_resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-1.0.1.tgz", + "_from": "https://registry.npmjs.org/ripemd160/-/ripemd160-1.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/.travis.yml new file mode 100644 index 0000000..1c0bada --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/.travis.yml @@ -0,0 +1,18 @@ +sudo: false +os: + - linux +language: node_js +node_js: + - "0.10" + - "0.11" + - "0.12" + - "4" + - "5" +env: + matrix: + - TEST_SUITE=unit +matrix: + include: + - node_js: "4" + env: TEST_SUITE=lint +script: npm run $TEST_SUITE diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/LICENSE new file mode 100644 index 0000000..92ba9d3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2013-2014 sha.js contributors + +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software and +associated documentation files (the "Software"), to +deal in the Software without restriction, including +without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom +the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/README.md new file mode 100644 index 0000000..fbce231 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/README.md @@ -0,0 +1,54 @@ +# sha.js + +Streamable SHA hashes in pure javascript. + +[![build status](https://secure.travis-ci.org/crypto-browserify/sha.js.png)](http://travis-ci.org/crypto-browserify/sha.js) +[![NPM](http://img.shields.io/npm/v/sha.js.svg)](https://www.npmjs.org/package/sha.js) + + +## Example + +``` js +var createHash = require('sha.js') + +var sha256 = createHash('sha256') +var sha512 = createHash('sha512') + +var h = sha256.update('abc', 'utf8').digest('hex') +console.log(h) //ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad + +//LEGACY, do not use in new systems: +var sha0 = createHash('sha') +var sha1 = createHash('sha1') + + +``` + +## supported hashes + +sha.js currently implements: + + +* sha256 +* sha512 +* sha1 (legacy, no not use in new systems) +* sha (legacy, no not use in new systems) + +## Note + +Note, this doesn't actually implement a stream, but wrapping this in a stream is trivial. +but is does update incrementally, so you can hash things larger than ram, and also, since it reuses +the typedarrays, it uses a constant amount of memory (except when using base64 or utf8 encoding, +see code comments) + + +## Acknowledgements + +This work is derived from Paul Johnston's ["A JavaScript implementation of the Secure Hash Algorithm"] +(http://pajhome.org.uk/crypt/md5/sha1.html) + + + +## License + +MIT diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/bin.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/bin.js new file mode 100644 index 0000000..0a4e95b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/bin.js @@ -0,0 +1,43 @@ +#! /usr/bin/env node + +var createHash = require('./browserify') +var argv = process.argv.slice(2) + +function pipe (algorithm, s) { + var start = Date.now() + var hash = createHash(algorithm || 'sha1') + + s.on('data', function (data) { + hash.update(data) + }) + + s.on('end', function () { + if (process.env.DEBUG) { + return console.log(hash.digest('hex'), Date.now() - start) + } + + console.log(hash.digest('hex')) + }) +} + +function usage () { + console.error('sha.js [algorithm=sha1] [filename] # hash filename with algorithm') + console.error('input | sha.js [algorithm=sha1] # hash stdin with algorithm') + console.error('sha.js --help # display this message') +} + +if (!process.stdin.isTTY) { + pipe(argv[0], process.stdin) + +} else if (argv.length) { + if (/--help|-h/.test(argv[0])) { + usage() + + } else { + var filename = argv.pop() + var algorithm = argv.pop() + pipe(algorithm, require('fs').createReadStream(filename)) + } +} else { + usage() +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/hash.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/hash.js new file mode 100644 index 0000000..09579d2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/hash.js @@ -0,0 +1,69 @@ +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = new Buffer(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 + this._s = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = new Buffer(data, enc) + } + + var l = this._len += data.length + var s = this._s || 0 + var f = 0 + var buffer = this._block + + while (s < l) { + var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize)) + var ch = (t - f) + + for (var i = 0; i < ch; i++) { + buffer[(s % this._blockSize) + i] = data[i + f] + } + + s += ch + f += ch + + if ((s % this._blockSize) === 0) { + this._update(buffer) + } + } + this._s = s + + return this +} + +Hash.prototype.digest = function (enc) { + // Suppose the length of the message M, in bits, is l + var l = this._len * 8 + + // Append the bit 1 to the end of the message + this._block[this._len % this._blockSize] = 0x80 + + // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize + this._block.fill(0, this._len % this._blockSize + 1) + + if (l % (this._blockSize * 8) >= this._finalSize * 8) { + this._update(this._block) + this._block.fill(0) + } + + // to this append the block which is equal to the number l written in binary + // TODO: handle case where l is > Math.pow(2, 29) + this._block.writeInt32BE(l, this._blockSize - 4) + + var hash = this._update(this._block) || this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/hexpp.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/hexpp.js new file mode 100644 index 0000000..4f1e921 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/hexpp.js @@ -0,0 +1,26 @@ +function toHex (buf, group, wrap, LE) { + buf = buf.buffer || buf + var s = '' + var l = buf.byteLength || buf.length + for (var i = 0; i < l ; i++) { + var byteParam = (i & 0xfffffffc) | (!LE ? i % 4 : 3 - i % 4) + s += ((buf[byteParam] >> 4).toString(16)) + + ((buf[byteParam] & 0xf).toString(16)) + + (group - 1 === i % group ? ' ' : '') + + (wrap - 1 === i % wrap ? '\n' : '') + } + return s +} + +var hexpp = module.exports = function hexpp (buffer, opts) { + opts = opts || {} + opts.groups = opts.groups || 4 + opts.wrap = opts.wrap || 16 + return toHex(buffer, opts.groups, opts.wrap, opts.bigendian, opts.ints) +} + +hexpp.defaults = function (opts) { + return function (b) { + return hexpp(b, opts) + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/index.js new file mode 100644 index 0000000..87cdf49 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/index.js @@ -0,0 +1,15 @@ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = require('./sha') +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/package.json new file mode 100644 index 0000000..120cbbe --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/package.json @@ -0,0 +1,44 @@ +{ + "name": "sha.js", + "description": "Streamable SHA hashes in pure javascript", + "version": "2.4.5", + "homepage": "https://github.com/crypto-browserify/sha.js", + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/sha.js.git" + }, + "dependencies": { + "inherits": "^2.0.1" + }, + "devDependencies": { + "buffer": "~2.3.2", + "hash-test-vectors": "^1.3.1", + "standard": "^4.0.0", + "tape": "~2.3.2", + "typedarray": "0.0.6" + }, + "bin": { + "sha.js": "./bin.js" + }, + "scripts": { + "prepublish": "npm ls && npm run unit", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "set -e; for t in test/*.js; do node $t; done;" + }, + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "license": "MIT", + "readme": "# sha.js\n\nStreamable SHA hashes in pure javascript.\n\n[![build status](https://secure.travis-ci.org/crypto-browserify/sha.js.png)](http://travis-ci.org/crypto-browserify/sha.js)\n[![NPM](http://img.shields.io/npm/v/sha.js.svg)](https://www.npmjs.org/package/sha.js)\n\n\n## Example\n\n``` js\nvar createHash = require('sha.js')\n\nvar sha256 = createHash('sha256')\nvar sha512 = createHash('sha512')\n\nvar h = sha256.update('abc', 'utf8').digest('hex')\nconsole.log(h) //ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\n\n//LEGACY, do not use in new systems:\nvar sha0 = createHash('sha')\nvar sha1 = createHash('sha1')\n\n\n```\n\n## supported hashes\n\nsha.js currently implements:\n\n\n* sha256\n* sha512\n* sha1 (legacy, no not use in new systems)\n* sha (legacy, no not use in new systems)\n\n## Note\n\nNote, this doesn't actually implement a stream, but wrapping this in a stream is trivial.\nbut is does update incrementally, so you can hash things larger than ram, and also, since it reuses\nthe typedarrays, it uses a constant amount of memory (except when using base64 or utf8 encoding,\nsee code comments)\n\n\n## Acknowledgements\n\nThis work is derived from Paul Johnston's [\"A JavaScript implementation of the Secure Hash Algorithm\"]\n(http://pajhome.org.uk/crypt/md5/sha1.html)\n\n\n\n## License\n\nMIT\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/crypto-browserify/sha.js/issues" + }, + "_id": "sha.js@2.4.5", + "_shasum": "27d171efcc82a118b99639ff581660242b506e7c", + "_resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.5.tgz", + "_from": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.5.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha.js new file mode 100644 index 0000000..7cde1b0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha.js @@ -0,0 +1,93 @@ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = new Buffer(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha1.js new file mode 100644 index 0000000..97f6b14 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha1.js @@ -0,0 +1,98 @@ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha1.prototype._hash = function () { + var H = new Buffer(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha1 diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha224.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha224.js new file mode 100644 index 0000000..31899ef --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha224.js @@ -0,0 +1,52 @@ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Sha256 = require('./sha256') +var Hash = require('./hash') + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this +} + +Sha224.prototype._hash = function () { + var H = new Buffer(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha256.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha256.js new file mode 100644 index 0000000..69b60fe --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha256.js @@ -0,0 +1,134 @@ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = new Buffer(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha384.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha384.js new file mode 100644 index 0000000..dc48312 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha384.js @@ -0,0 +1,56 @@ +var inherits = require('inherits') +var SHA512 = require('./sha512') +var Hash = require('./hash') + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = new Buffer(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha512.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha512.js new file mode 100644 index 0000000..204a7b8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/sha512.js @@ -0,0 +1,259 @@ +var inherits = require('inherits') +var Hash = require('./hash') + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = new Buffer(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/hash.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/hash.js new file mode 100644 index 0000000..2f376b4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/hash.js @@ -0,0 +1,86 @@ +var hexpp = require('../hexpp').defaults({ bigendian: false }) +var tape = require('tape') +var Hash = require('../hash') + +var hex = '0A1B2C3D4E5F6G7H' + +function equal (t, a, b) { + t.equal(a.length, b.length) + + for (var i = 0; i < a.length; i++) { + t.equal(a[i], b[i]) + } +} + +var hexBuf = new Buffer([48, 65, 49, 66, 50, 67, 51, 68, 52, 69, 53, 70, 54, 71, 55, 72]) +var count16 = { + strings: ['0A1B2C3D4E5F6G7H'], + buffers: [ + hexBuf, + new Buffer([ 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128]) + ] +} + +var empty = { + strings: [''], + buffers: [ + new Buffer([ 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]) + ] +} + +var multi = { + strings: ['abcd', 'efhijk', 'lmnopq'], + buffers: [ + new Buffer('abcdefhijklmnopq', 'ascii'), + new Buffer([128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128]) + ] + } + +var long = { + strings: [hex + hex], + buffers: [ + hexBuf, + hexBuf, + new Buffer([128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]) + ] +} + +function makeTest (name, data) { + tape(name, function (t) { + + var h = new Hash(16, 8) + var hash = new Buffer(20) + var n = 2 + var expected = data.buffers.slice() + // t.plan(expected.length + 1) + + h._update = function (block) { + var e = expected.shift() + + console.log('---block---') + console.log(hexpp(block), block.length) + console.log('---e---') + console.log(hexpp(e), block.length) + console.log(block) + equal(t, block, e) + + if (n < 0) { + throw new Error('expecting only 2 calls to _update') + } + + return hash + } + + data.strings.forEach(function (string) { + h.update(string, 'ascii') + }) + + equal(t, h.digest(), hash) + t.end() + }) +} + +makeTest('Hash#update 1 in 1', count16) +makeTest('empty Hash#update', empty) +makeTest('Hash#update 1 in 3', multi) +makeTest('Hash#update 2 in 1', long) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/test.js new file mode 100644 index 0000000..0a46e44 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/test.js @@ -0,0 +1,85 @@ +var crypto = require('crypto') +var tape = require('tape') +var Sha1 = require('../').sha1 + +var inputs = [ + ['', 'ascii'], + ['abc', 'ascii'], + ['123', 'ascii'], + ['123456789abcdef123456789abcdef123456789abcdef123456789abcdef', 'ascii'], + ['123456789abcdef123456789abcdef123456789abcdef123456789abc', 'ascii'], + ['123456789abcdef123456789abcdef123456789abcdef123456789ab', 'ascii'], + ['0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde', 'ascii'], + ['0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', 'ascii'], + ['foobarbaz', 'ascii'] +] + +tape("hash is the same as node's crypto", function (t) { + inputs.forEach(function (v) { + var a = new Sha1().update(v[0], v[1]).digest('hex') + var e = crypto.createHash('sha1').update(v[0], v[1]).digest('hex') + console.log(a, '==', e) + t.equal(a, e) + }) + + t.end() +}) + +tape('call update multiple times', function (t) { + inputs.forEach(function (v) { + var hash = new Sha1() + var _hash = crypto.createHash('sha1') + + for (var i = 0; i < v[0].length; i = (i + 1) * 2) { + var s = v[0].substring(i, (i + 1) * 2) + hash.update(s, v[1]) + _hash.update(s, v[1]) + } + + var a = hash.digest('hex') + var e = _hash.digest('hex') + console.log(a, '==', e) + t.equal(a, e) + }) + t.end() +}) + +tape('call update twice', function (t) { + var _hash = crypto.createHash('sha1') + var hash = new Sha1() + + _hash.update('foo', 'ascii') + hash.update('foo', 'ascii') + + _hash.update('bar', 'ascii') + hash.update('bar', 'ascii') + + _hash.update('baz', 'ascii') + hash.update('baz', 'ascii') + + var a = hash.digest('hex') + var e = _hash.digest('hex') + + t.equal(a, e) + t.end() +}) + +tape('hex encoding', function (t) { + inputs.forEach(function (v) { + var hash = new Sha1() + var _hash = crypto.createHash('sha1') + + for (var i = 0; i < v[0].length; i = (i + 1) * 2) { + var s = v[0].substring(i, (i + 1) * 2) + hash.update(new Buffer(s, 'ascii').toString('hex'), 'hex') + _hash.update(new Buffer(s, 'ascii').toString('hex'), 'hex') + } + var a = hash.digest('hex') + var e = _hash.digest('hex') + + console.log(a, '==', e) + t.equal(a, e) + }) + + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/vectors.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/vectors.js new file mode 100644 index 0000000..4aef39c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/node_modules/sha.js/test/vectors.js @@ -0,0 +1,76 @@ +var tape = require('tape') +var vectors = require('hash-test-vectors') +// var from = require('bops/typedarray/from') +var Buffer = require('buffer').Buffer +var hexpp = require('../hexpp') + +var createHash = require('../') + +function makeTest (alg, i, verbose) { + var v = vectors[i] + + tape(alg + ': NIST vector ' + i, function (t) { + if (verbose) { + console.log(v) + console.log('VECTOR', i) + console.log('INPUT', v.input) + console.log(hexpp(new Buffer(v.input, 'base64'))) + console.log(new Buffer(v.input, 'base64').toString('hex')) + } + + var buf = new Buffer(v.input, 'base64') + t.equal(createHash(alg).update(buf).digest('hex'), v[alg]) + + i = ~~(buf.length / 2) + var buf1 = buf.slice(0, i) + var buf2 = buf.slice(i, buf.length) + + console.log(buf1.length, buf2.length, buf.length) + console.log(createHash(alg)._block.length) + + t.equal( + createHash(alg) + .update(buf1) + .update(buf2) + .digest('hex'), + v[alg] + ) + + var j, buf3 + + i = ~~(buf.length / 3) + j = ~~(buf.length * 2 / 3) + buf1 = buf.slice(0, i) + buf2 = buf.slice(i, j) + buf3 = buf.slice(j, buf.length) + + t.equal( + createHash(alg) + .update(buf1) + .update(buf2) + .update(buf3) + .digest('hex'), + v[alg] + ) + + setTimeout(function () { + // avoid "too much recursion" errors in tape in firefox + t.end() + }) + }) + +} + +if (process.argv[2]) { + makeTest(process.argv[2], parseInt(process.argv[3], 10), true) + +} else { + vectors.forEach(function (v, i) { + makeTest('sha', i) + makeTest('sha1', i) + makeTest('sha224', i) + makeTest('sha256', i) + makeTest('sha384', i) + makeTest('sha512', i) + }) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/package.json new file mode 100644 index 0000000..5072fe8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/package.json @@ -0,0 +1,40 @@ +{ + "name": "create-hash", + "version": "1.1.2", + "description": "create hashes for browserify", + "browser": "browser.js", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/crypto-browserify/createHash.git" + }, + "keywords": [ + "crypto" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/createHash/issues" + }, + "homepage": "https://github.com/crypto-browserify/createHash", + "devDependencies": { + "hash-test-vectors": "^1.3.2", + "tap-spec": "^2.1.2", + "tape": "^3.0.3" + }, + "dependencies": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "ripemd160": "^1.0.0", + "sha.js": "^2.3.6" + }, + "readme": "create-hash\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/createHash.svg)](https://travis-ci.org/crypto-browserify/createHash)\n\nNode style hashes for use in the browser, with native hash functions in node. Api is the same as hashes in node:\n\n```js\nvar createHash = require('create-hash');\nvar hash = createHash('sha224');\nhash.update('synchronous write'); //optional encoding parameter\nhash.digest();// synchronously get result with optional encoding parameter\n\nhash.write('write to it as a stream');\nhash.end();//remember it's a stream\nhash.read();//only if you ended it as a stream though\n```\n\nTo get the JavaScript version even in node do `require('create-hash/browser');`", + "readmeFilename": "readme.md", + "_id": "create-hash@1.1.2", + "_shasum": "51210062d7bb7479f6c65bb41a92208b1d61abad", + "_resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.1.2.tgz", + "_from": "https://registry.npmjs.org/create-hash/-/create-hash-1.1.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/readme.md new file mode 100644 index 0000000..a4a6815 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/readme.md @@ -0,0 +1,19 @@ +create-hash +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/createHash.svg)](https://travis-ci.org/crypto-browserify/createHash) + +Node style hashes for use in the browser, with native hash functions in node. Api is the same as hashes in node: + +```js +var createHash = require('create-hash'); +var hash = createHash('sha224'); +hash.update('synchronous write'); //optional encoding parameter +hash.digest();// synchronously get result with optional encoding parameter + +hash.write('write to it as a stream'); +hash.end();//remember it's a stream +hash.read();//only if you ended it as a stream though +``` + +To get the JavaScript version even in node do `require('create-hash/browser');` \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/test.js new file mode 100644 index 0000000..0c6bd88 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hash/test.js @@ -0,0 +1,39 @@ +var fs = require('fs') +var test = require('tape') + +var algorithms = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160', 'ripemd160'] +var encodings = [/*'binary',*/ 'hex', 'base64']; +var vectors = require('hash-test-vectors') +vectors.forEach(function (vector) { + vector.ripemd160 = vector.rmd160 +}) +var createHash = require('./browser') + +algorithms.forEach(function (algorithm) { + test('test ' + algorithm + ' against test vectors', function (t) { + vectors.forEach(function (obj, i) { + var input = new Buffer(obj.input, 'base64') + var node = obj[algorithm] + var js = createHash(algorithm).update(input).digest('hex') + t.equal(js, node, algorithm + '(testVector['+i+']) == ' + node) + }) + + encodings.forEach(function (encoding) { + vectors.forEach(function (obj, i) { + var input = new Buffer(obj.input, 'base64').toString(encoding) + var node = obj[algorithm] + var js = createHash(algorithm).update(input, encoding).digest('hex') + t.equal(js, node, algorithm + '(testVector['+i+'], '+encoding+') == ' + node) + }) + }); + vectors.forEach(function (obj, i) { + var input = new Buffer(obj.input, 'base64') + var node = obj[algorithm] + var hash = createHash(algorithm); + hash.end(input) + var js = hash.read().toString('hex') + t.equal(js, node, algorithm + '(testVector['+i+']) == ' + node) + }) + t.end() + }) +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/.travis.yml new file mode 100644 index 0000000..1416d60 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.10" + - "0.11" \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/browser.js new file mode 100644 index 0000000..b610781 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/browser.js @@ -0,0 +1,68 @@ +'use strict'; +var createHash = require('create-hash/browser'); +var inherits = require('inherits') + +var Transform = require('stream').Transform + +var ZEROS = new Buffer(128) +ZEROS.fill(0) + +function Hmac(alg, key) { + Transform.call(this) + alg = alg.toLowerCase() + if (typeof key === 'string') { + key = new Buffer(key) + } + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + this._alg = alg + this._key = key + + if (key.length > blocksize) { + key = createHash(alg).update(key).digest() + + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = new Buffer(blocksize) + var opad = this._opad = new Buffer(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + this._hash = createHash(alg).update(ipad) +} + +inherits(Hmac, Transform) + +Hmac.prototype.update = function (data, enc) { + this._hash.update(data, enc) + + return this +} + +Hmac.prototype._transform = function (data, _, next) { + this._hash.update(data) + + next() +} + +Hmac.prototype._flush = function (next) { + this.push(this.digest()) + + next() +} + +Hmac.prototype.digest = function (enc) { + var h = this._hash.digest() + + return createHash(this._alg).update(this._opad).update(h).digest(enc) +} + +module.exports = function createHmac(alg, key) { + return new Hmac(alg, key) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/index.js new file mode 100644 index 0000000..220908a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').createHmac; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/package.json new file mode 100644 index 0000000..ed13da7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/package.json @@ -0,0 +1,39 @@ +{ + "name": "create-hmac", + "version": "1.1.4", + "description": "node style hmacs in the browser", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/createHmac.git" + }, + "keywords": [ + "crypto", + "hmac" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/createHmac/issues" + }, + "homepage": "https://github.com/crypto-browserify/createHmac", + "devDependencies": { + "hash-test-vectors": "^1.3.2", + "tap-spec": "^2.1.2", + "tape": "^3.0.3" + }, + "dependencies": { + "create-hash": "^1.1.0", + "inherits": "^2.0.1" + }, + "browser": "./browser.js", + "readme": "create-hmac\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/createHmac.svg)](https://travis-ci.org/crypto-browserify/createHmac)\n\nNode style hmacs for use in the browser, with native hmac functions in node. Api is the same as hmacs in node:\n\n```js\nvar createHmac = require('create-hmac');\nvar hmac = createHmac('sha224', new Buffer(\"secret key\"));\nhmac.update('synchronous write'); //optional encoding parameter\nhmac.digest();// synchronously get result with optional encoding parameter\n\nhmac.write('write to it as a stream');\nhmac.end();//remember it's a stream\nhmac.read();//only if you ended it as a stream though\n```\n\nTo get the JavaScript version even in node require `require('create-hmac/browser');`", + "readmeFilename": "readme.md", + "_id": "create-hmac@1.1.4", + "_shasum": "d3fb4ba253eb8b3f56e39ea2fbcb8af747bd3170", + "_resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.4.tgz", + "_from": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.4.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/readme.md new file mode 100644 index 0000000..4e8bda4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/readme.md @@ -0,0 +1,19 @@ +create-hmac +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/createHmac.svg)](https://travis-ci.org/crypto-browserify/createHmac) + +Node style hmacs for use in the browser, with native hmac functions in node. Api is the same as hmacs in node: + +```js +var createHmac = require('create-hmac'); +var hmac = createHmac('sha224', new Buffer("secret key")); +hmac.update('synchronous write'); //optional encoding parameter +hmac.digest();// synchronously get result with optional encoding parameter + +hmac.write('write to it as a stream'); +hmac.end();//remember it's a stream +hmac.read();//only if you ended it as a stream though +``` + +To get the JavaScript version even in node require `require('create-hmac/browser');` \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/test.js new file mode 100644 index 0000000..cb0cd57 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/create-hmac/test.js @@ -0,0 +1,41 @@ +var test = require('tape') + +var algorithms = ['sha1', 'sha224','sha256', 'sha384', 'sha512', 'SHA512', 'md5', 'rmd160'] +var formats = [undefined, 'base64', 'hex', 'binary'] + +var vectors = require('hash-test-vectors/hmac') +var createHmac = require('./browser') +algorithms.forEach(function (alg) { + vectors.forEach(function (input) { + var key = new Buffer(input.key, 'hex') + var inputBuffer = new Buffer(input.data, 'hex') + + formats.forEach(function (format) { + test('hmac(' + alg + ') w/ ' + input.data.slice(0, 6) + '... as ' + format, function (t) { + var hmac = createHmac(alg, key) + + var formattedInput = format ? inputBuffer.toString(format) : inputBuffer + hmac.update(formattedInput, format) + + var formattedOutput = hmac.digest(format) + var output = new Buffer(formattedOutput, format) + + var truncated = input.truncate ? output.slice(0, input.truncate) : output + t.equal(truncated.toString('hex'), input[alg.toLowerCase()]) + t.end() + }) + }) + }) + + vectors.forEach(function (input) { + test('hmac(' + alg + ') as stream w/ ' + input.data.slice(0, 6) + '...', function (t) { + var hmac = createHmac(alg, new Buffer(input.key, 'hex')) + hmac.end(input.data, 'hex') + + var output = hmac.read() + var truncated = input.truncate ? output.slice(0, input.truncate) : output + t.equal(truncated.toString('hex'), input[alg.toLowerCase()]) + t.end() + }) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/.npmignore new file mode 100644 index 0000000..daa6029 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/.npmignore @@ -0,0 +1 @@ +test.js diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/.travis.yml new file mode 100644 index 0000000..0dda273 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "1" + - "2" + - "3" + - "4" +sudo: false diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/browser.js new file mode 100644 index 0000000..d4be92b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/browser.js @@ -0,0 +1,42 @@ +var generatePrime = require('./lib/generatePrime') +var primes = require('./lib/primes.json') + +var DH = require('./lib/dh') + +function getDiffieHellman (mod) { + var prime = new Buffer(primes[mod].prime, 'hex') + var gen = new Buffer(primes[mod].gen, 'hex') + + return new DH(prime, gen) +} + +var ENCODINGS = { + 'binary': true, 'hex': true, 'base64': true +} + +function createDiffieHellman (prime, enc, generator, genc) { + if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { + return createDiffieHellman(prime, 'binary', enc, generator) + } + + enc = enc || 'binary' + genc = genc || 'binary' + generator = generator || new Buffer([2]) + + if (!Buffer.isBuffer(generator)) { + generator = new Buffer(generator, genc) + } + + if (typeof prime === 'number') { + return new DH(generatePrime(prime, generator), generator, true) + } + + if (!Buffer.isBuffer(prime)) { + prime = new Buffer(prime, enc) + } + + return new DH(prime, generator, true) +} + +exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman +exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/index.js new file mode 100644 index 0000000..ab7c40f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/index.js @@ -0,0 +1,10 @@ +var crypto = require('crypto') + +// getDiffieHellman +exports.DiffieHellmanGroup = crypto.DiffieHellmanGroup +exports.createDiffieHellmanGroup = crypto.createDiffieHellmanGroup +exports.getDiffieHellman = crypto.getDiffieHellman + +// createDiffieHellman +exports.createDiffieHellman = crypto.createDiffieHellman +exports.DiffieHellman = crypto.DiffieHellman diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/dh.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/dh.js new file mode 100644 index 0000000..0650f65 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/dh.js @@ -0,0 +1,164 @@ +var BN = require('bn.js'); +var MillerRabin = require('miller-rabin'); +var millerRabin = new MillerRabin(); +var TWENTYFOUR = new BN(24); +var ELEVEN = new BN(11); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var primes = require('./generatePrime'); +var randomBytes = require('randombytes'); +module.exports = DH; + +function setPublicKey(pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this._pub = new BN(pub); + return this; +} + +function setPrivateKey(priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + this._priv = new BN(priv); + return this; +} + +var primeCache = {}; +function checkPrime(prime, generator) { + var gen = generator.toString('hex'); + var hex = [gen, prime.toString(16)].join('_'); + if (hex in primeCache) { + return primeCache[hex]; + } + var error = 0; + + if (prime.isEven() || + !primes.simpleSieve || + !primes.fermatTest(prime) || + !millerRabin.test(prime)) { + //not a prime so +1 + error += 1; + + if (gen === '02' || gen === '05') { + // we'd be able to check the generator + // it would fail so +8 + error += 8; + } else { + //we wouldn't be able to test the generator + // so +4 + error += 4; + } + primeCache[hex] = error; + return error; + } + if (!millerRabin.test(prime.shrn(1))) { + //not a safe prime + error += 2; + } + var rem; + switch (gen) { + case '02': + if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { + // unsuidable generator + error += 8; + } + break; + case '05': + rem = prime.mod(TEN); + if (rem.cmp(THREE) && rem.cmp(SEVEN)) { + // prime mod 10 needs to equal 3 or 7 + error += 8; + } + break; + default: + error += 4; + } + primeCache[hex] = error; + return error; +} + +function DH(prime, generator, malleable) { + this.setGenerator(generator); + this.__prime = new BN(prime); + this._prime = BN.mont(this.__prime); + this._primeLen = prime.length; + this._pub = undefined; + this._priv = undefined; + this._primeCode = undefined; + if (malleable) { + this.setPublicKey = setPublicKey; + this.setPrivateKey = setPrivateKey; + } else { + this._primeCode = 8; + } +} +Object.defineProperty(DH.prototype, 'verifyError', { + enumerable: true, + get: function () { + if (typeof this._primeCode !== 'number') { + this._primeCode = checkPrime(this.__prime, this.__gen); + } + return this._primeCode; + } +}); +DH.prototype.generateKeys = function () { + if (!this._priv) { + this._priv = new BN(randomBytes(this._primeLen)); + } + this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); + return this.getPublicKey(); +}; + +DH.prototype.computeSecret = function (other) { + other = new BN(other); + other = other.toRed(this._prime); + var secret = other.redPow(this._priv).fromRed(); + var out = new Buffer(secret.toArray()); + var prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0); + out = Buffer.concat([front, out]); + } + return out; +}; + +DH.prototype.getPublicKey = function getPublicKey(enc) { + return formatReturnValue(this._pub, enc); +}; + +DH.prototype.getPrivateKey = function getPrivateKey(enc) { + return formatReturnValue(this._priv, enc); +}; + +DH.prototype.getPrime = function (enc) { + return formatReturnValue(this.__prime, enc); +}; + +DH.prototype.getGenerator = function (enc) { + return formatReturnValue(this._gen, enc); +}; + +DH.prototype.setGenerator = function (gen, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(gen)) { + gen = new Buffer(gen, enc); + } + this.__gen = gen; + this._gen = new BN(gen); + return this; +}; + +function formatReturnValue(bn, enc) { + var buf = new Buffer(bn.toArray()); + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/generatePrime.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/generatePrime.js new file mode 100644 index 0000000..32e053c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/generatePrime.js @@ -0,0 +1,105 @@ +var randomBytes = require('randombytes'); +module.exports = findPrime; +findPrime.simpleSieve = simpleSieve; +findPrime.fermatTest = fermatTest; +var BN = require('bn.js'); +var TWENTYFOUR = new BN(24); +var MillerRabin = require('miller-rabin'); +var millerRabin = new MillerRabin(); +var ONE = new BN(1); +var TWO = new BN(2); +var FIVE = new BN(5); +var SIXTEEN = new BN(16); +var EIGHT = new BN(8); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var ELEVEN = new BN(11); +var FOUR = new BN(4); +var TWELVE = new BN(12); +var primes = null; + +function _getPrimes() { + if (primes !== null) + return primes; + + var limit = 0x100000; + var res = []; + res[0] = 2; + for (var i = 1, k = 3; k < limit; k += 2) { + var sqrt = Math.ceil(Math.sqrt(k)); + for (var j = 0; j < i && res[j] <= sqrt; j++) + if (k % res[j] === 0) + break; + + if (i !== j && res[j] <= sqrt) + continue; + + res[i++] = k; + } + primes = res; + return res; +} + +function simpleSieve(p) { + var primes = _getPrimes(); + + for (var i = 0; i < primes.length; i++) + if (p.modn(primes[i]) === 0) { + if (p.cmpn(primes[i]) === 0) { + return true; + } else { + return false; + } + } + + return true; +} + +function fermatTest(p) { + var red = BN.mont(p); + return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; +} + +function findPrime(bits, gen) { + if (bits < 16) { + // this is what openssl does + if (gen === 2 || gen === 5) { + return new BN([0x8c, 0x7b]); + } else { + return new BN([0x8c, 0x27]); + } + } + gen = new BN(gen); + + var num, n2; + + while (true) { + num = new BN(randomBytes(Math.ceil(bits / 8))); + while (num.bitLength() > bits) { + num.ishrn(1); + } + if (num.isEven()) { + num.iadd(ONE); + } + if (!num.testn(1)) { + num.iadd(TWO); + } + if (!gen.cmp(TWO)) { + while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { + num.iadd(FOUR); + } + } else if (!gen.cmp(FIVE)) { + while (num.mod(TEN).cmp(THREE)) { + num.iadd(FOUR); + } + } + n2 = num.shrn(1); + if (simpleSieve(n2) && simpleSieve(num) && + fermatTest(n2) && fermatTest(num) && + millerRabin.test(n2) && millerRabin.test(num)) { + return num; + } + } + +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/primes.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/primes.json new file mode 100644 index 0000000..9fef6c9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/lib/primes.json @@ -0,0 +1,34 @@ +{ + "modp1": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" + }, + "modp2": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" + }, + "modp5": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" + }, + "modp14": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" + }, + "modp15": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" + }, + "modp16": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" + }, + "modp17": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" + }, + "modp18": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" + } +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/.bin/miller-rabin b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/.bin/miller-rabin new file mode 100644 index 0000000..1fd4071 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/.bin/miller-rabin @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../miller-rabin/bin/miller-rabin" "$@" + ret=$? +else + node "$basedir/../miller-rabin/bin/miller-rabin" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/.bin/miller-rabin.cmd b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/.bin/miller-rabin.cmd new file mode 100644 index 0000000..de8d55c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/.bin/miller-rabin.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\miller-rabin\bin\miller-rabin" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\miller-rabin\bin\miller-rabin" %* +) \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/.npmignore new file mode 100644 index 0000000..6d1eebb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/.npmignore @@ -0,0 +1,6 @@ +benchmarks/ +coverage/ +node_modules/ +npm-debug.log +1.js +logo.png diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/.travis.yml new file mode 100644 index 0000000..936b7b7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "5" +env: + matrix: + - TEST_SUITE=unit +matrix: + include: + - node_js: "4" + env: TEST_SUITE=lint +script: npm run $TEST_SUITE diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/README.md new file mode 100644 index 0000000..fee65ba --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/README.md @@ -0,0 +1,219 @@ +# bn.js + +> BigNum in pure javascript + +[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) + +## Install +`npm install --save bn.js` + +## Usage + +```js +const BN = require('bn.js'); + +var a = new BN('dead', 16); +var b = new BN('101010', 2); + +var res = a.add(b); +console.log(res.toString(10)); // 57047 +``` + +**Note**: decimals are not supported in this library. + +## Notation + +### Prefixes + +There are several prefixes to instructions that affect the way the work. Here +is the list of them in the order of appearance in the function name: + +* `i` - perform operation in-place, storing the result in the host object (on + which the method was invoked). Might be used to avoid number allocation costs +* `u` - unsigned, ignore the sign of operands when performing operation, or + always return positive value. Second case applies to reduction operations + like `mod()`. In such cases if the result will be negative - modulo will be + added to the result to make it positive + +### Postfixes + +The only available postfix at the moment is: + +* `n` - which means that the argument of the function must be a plain JavaScript + number + +### Examples + +* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` +* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value +* `a.iushln(13)` - shift bits of `a` left by 13 + +## Instructions + +Prefixes/postfixes are put in parens at the of the line. `endian` - could be +either `le` (little-endian) or `be` (big-endian). + +### Utilities + +* `a.clone()` - clone number +* `a.toString(base, length)` - convert to base-string and pad with zeroes +* `a.toNumber()` - convert to Javascript Number (limited to 53 bits) +* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) +* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero + pad to length, throwing if already exceeding +* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, + which must behave like an `Array` +* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available) +* `a.bitLength()` - get number of bits occupied +* `a.zeroBits()` - return number of less-significant consequent zero bits + (example: `1010000` has 4 zero bits) +* `a.byteLength()` - return number of bytes occupied +* `a.isNeg()` - true if the number is negative +* `a.isEven()` - no comments +* `a.isOdd()` - no comments +* `a.isZero()` - no comments +* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) + depending on the comparison result (`ucmp`, `cmpn`) +* `a.lt(b)` - `a` less than `b` (`n`) +* `a.lte(b)` - `a` less than or equals `b` (`n`) +* `a.gt(b)` - `a` greater than `b` (`n`) +* `a.gte(b)` - `a` greater than or equals `b` (`n`) +* `a.eq(b)` - `a` equals `b` (`n`) +* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width +* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width +* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance + +### Arithmetics + +* `a.neg()` - negate sign (`i`) +* `a.abs()` - absolute value (`i`) +* `a.add(b)` - addition (`i`, `n`, `in`) +* `a.sub(b)` - subtraction (`i`, `n`, `in`) +* `a.mul(b)` - multiply (`i`, `n`, `in`) +* `a.sqr()` - square (`i`) +* `a.pow(b)` - raise `a` to the power of `b` +* `a.div(b)` - divide (`divn`, `idivn`) +* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) +* `a.divRound(b)` - rounded division + +### Bit operations + +* `a.or(b)` - or (`i`, `u`, `iu`) +* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced + with `andn` in future) +* `a.xor(b)` - xor (`i`, `u`, `iu`) +* `a.setn(b)` - set specified bit to `1` +* `a.shln(b)` - shift left (`i`, `u`, `iu`) +* `a.shrn(b)` - shift right (`i`, `u`, `iu`) +* `a.testn(b)` - test if specified bit is set +* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) +* `a.bincn(b)` - add `1 << b` to the number +* `a.notn(w)` - not (for the width specified by `w`) (`i`) + +### Reduction + +* `a.gcd(b)` - GCD +* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) +* `a.invm(b)` - inverse `a` modulo `b` + +## Fast reduction + +When doing lots of reductions using the same modulo, it might be beneficial to +use some tricks: like [Montgomery multiplication][0], or using special algorithm +for [Mersenne Prime][1]. + +### Reduction context + +To enable this tricks one should create a reduction context: + +```js +var red = BN.red(num); +``` +where `num` is just a BN instance. + +Or: + +```js +var red = BN.red(primeName); +``` + +Where `primeName` is either of these [Mersenne Primes][1]: + +* `'k256'` +* `'p224'` +* `'p192'` +* `'p25519'` + +Or: + +```js +var red = BN.mont(num); +``` + +To reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than +`.red(num)`, but slower than `BN.red(primeName)`. + +### Converting numbers + +Before performing anything in reduction context - numbers should be converted +to it. Usually, this means that one should: + +* Convert inputs to reducted ones +* Operate on them in reduction context +* Convert outputs back from the reduction context + +Here is how one may convert numbers to `red`: + +```js +var redA = a.toRed(red); +``` +Where `red` is a reduction context created using instructions above + +Here is how to convert them back: + +```js +var a = redA.fromRed(); +``` + +### Red instructions + +Most of the instructions from the very start of this readme have their +counterparts in red context: + +* `a.redAdd(b)`, `a.redIAdd(b)` +* `a.redSub(b)`, `a.redISub(b)` +* `a.redShl(num)` +* `a.redMul(b)`, `a.redIMul(b)` +* `a.redSqr()`, `a.redISqr()` +* `a.redSqrt()` - square root modulo reduction context's prime +* `a.redInvm()` - modular inverse of the number +* `a.redNeg()` +* `a.redPow(b)` - modular exponentiation + +## LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2015. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + +[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication +[1]: https://en.wikipedia.org/wiki/Mersenne_prime diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js new file mode 100644 index 0000000..3ca1646 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js @@ -0,0 +1,3420 @@ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buf' + 'fer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + return num !== null && typeof num === 'object' && + num.constructor.name === 'BN' && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var length = this.bitLength(); + var ret; + if (length <= 26) { + ret = this.words[0]; + } else if (length <= 52) { + ret = (this.words[1] * 0x4000000) + this.words[0]; + } else if (length === 53) { + // NOTE: at this stage it is known that the top bit is set + ret = 0x10000000000000 + (this.words[1] * 0x4000000) + this.words[0]; + } else { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid += Math.imul(ah0, bl0); + hi = Math.imul(ah0, bh0); + var w0 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w0 >>> 26); + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid += Math.imul(ah1, bl0); + hi = Math.imul(ah1, bh0); + lo += Math.imul(al0, bl1); + mid += Math.imul(al0, bh1); + mid += Math.imul(ah0, bl1); + hi += Math.imul(ah0, bh1); + var w1 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w1 >>> 26); + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid += Math.imul(ah2, bl0); + hi = Math.imul(ah2, bh0); + lo += Math.imul(al1, bl1); + mid += Math.imul(al1, bh1); + mid += Math.imul(ah1, bl1); + hi += Math.imul(ah1, bh1); + lo += Math.imul(al0, bl2); + mid += Math.imul(al0, bh2); + mid += Math.imul(ah0, bl2); + hi += Math.imul(ah0, bh2); + var w2 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w2 >>> 26); + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid += Math.imul(ah3, bl0); + hi = Math.imul(ah3, bh0); + lo += Math.imul(al2, bl1); + mid += Math.imul(al2, bh1); + mid += Math.imul(ah2, bl1); + hi += Math.imul(ah2, bh1); + lo += Math.imul(al1, bl2); + mid += Math.imul(al1, bh2); + mid += Math.imul(ah1, bl2); + hi += Math.imul(ah1, bh2); + lo += Math.imul(al0, bl3); + mid += Math.imul(al0, bh3); + mid += Math.imul(ah0, bl3); + hi += Math.imul(ah0, bh3); + var w3 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w3 >>> 26); + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid += Math.imul(ah4, bl0); + hi = Math.imul(ah4, bh0); + lo += Math.imul(al3, bl1); + mid += Math.imul(al3, bh1); + mid += Math.imul(ah3, bl1); + hi += Math.imul(ah3, bh1); + lo += Math.imul(al2, bl2); + mid += Math.imul(al2, bh2); + mid += Math.imul(ah2, bl2); + hi += Math.imul(ah2, bh2); + lo += Math.imul(al1, bl3); + mid += Math.imul(al1, bh3); + mid += Math.imul(ah1, bl3); + hi += Math.imul(ah1, bh3); + lo += Math.imul(al0, bl4); + mid += Math.imul(al0, bh4); + mid += Math.imul(ah0, bl4); + hi += Math.imul(ah0, bh4); + var w4 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w4 >>> 26); + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid += Math.imul(ah5, bl0); + hi = Math.imul(ah5, bh0); + lo += Math.imul(al4, bl1); + mid += Math.imul(al4, bh1); + mid += Math.imul(ah4, bl1); + hi += Math.imul(ah4, bh1); + lo += Math.imul(al3, bl2); + mid += Math.imul(al3, bh2); + mid += Math.imul(ah3, bl2); + hi += Math.imul(ah3, bh2); + lo += Math.imul(al2, bl3); + mid += Math.imul(al2, bh3); + mid += Math.imul(ah2, bl3); + hi += Math.imul(ah2, bh3); + lo += Math.imul(al1, bl4); + mid += Math.imul(al1, bh4); + mid += Math.imul(ah1, bl4); + hi += Math.imul(ah1, bh4); + lo += Math.imul(al0, bl5); + mid += Math.imul(al0, bh5); + mid += Math.imul(ah0, bl5); + hi += Math.imul(ah0, bh5); + var w5 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w5 >>> 26); + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid += Math.imul(ah6, bl0); + hi = Math.imul(ah6, bh0); + lo += Math.imul(al5, bl1); + mid += Math.imul(al5, bh1); + mid += Math.imul(ah5, bl1); + hi += Math.imul(ah5, bh1); + lo += Math.imul(al4, bl2); + mid += Math.imul(al4, bh2); + mid += Math.imul(ah4, bl2); + hi += Math.imul(ah4, bh2); + lo += Math.imul(al3, bl3); + mid += Math.imul(al3, bh3); + mid += Math.imul(ah3, bl3); + hi += Math.imul(ah3, bh3); + lo += Math.imul(al2, bl4); + mid += Math.imul(al2, bh4); + mid += Math.imul(ah2, bl4); + hi += Math.imul(ah2, bh4); + lo += Math.imul(al1, bl5); + mid += Math.imul(al1, bh5); + mid += Math.imul(ah1, bl5); + hi += Math.imul(ah1, bh5); + lo += Math.imul(al0, bl6); + mid += Math.imul(al0, bh6); + mid += Math.imul(ah0, bl6); + hi += Math.imul(ah0, bh6); + var w6 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w6 >>> 26); + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid += Math.imul(ah7, bl0); + hi = Math.imul(ah7, bh0); + lo += Math.imul(al6, bl1); + mid += Math.imul(al6, bh1); + mid += Math.imul(ah6, bl1); + hi += Math.imul(ah6, bh1); + lo += Math.imul(al5, bl2); + mid += Math.imul(al5, bh2); + mid += Math.imul(ah5, bl2); + hi += Math.imul(ah5, bh2); + lo += Math.imul(al4, bl3); + mid += Math.imul(al4, bh3); + mid += Math.imul(ah4, bl3); + hi += Math.imul(ah4, bh3); + lo += Math.imul(al3, bl4); + mid += Math.imul(al3, bh4); + mid += Math.imul(ah3, bl4); + hi += Math.imul(ah3, bh4); + lo += Math.imul(al2, bl5); + mid += Math.imul(al2, bh5); + mid += Math.imul(ah2, bl5); + hi += Math.imul(ah2, bh5); + lo += Math.imul(al1, bl6); + mid += Math.imul(al1, bh6); + mid += Math.imul(ah1, bl6); + hi += Math.imul(ah1, bh6); + lo += Math.imul(al0, bl7); + mid += Math.imul(al0, bh7); + mid += Math.imul(ah0, bl7); + hi += Math.imul(ah0, bh7); + var w7 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w7 >>> 26); + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid += Math.imul(ah8, bl0); + hi = Math.imul(ah8, bh0); + lo += Math.imul(al7, bl1); + mid += Math.imul(al7, bh1); + mid += Math.imul(ah7, bl1); + hi += Math.imul(ah7, bh1); + lo += Math.imul(al6, bl2); + mid += Math.imul(al6, bh2); + mid += Math.imul(ah6, bl2); + hi += Math.imul(ah6, bh2); + lo += Math.imul(al5, bl3); + mid += Math.imul(al5, bh3); + mid += Math.imul(ah5, bl3); + hi += Math.imul(ah5, bh3); + lo += Math.imul(al4, bl4); + mid += Math.imul(al4, bh4); + mid += Math.imul(ah4, bl4); + hi += Math.imul(ah4, bh4); + lo += Math.imul(al3, bl5); + mid += Math.imul(al3, bh5); + mid += Math.imul(ah3, bl5); + hi += Math.imul(ah3, bh5); + lo += Math.imul(al2, bl6); + mid += Math.imul(al2, bh6); + mid += Math.imul(ah2, bl6); + hi += Math.imul(ah2, bh6); + lo += Math.imul(al1, bl7); + mid += Math.imul(al1, bh7); + mid += Math.imul(ah1, bl7); + hi += Math.imul(ah1, bh7); + lo += Math.imul(al0, bl8); + mid += Math.imul(al0, bh8); + mid += Math.imul(ah0, bl8); + hi += Math.imul(ah0, bh8); + var w8 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w8 >>> 26); + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid += Math.imul(ah9, bl0); + hi = Math.imul(ah9, bh0); + lo += Math.imul(al8, bl1); + mid += Math.imul(al8, bh1); + mid += Math.imul(ah8, bl1); + hi += Math.imul(ah8, bh1); + lo += Math.imul(al7, bl2); + mid += Math.imul(al7, bh2); + mid += Math.imul(ah7, bl2); + hi += Math.imul(ah7, bh2); + lo += Math.imul(al6, bl3); + mid += Math.imul(al6, bh3); + mid += Math.imul(ah6, bl3); + hi += Math.imul(ah6, bh3); + lo += Math.imul(al5, bl4); + mid += Math.imul(al5, bh4); + mid += Math.imul(ah5, bl4); + hi += Math.imul(ah5, bh4); + lo += Math.imul(al4, bl5); + mid += Math.imul(al4, bh5); + mid += Math.imul(ah4, bl5); + hi += Math.imul(ah4, bh5); + lo += Math.imul(al3, bl6); + mid += Math.imul(al3, bh6); + mid += Math.imul(ah3, bl6); + hi += Math.imul(ah3, bh6); + lo += Math.imul(al2, bl7); + mid += Math.imul(al2, bh7); + mid += Math.imul(ah2, bl7); + hi += Math.imul(ah2, bh7); + lo += Math.imul(al1, bl8); + mid += Math.imul(al1, bh8); + mid += Math.imul(ah1, bl8); + hi += Math.imul(ah1, bh8); + lo += Math.imul(al0, bl9); + mid += Math.imul(al0, bh9); + mid += Math.imul(ah0, bl9); + hi += Math.imul(ah0, bh9); + var w9 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w9 >>> 26); + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid += Math.imul(ah9, bl1); + hi = Math.imul(ah9, bh1); + lo += Math.imul(al8, bl2); + mid += Math.imul(al8, bh2); + mid += Math.imul(ah8, bl2); + hi += Math.imul(ah8, bh2); + lo += Math.imul(al7, bl3); + mid += Math.imul(al7, bh3); + mid += Math.imul(ah7, bl3); + hi += Math.imul(ah7, bh3); + lo += Math.imul(al6, bl4); + mid += Math.imul(al6, bh4); + mid += Math.imul(ah6, bl4); + hi += Math.imul(ah6, bh4); + lo += Math.imul(al5, bl5); + mid += Math.imul(al5, bh5); + mid += Math.imul(ah5, bl5); + hi += Math.imul(ah5, bh5); + lo += Math.imul(al4, bl6); + mid += Math.imul(al4, bh6); + mid += Math.imul(ah4, bl6); + hi += Math.imul(ah4, bh6); + lo += Math.imul(al3, bl7); + mid += Math.imul(al3, bh7); + mid += Math.imul(ah3, bl7); + hi += Math.imul(ah3, bh7); + lo += Math.imul(al2, bl8); + mid += Math.imul(al2, bh8); + mid += Math.imul(ah2, bl8); + hi += Math.imul(ah2, bh8); + lo += Math.imul(al1, bl9); + mid += Math.imul(al1, bh9); + mid += Math.imul(ah1, bl9); + hi += Math.imul(ah1, bh9); + var w10 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w10 >>> 26); + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid += Math.imul(ah9, bl2); + hi = Math.imul(ah9, bh2); + lo += Math.imul(al8, bl3); + mid += Math.imul(al8, bh3); + mid += Math.imul(ah8, bl3); + hi += Math.imul(ah8, bh3); + lo += Math.imul(al7, bl4); + mid += Math.imul(al7, bh4); + mid += Math.imul(ah7, bl4); + hi += Math.imul(ah7, bh4); + lo += Math.imul(al6, bl5); + mid += Math.imul(al6, bh5); + mid += Math.imul(ah6, bl5); + hi += Math.imul(ah6, bh5); + lo += Math.imul(al5, bl6); + mid += Math.imul(al5, bh6); + mid += Math.imul(ah5, bl6); + hi += Math.imul(ah5, bh6); + lo += Math.imul(al4, bl7); + mid += Math.imul(al4, bh7); + mid += Math.imul(ah4, bl7); + hi += Math.imul(ah4, bh7); + lo += Math.imul(al3, bl8); + mid += Math.imul(al3, bh8); + mid += Math.imul(ah3, bl8); + hi += Math.imul(ah3, bh8); + lo += Math.imul(al2, bl9); + mid += Math.imul(al2, bh9); + mid += Math.imul(ah2, bl9); + hi += Math.imul(ah2, bh9); + var w11 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w11 >>> 26); + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid += Math.imul(ah9, bl3); + hi = Math.imul(ah9, bh3); + lo += Math.imul(al8, bl4); + mid += Math.imul(al8, bh4); + mid += Math.imul(ah8, bl4); + hi += Math.imul(ah8, bh4); + lo += Math.imul(al7, bl5); + mid += Math.imul(al7, bh5); + mid += Math.imul(ah7, bl5); + hi += Math.imul(ah7, bh5); + lo += Math.imul(al6, bl6); + mid += Math.imul(al6, bh6); + mid += Math.imul(ah6, bl6); + hi += Math.imul(ah6, bh6); + lo += Math.imul(al5, bl7); + mid += Math.imul(al5, bh7); + mid += Math.imul(ah5, bl7); + hi += Math.imul(ah5, bh7); + lo += Math.imul(al4, bl8); + mid += Math.imul(al4, bh8); + mid += Math.imul(ah4, bl8); + hi += Math.imul(ah4, bh8); + lo += Math.imul(al3, bl9); + mid += Math.imul(al3, bh9); + mid += Math.imul(ah3, bl9); + hi += Math.imul(ah3, bh9); + var w12 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w12 >>> 26); + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid += Math.imul(ah9, bl4); + hi = Math.imul(ah9, bh4); + lo += Math.imul(al8, bl5); + mid += Math.imul(al8, bh5); + mid += Math.imul(ah8, bl5); + hi += Math.imul(ah8, bh5); + lo += Math.imul(al7, bl6); + mid += Math.imul(al7, bh6); + mid += Math.imul(ah7, bl6); + hi += Math.imul(ah7, bh6); + lo += Math.imul(al6, bl7); + mid += Math.imul(al6, bh7); + mid += Math.imul(ah6, bl7); + hi += Math.imul(ah6, bh7); + lo += Math.imul(al5, bl8); + mid += Math.imul(al5, bh8); + mid += Math.imul(ah5, bl8); + hi += Math.imul(ah5, bh8); + lo += Math.imul(al4, bl9); + mid += Math.imul(al4, bh9); + mid += Math.imul(ah4, bl9); + hi += Math.imul(ah4, bh9); + var w13 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w13 >>> 26); + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid += Math.imul(ah9, bl5); + hi = Math.imul(ah9, bh5); + lo += Math.imul(al8, bl6); + mid += Math.imul(al8, bh6); + mid += Math.imul(ah8, bl6); + hi += Math.imul(ah8, bh6); + lo += Math.imul(al7, bl7); + mid += Math.imul(al7, bh7); + mid += Math.imul(ah7, bl7); + hi += Math.imul(ah7, bh7); + lo += Math.imul(al6, bl8); + mid += Math.imul(al6, bh8); + mid += Math.imul(ah6, bl8); + hi += Math.imul(ah6, bh8); + lo += Math.imul(al5, bl9); + mid += Math.imul(al5, bh9); + mid += Math.imul(ah5, bl9); + hi += Math.imul(ah5, bh9); + var w14 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w14 >>> 26); + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid += Math.imul(ah9, bl6); + hi = Math.imul(ah9, bh6); + lo += Math.imul(al8, bl7); + mid += Math.imul(al8, bh7); + mid += Math.imul(ah8, bl7); + hi += Math.imul(ah8, bh7); + lo += Math.imul(al7, bl8); + mid += Math.imul(al7, bh8); + mid += Math.imul(ah7, bl8); + hi += Math.imul(ah7, bh8); + lo += Math.imul(al6, bl9); + mid += Math.imul(al6, bh9); + mid += Math.imul(ah6, bl9); + hi += Math.imul(ah6, bh9); + var w15 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w15 >>> 26); + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid += Math.imul(ah9, bl7); + hi = Math.imul(ah9, bh7); + lo += Math.imul(al8, bl8); + mid += Math.imul(al8, bh8); + mid += Math.imul(ah8, bl8); + hi += Math.imul(ah8, bh8); + lo += Math.imul(al7, bl9); + mid += Math.imul(al7, bh9); + mid += Math.imul(ah7, bl9); + hi += Math.imul(ah7, bh9); + var w16 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w16 >>> 26); + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid += Math.imul(ah9, bl8); + hi = Math.imul(ah9, bh8); + lo += Math.imul(al8, bl9); + mid += Math.imul(al8, bh9); + mid += Math.imul(ah8, bl9); + hi += Math.imul(ah8, bh9); + var w17 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w17 >>> 26); + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid += Math.imul(ah9, bl9); + hi = Math.imul(ah9, bh9); + var w18 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w18 >>> 26); + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})(typeof module === 'undefined' || module, this); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/package.json new file mode 100644 index 0000000..63ecf80 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/package.json @@ -0,0 +1,42 @@ +{ + "name": "bn.js", + "version": "4.11.1", + "description": "Big number implementation in pure javascript", + "main": "lib/bn.js", + "scripts": { + "lint": "semistandard", + "unit": "mocha --reporter=spec test/*-test.js", + "test": "npm run lint && npm run unit" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/bn.js.git" + }, + "keywords": [ + "BN", + "BigNum", + "Big number", + "Modulo", + "Montgomery" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/bn.js/issues" + }, + "homepage": "https://github.com/indutny/bn.js", + "devDependencies": { + "istanbul": "^0.3.5", + "mocha": "^2.1.0", + "semistandard": "^7.0.4" + }, + "readme": "# \"bn.js\"\n\n> BigNum in pure javascript\n\n[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js)\n\n## Install\n`npm install --save bn.js`\n\n## Usage\n\n```js\nconst BN = require('bn.js');\n\nvar a = new BN('dead', 16);\nvar b = new BN('101010', 2);\n\nvar res = a.add(b);\nconsole.log(res.toString(10)); // 57047\n```\n\n**Note**: decimals are not supported in this library.\n\n## Notation\n\n### Prefixes\n\nThere are several prefixes to instructions that affect the way the work. Here\nis the list of them in the order of appearance in the function name:\n\n* `i` - perform operation in-place, storing the result in the host object (on\n which the method was invoked). Might be used to avoid number allocation costs\n* `u` - unsigned, ignore the sign of operands when performing operation, or\n always return positive value. Second case applies to reduction operations\n like `mod()`. In such cases if the result will be negative - modulo will be\n added to the result to make it positive\n\n### Postfixes\n\nThe only available postfix at the moment is:\n\n* `n` - which means that the argument of the function must be a plain JavaScript\n number\n\n### Examples\n\n* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a`\n* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value\n* `a.iushln(13)` - shift bits of `a` left by 13\n\n## Instructions\n\nPrefixes/postfixes are put in parens at the of the line. `endian` - could be\neither `le` (little-endian) or `be` (big-endian).\n\n### Utilities\n\n* `a.clone()` - clone number\n* `a.toString(base, length)` - convert to base-string and pad with zeroes\n* `a.toNumber()` - convert to Javascript Number (limited to 53 bits)\n* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`)\n* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero\n pad to length, throwing if already exceeding\n* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`,\n which must behave like an `Array`\n* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available)\n* `a.bitLength()` - get number of bits occupied\n* `a.zeroBits()` - return number of less-significant consequent zero bits\n (example: `1010000` has 4 zero bits)\n* `a.byteLength()` - return number of bytes occupied\n* `a.isNeg()` - true if the number is negative\n* `a.isEven()` - no comments\n* `a.isOdd()` - no comments\n* `a.isZero()` - no comments\n* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b)\n depending on the comparison result (`ucmp`, `cmpn`)\n* `a.lt(b)` - `a` less than `b` (`n`)\n* `a.lte(b)` - `a` less than or equals `b` (`n`)\n* `a.gt(b)` - `a` greater than `b` (`n`)\n* `a.gte(b)` - `a` greater than or equals `b` (`n`)\n* `a.eq(b)` - `a` equals `b` (`n`)\n* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width\n* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width\n* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance\n\n### Arithmetics\n\n* `a.neg()` - negate sign (`i`)\n* `a.abs()` - absolute value (`i`)\n* `a.add(b)` - addition (`i`, `n`, `in`)\n* `a.sub(b)` - subtraction (`i`, `n`, `in`)\n* `a.mul(b)` - multiply (`i`, `n`, `in`)\n* `a.sqr()` - square (`i`)\n* `a.pow(b)` - raise `a` to the power of `b`\n* `a.div(b)` - divide (`divn`, `idivn`)\n* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`)\n* `a.divRound(b)` - rounded division\n\n### Bit operations\n\n* `a.or(b)` - or (`i`, `u`, `iu`)\n* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced\n with `andn` in future)\n* `a.xor(b)` - xor (`i`, `u`, `iu`)\n* `a.setn(b)` - set specified bit to `1`\n* `a.shln(b)` - shift left (`i`, `u`, `iu`)\n* `a.shrn(b)` - shift right (`i`, `u`, `iu`)\n* `a.testn(b)` - test if specified bit is set\n* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`)\n* `a.bincn(b)` - add `1 << b` to the number\n* `a.notn(w)` - not (for the width specified by `w`) (`i`)\n\n### Reduction\n\n* `a.gcd(b)` - GCD\n* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`)\n* `a.invm(b)` - inverse `a` modulo `b`\n\n## Fast reduction\n\nWhen doing lots of reductions using the same modulo, it might be beneficial to\nuse some tricks: like [Montgomery multiplication][0], or using special algorithm\nfor [Mersenne Prime][1].\n\n### Reduction context\n\nTo enable this tricks one should create a reduction context:\n\n```js\nvar red = BN.red(num);\n```\nwhere `num` is just a BN instance.\n\nOr:\n\n```js\nvar red = BN.red(primeName);\n```\n\nWhere `primeName` is either of these [Mersenne Primes][1]:\n\n* `'k256'`\n* `'p224'`\n* `'p192'`\n* `'p25519'`\n\nOr:\n\n```js\nvar red = BN.mont(num);\n```\n\nTo reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than\n`.red(num)`, but slower than `BN.red(primeName)`.\n\n### Converting numbers\n\nBefore performing anything in reduction context - numbers should be converted\nto it. Usually, this means that one should:\n\n* Convert inputs to reducted ones\n* Operate on them in reduction context\n* Convert outputs back from the reduction context\n\nHere is how one may convert numbers to `red`:\n\n```js\nvar redA = a.toRed(red);\n```\nWhere `red` is a reduction context created using instructions above\n\nHere is how to convert them back:\n\n```js\nvar a = redA.fromRed();\n```\n\n### Red instructions\n\nMost of the instructions from the very start of this readme have their\ncounterparts in red context:\n\n* `a.redAdd(b)`, `a.redIAdd(b)`\n* `a.redSub(b)`, `a.redISub(b)`\n* `a.redShl(num)`\n* `a.redMul(b)`, `a.redIMul(b)`\n* `a.redSqr()`, `a.redISqr()`\n* `a.redSqrt()` - square root modulo reduction context's prime\n* `a.redInvm()` - modular inverse of the number\n* `a.redNeg()`\n* `a.redPow(b)` - modular exponentiation\n\n## LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2015.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication\n[1]: https://en.wikipedia.org/wiki/Mersenne_prime\n", + "readmeFilename": "README.md", + "_id": "bn.js@4.11.1", + "_shasum": "ff1c52c52fd371e9d91419439bac5cfba2b41798", + "_resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz", + "_from": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/arithmetic-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/arithmetic-test.js new file mode 100644 index 0000000..3f336ac --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/arithmetic-test.js @@ -0,0 +1,635 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; +var fixtures = require('./fixtures'); + +describe('BN.js/Arithmetic', function () { + describe('.add()', function () { + it('should add numbers', function () { + assert.equal(new BN(14).add(new BN(26)).toString(16), '28'); + var k = new BN(0x1234); + var r = k; + + for (var i = 0; i < 257; i++) { + r = r.add(k); + } + + assert.equal(r.toString(16), '125868'); + }); + + it('should handle carry properly (in-place)', function () { + var k = new BN('abcdefabcdefabcdef', 16); + var r = new BN('deadbeef', 16); + + for (var i = 0; i < 257; i++) { + r.iadd(k); + } + + assert.equal(r.toString(16), 'ac79bd9b79be7a277bde'); + }); + + it('should properly do positive + negative', function () { + var a = new BN('abcd', 16); + var b = new BN('-abce', 16); + + assert.equal(a.iadd(b).toString(16), '-1'); + + a = new BN('abcd', 16); + b = new BN('-abce', 16); + + assert.equal(a.add(b).toString(16), '-1'); + assert.equal(b.add(a).toString(16), '-1'); + }); + }); + + describe('.iaddn()', function () { + it('should allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should add negative number', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(-200); + + assert.equal(a.toString(), '-300'); + }); + + it('should allow neg + pos with big number', function () { + var a = new BN('-1000000000', 10); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.toString(), '-999999800'); + }); + + it('should carry limb', function () { + var a = new BN('3ffffff', 16); + + assert.equal(a.iaddn(1).toString(16), '4000000'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).iaddn(0x4000000); + }); + }); + }); + + describe('.sub()', function () { + it('should subtract small numbers', function () { + assert.equal(new BN(26).sub(new BN(14)).toString(16), 'c'); + assert.equal(new BN(14).sub(new BN(26)).toString(16), '-c'); + assert.equal(new BN(26).sub(new BN(26)).toString(16), '0'); + assert.equal(new BN(-26).sub(new BN(26)).toString(16), '-34'); + }); + + var a = new BN( + '31ff3c61db2db84b9823d320907a573f6ad37c437abe458b1802cda041d6384' + + 'a7d8daef41395491e2', + 16); + var b = new BN( + '6f0e4d9f1d6071c183677f601af9305721c91d31b0bbbae8fb790000', + 16); + var r = new BN( + '31ff3c61db2db84b9823d3208989726578fd75276287cd9516533a9acfb9a67' + + '76281f34583ddb91e2', + 16); + + it('should subtract big numbers', function () { + assert.equal(a.sub(b).cmp(r), 0); + }); + + it('should subtract numbers in place', function () { + assert.equal(b.clone().isub(a).neg().cmp(r), 0); + }); + + it('should subtract with carry', function () { + // Carry and copy + var a = new BN('12345', 16); + var b = new BN('1000000000000', 16); + assert.equal(a.isub(b).toString(16), '-fffffffedcbb'); + + a = new BN('12345', 16); + b = new BN('1000000000000', 16); + assert.equal(b.isub(a).toString(16), 'fffffffedcbb'); + }); + }); + + describe('.isubn()', function () { + it('should subtract negative number', function () { + var r = new BN( + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b', 16); + assert.equal(r.isubn(-1).toString(16), + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681c'); + }); + + it('should work for positive numbers', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(200); + assert.equal(a.negative, 1); + assert.equal(a.toString(), '-300'); + }); + + it('should not allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(-200); + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should change sign on small numbers at 0', function () { + var a = new BN(0).subn(2); + assert.equal(a.toString(), '-2'); + }); + + it('should change sign on small numbers at 1', function () { + var a = new BN(1).subn(2); + assert.equal(a.toString(), '-1'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).isubn(0x4000000); + }); + }); + }); + + function testMethod (name, mul) { + describe(name, function () { + it('should multiply numbers of different signs', function () { + var offsets = [ + 1, // smallMulTo + 250, // comb10MulTo + 1000, // bigMulTo + 15000 // jumboMulTo + ]; + + for (var i = 0; i < offsets.length; ++i) { + var x = new BN(1).ishln(offsets[i]); + + assert.equal(mul(x, x).isNeg(), false); + assert.equal(mul(x, x.neg()).isNeg(), true); + assert.equal(mul(x.neg(), x).isNeg(), true); + assert.equal(mul(x.neg(), x.neg()).isNeg(), false); + } + }); + + it('should multiply with carry', function () { + var n = new BN(0x1001); + var r = n; + + for (var i = 0; i < 4; i++) { + r = mul(r, n); + } + + assert.equal(r.toString(16), '100500a00a005001'); + }); + + it('should correctly multiply big numbers', function () { + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal( + mul(n, n).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40'); + assert.equal( + mul(mul(n, n), n).toString(16), + '1b888e01a06e974017a28a5b4da436169761c9730b7aeedf75fc60f687b' + + '46e0cf2cb11667f795d5569482640fe5f628939467a01a612b02350' + + '0d0161e9730279a7561043af6197798e41b7432458463e64fa81158' + + '907322dc330562697d0d600'); + }); + + it('should multiply neg number on 0', function () { + assert.equal( + mul(new BN('-100000000000'), new BN('3').div(new BN('4'))) + .toString(16), + '0' + ); + }); + + it('should regress mul big numbers', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + assert.equal(mul(q, q).toString(16), qs); + }); + }); + } + + testMethod('.mul()', function (x, y) { + return BN.prototype.mul.apply(x, [ y ]); + }); + + testMethod('.mulf()', function (x, y) { + return BN.prototype.mulf.apply(x, [ y ]); + }); + + describe('.imul()', function () { + it('should multiply numbers in-place', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('deadbeefa551edebabba8', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + + a = new BN('abcdef01234567890abcd214a25123f512361e6d236', 16); + b = new BN('deadbeefa551edebabba8121234fd21bac0341324dd', 16); + c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should multiply by 0', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('0', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should regress mul big numbers in-place', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + + assert.equal(q.isqr().toString(16), qs); + }); + }); + + describe('.muln()', function () { + it('should multiply number by small number', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('dead', 16); + var c = a.mul(b); + + assert.equal(a.muln(0xdead).toString(16), c.toString(16)); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).imuln(0x4000000); + }); + }); + }); + + describe('.pow()', function () { + it('should raise number to the power', function () { + var a = new BN('ab', 16); + var b = new BN('13', 10); + var c = a.pow(b); + + assert.equal(c.toString(16), '15963da06977df51909c9ba5b'); + }); + }); + + describe('.div()', function () { + it('should divide small numbers (<=26 bits)', function () { + assert.equal(new BN('256').div(new BN(10)).toString(10), + '25'); + assert.equal(new BN('-256').div(new BN(10)).toString(10), + '-25'); + assert.equal(new BN('256').div(new BN(-10)).toString(10), + '-25'); + assert.equal(new BN('-256').div(new BN(-10)).toString(10), + '25'); + + assert.equal(new BN('10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('10').div(new BN(-256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(-256)).toString(10), + '0'); + }); + + it('should divide large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').div(new BN('611111124969028')) + .toString(10), '1'); + assert.equal(new BN('-1222222225255589').div(new BN('611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('1222222225255589').div(new BN('-611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('-1222222225255589').div(new BN('-611111124969028')) + .toString(10), '1'); + + assert.equal(new BN('611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + }); + + it('should divide numbers', function () { + assert.equal(new BN('69527932928').div(new BN('16974594')).toString(16), + 'fff'); + assert.equal(new BN('-69527932928').div(new BN('16974594')).toString(16), + '-fff'); + + var b = new BN( + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40', + 16); + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal(b.div(n).toString(16), n.toString(16)); + + assert.equal(new BN('1').div(new BN('-5')).toString(10), '0'); + }); + + it('should not fail on regression after moving to _wordDiv', function () { + // Regression after moving to word div + var p = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', + 16); + var a = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16); + var as = a.sqr(); + assert.equal( + as.div(p).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729e58090b9'); + + p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.div(p).toString(16), + 'ffffffff00000002000000000000000000000001000000000000000000000001'); + }); + }); + + describe('.idivn()', function () { + it('should divide numbers in-place', function () { + assert.equal(new BN('10', 16).idivn(3).toString(16), '5'); + assert.equal(new BN('12', 16).idivn(3).toString(16), '6'); + assert.equal(new BN('10000000000000000').idivn(3).toString(10), + '3333333333333333'); + assert.equal( + new BN('100000000000000000000000000000').idivn(3).toString(10), + '33333333333333333333333333333'); + + var t = new BN(3); + assert.equal( + new BN('12345678901234567890123456', 16).idivn(3).toString(16), + new BN('12345678901234567890123456', 16).div(t).toString(16)); + }); + }); + + describe('.divRound()', function () { + it('should divide numbers with rounding', function () { + assert.equal(new BN(9).divRound(new BN(20)).toString(10), + '0'); + assert.equal(new BN(10).divRound(new BN(20)).toString(10), + '1'); + assert.equal(new BN(150).divRound(new BN(20)).toString(10), + '8'); + assert.equal(new BN(149).divRound(new BN(20)).toString(10), + '7'); + assert.equal(new BN(149).divRound(new BN(17)).toString(10), + '9'); + assert.equal(new BN(144).divRound(new BN(17)).toString(10), + '8'); + assert.equal(new BN(-144).divRound(new BN(17)).toString(10), + '-8'); + }); + + it('should return 1 on exact division', function () { + assert.equal(new BN(144).divRound(new BN(144)).toString(10), '1'); + }); + }); + + describe('.mod()', function () { + it('should modulo small numbers (<=26 bits)', function () { + assert.equal(new BN('256').mod(new BN(10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(10)).toString(10), + '-6'); + assert.equal(new BN('256').mod(new BN(-10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(-10)).toString(10), + '-6'); + + assert.equal(new BN('10').mod(new BN(256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(256)).toString(10), + '-10'); + assert.equal(new BN('10').mod(new BN(-256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(-256)).toString(10), + '-10'); + }); + + it('should modulo large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').mod(new BN('611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('611111124969028')) + .toString(10), '-611111100286561'); + assert.equal(new BN('1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '-611111100286561'); + + assert.equal(new BN('611111124969028').mod(new BN('1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('1222222225255589')) + .toString(10), '-611111124969028'); + assert.equal(new BN('611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '-611111124969028'); + }); + + it('should mod numbers', function () { + assert.equal(new BN('10').mod(new BN(256)).toString(16), + 'a'); + assert.equal(new BN('69527932928').mod(new BN('16974594')).toString(16), + '102f302'); + + // 178 = 10 * 17 + 8 + assert.equal(new BN(178).div(new BN(10)).toNumber(), 17); + assert.equal(new BN(178).mod(new BN(10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(10)).toNumber(), 8); + + // -178 = 10 * (-17) + (-8) + assert.equal(new BN(-178).div(new BN(10)).toNumber(), -17); + assert.equal(new BN(-178).mod(new BN(10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(10)).toNumber(), 2); + + // 178 = -10 * (-17) + 8 + assert.equal(new BN(178).div(new BN(-10)).toNumber(), -17); + assert.equal(new BN(178).mod(new BN(-10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(-10)).toNumber(), 8); + + // -178 = -10 * (17) + (-8) + assert.equal(new BN(-178).div(new BN(-10)).toNumber(), 17); + assert.equal(new BN(-178).mod(new BN(-10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(-10)).toNumber(), 2); + + // -4 = 1 * (-3) + -1 + assert.equal(new BN(-4).div(new BN(-3)).toNumber(), 1); + assert.equal(new BN(-4).mod(new BN(-3)).toNumber(), -1); + + // -4 = -1 * (3) + -1 + assert.equal(new BN(-4).mod(new BN(3)).toNumber(), -1); + // -4 = 1 * (-3) + (-1 + 3) + assert.equal(new BN(-4).umod(new BN(-3)).toNumber(), 2); + + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.mod(p).toString(16), + '0'); + }); + + it('should properly carry the sign inside division', function () { + var a = new BN('945304eb96065b2a98b57a48a06ae28d285a71b5', 'hex'); + var b = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe', + 'hex'); + + assert.equal(a.mul(b).mod(a).cmpn(0), 0); + }); + }); + + describe('.modn()', function () { + it('should act like .mod() on small numbers', function () { + assert.equal(new BN('10', 16).modn(256).toString(16), '10'); + assert.equal(new BN('100', 16).modn(256).toString(16), '0'); + assert.equal(new BN('1001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(257).toString(16), + new BN('100000000001', 16).mod(new BN(257)).toString(16)); + assert.equal(new BN('123456789012', 16).modn(3).toString(16), + new BN('123456789012', 16).mod(new BN(3)).toString(16)); + }); + }); + + describe('.abs()', function () { + it('should return absolute value', function () { + assert.equal(new BN(0x1001).abs().toString(), '4097'); + assert.equal(new BN(-0x1001).abs().toString(), '4097'); + assert.equal(new BN('ffffffff', 16).abs().toString(), '4294967295'); + }); + }); + + describe('.invm()', function () { + it('should invert relatively-prime numbers', function () { + var p = new BN(257); + var a = new BN(3); + var b = a.invm(p); + assert.equal(a.mul(b).mod(p).toString(16), '1'); + + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + a = new BN('deadbeef', 16); + b = a.invm(p192); + assert.equal(a.mul(b).mod(p192).toString(16), '1'); + + // Even base + var phi = new BN('872d9b030ba368706b68932cf07a0e0c', 16); + var e = new BN(65537); + var d = e.invm(phi); + assert.equal(e.mul(d).mod(phi).toString(16), '1'); + + // Even base (take #2) + a = new BN('5'); + b = new BN('6'); + var r = a.invm(b); + assert.equal(r.mul(a).mod(b).toString(16), '1'); + }); + }); + + describe('.gcd()', function () { + it('should return GCD', function () { + assert.equal(new BN(3).gcd(new BN(2)).toString(10), '1'); + assert.equal(new BN(18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(-12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(0)).toString(10), '18'); + assert.equal(new BN(0).gcd(new BN(-18)).toString(10), '18'); + assert.equal(new BN(2).gcd(new BN(0)).toString(10), '2'); + assert.equal(new BN(0).gcd(new BN(3)).toString(10), '3'); + assert.equal(new BN(0).gcd(new BN(0)).toString(10), '0'); + }); + }); + + describe('.egcd()', function () { + it('should return EGCD', function () { + assert.equal(new BN(3).egcd(new BN(2)).gcd.toString(10), '1'); + assert.equal(new BN(18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(-18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(0).egcd(new BN(12)).gcd.toString(10), '12'); + }); + it('should not allow 0 input', function () { + assert.throws(function () { + BN(1).egcd(0); + }); + }); + it('should not allow negative input', function () { + assert.throws(function () { + BN(1).egcd(-1); + }); + }); + }); + + describe('BN.max(a, b)', function () { + it('should return maximum', function () { + assert.equal(BN.max(new BN(3), new BN(2)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(3)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.max(new BN(2), new BN(-2)).toString(16), '2'); + }); + }); + + describe('BN.min(a, b)', function () { + it('should return minimum', function () { + assert.equal(BN.min(new BN(3), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(3)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(-2)).toString(16), '-2'); + }); + }); + + describe('BN.ineg', function () { + it('shouldn\'t change sign for zero', function () { + assert.equal(new BN(0).ineg().toString(10), '0'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/binary-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/binary-test.js new file mode 100644 index 0000000..b73242c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/binary-test.js @@ -0,0 +1,228 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Binary', function () { + describe('.shl()', function () { + it('should shl numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').shln(45).toString(16), + '206060200000000000000'); + }); + + it('should ushl numbers', function () { + assert.equal(new BN('69527932928').ushln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').ushln(45).toString(16), + '206060200000000000000'); + }); + }); + + describe('.shr()', function () { + it('should shr numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').shrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').shrn(256).toString(16), + '0'); + }); + + it('should ushr numbers', function () { + assert.equal(new BN('69527932928').ushrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').ushrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').ushrn(256).toString(16), + '0'); + }); + }); + + describe('.bincn()', function () { + it('should increment bit', function () { + assert.equal(new BN(0).bincn(1).toString(16), '2'); + assert.equal(new BN(2).bincn(1).toString(16), '4'); + assert.equal(new BN(2).bincn(1).bincn(1).toString(16), + new BN(2).bincn(2).toString(16)); + assert.equal(new BN(0xffffff).bincn(1).toString(16), '1000001'); + assert.equal(new BN(2).bincn(63).toString(16), + '8000000000000002'); + }); + }); + + describe('.imaskn()', function () { + it('should mask bits in-place', function () { + assert.equal(new BN(0).imaskn(1).toString(16), '0'); + assert.equal(new BN(3).imaskn(1).toString(16), '1'); + assert.equal(new BN('123456789', 16).imaskn(4).toString(16), '9'); + assert.equal(new BN('123456789', 16).imaskn(16).toString(16), '6789'); + assert.equal(new BN('123456789', 16).imaskn(28).toString(16), '3456789'); + }); + }); + + describe('.testn()', function () { + it('should support test specific bit', function () { + [ + 'ff', + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' + ].forEach(function (hex) { + var bn = new BN(hex, 16); + var bl = bn.bitLength(); + + for (var i = 0; i < bl; ++i) { + assert.equal(bn.testn(i), true); + } + + // test off the end + assert.equal(bn.testn(bl), false); + }); + + var xbits = '01111001010111001001000100011101' + + '11010011101100011000111001011101' + + '10010100111000000001011000111101' + + '01011111001111100100011110000010' + + '01011010100111010001010011000100' + + '01101001011110100001001111100110' + + '001110010111'; + + var x = new BN( + '23478905234580795234378912401239784125643978256123048348957342' + ); + for (var i = 0; i < x.bitLength(); ++i) { + assert.equal(x.testn(i), (xbits.charAt(i) === '1'), 'Failed @ bit ' + i); + } + }); + + it('should have short-cuts', function () { + var x = new BN('abcd', 16); + assert(!x.testn(128)); + }); + }); + + describe('.and()', function () { + it('should and numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .and(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .and(new BN('abcd', 16)).toString(16), + 'abcd'); + }); + }); + + describe('.iand()', function () { + it('should iand numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .iand(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + assert.equal(new BN('1000000000000000000000000000000000000001', 2) + .iand(new BN('1', 2)) + .toString(2), '1'); + assert.equal(new BN('1', 2) + .iand(new BN('1000000000000000000000000000000000000001', 2)) + .toString(2), '1'); + }); + }); + + describe('.or()', function () { + it('should or numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .or(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + }); + + it('should or numbers of different limb-length', function () { + assert.equal( + new BN('abcd00000000', 16) + .or(new BN('abcd', 16)).toString(16), + 'abcd0000abcd'); + }); + }); + + describe('.ior()', function () { + it('should ior numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .ior(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + assert.equal(new BN('1000000000000000000000000000000000000000', 2) + .ior(new BN('1', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + assert.equal(new BN('1', 2) + .ior(new BN('1000000000000000000000000000000000000000', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + }); + }); + + describe('.xor()', function () { + it('should xor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .xor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + }); + }); + + describe('.ixor()', function () { + it('should ixor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1', 2)) + .toString(2), '11001100110011001100110011001101'); + assert.equal(new BN('1', 2) + .ixor(new BN('11001100110011001100110011001100', 2)) + .toString(2), '11001100110011001100110011001101'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .xor(new BN('abcd', 16)).toString(16), + 'abcd00005432'); + }); + }); + + describe('.setn()', function () { + it('should allow single bits to be set', function () { + assert.equal(new BN(0).setn(2, true).toString(2), '100'); + assert.equal(new BN(0).setn(27, true).toString(2), + '1000000000000000000000000000'); + assert.equal(new BN(0).setn(63, true).toString(16), + new BN(1).iushln(63).toString(16)); + assert.equal(new BN('1000000000000000000000000001', 2).setn(27, false) + .toString(2), '1'); + assert.equal(new BN('101', 2).setn(2, false).toString(2), '1'); + }); + }); + + describe('.notn()', function () { + it('should allow bitwise negation', function () { + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(32).toString(2), + '11111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(32).toString(2), + '11111111111111111111111111000111'); + assert.equal(new BN('111000111', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111111000111'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/constructor-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/constructor-test.js new file mode 100644 index 0000000..bad412b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/constructor-test.js @@ -0,0 +1,149 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Constructor', function () { + describe('with Smi input', function () { + it('should accept one limb number', function () { + assert.equal(new BN(12345).toString(16), '3039'); + }); + + it('should accept two-limb number', function () { + assert.equal(new BN(0x4123456).toString(16), '4123456'); + }); + + it('should accept 52 bits of precision', function () { + var num = Math.pow(2, 52); + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should accept max safe integer', function () { + var num = Math.pow(2, 53) - 1; + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should not accept an unsafe integer', function () { + var num = Math.pow(2, 53); + + assert.throws(function () { + BN(num, 10); + }); + }); + + it('should accept two-limb LE number', function () { + assert.equal(new BN(0x4123456, null, 'le').toString(16), '56341204'); + }); + }); + + describe('with String input', function () { + it('should accept base-16', function () { + assert.equal(new BN('1A6B765D8CDF', 16).toString(16), '1a6b765d8cdf'); + assert.equal(new BN('1A6B765D8CDF', 16).toString(), '29048849665247'); + }); + + it('should accept base-hex', function () { + assert.equal(new BN('FF', 'hex').toString(), '255'); + }); + + it('should accept base-16 with spaces', function () { + var num = 'a89c e5af8724 c0a23e0e 0ff77500'; + assert.equal(new BN(num, 16).toString(16), num.replace(/ /g, '')); + }); + + it('should accept long base-16', function () { + var num = '123456789abcdef123456789abcdef123456789abcdef'; + assert.equal(new BN(num, 16).toString(16), num); + }); + + it('should accept positive base-10', function () { + assert.equal(new BN('10654321').toString(), '10654321'); + assert.equal(new BN('29048849665247').toString(16), '1a6b765d8cdf'); + }); + + it('should accept negative base-10', function () { + assert.equal(new BN('-29048849665247').toString(16), '-1a6b765d8cdf'); + }); + + it('should accept long base-10', function () { + var num = '10000000000000000'; + assert.equal(new BN(num).toString(10), num); + }); + + it('should accept base-2', function () { + var base2 = '11111111111111111111111111111111111111111111111111111'; + assert.equal(new BN(base2, 2).toString(2), base2); + }); + + it('should accept base-36', function () { + var base36 = 'zzZzzzZzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'; + assert.equal(new BN(base36, 36).toString(36), base36.toLowerCase()); + }); + + it('should not overflow limbs during base-10', function () { + var num = '65820182292848241686198767302293' + + '20890292528855852623664389292032'; + assert(new BN(num).words[0] < 0x4000000); + }); + + it('should accept base-16 LE integer', function () { + assert.equal(new BN('1A6B765D8CDF', 16, 'le').toString(16), + 'df8c5d766b1a'); + }); + }); + + describe('with Array input', function () { + it('should not fail on empty array', function () { + assert.equal(new BN([]).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN([ 1, 2, 3 ]).toString(16), '10203'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toString(16), '1020304'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ]).toString(16), '102030405'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toString(16), + '102030405060708'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray().join(','), '1,2,3,4'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray().join(','), + '1,2,3,4,5,6,7,8'); + }); + + it('should import little endian', function () { + assert.equal(new BN([ 1, 2, 3 ], 10, 'le').toString(16), '30201'); + assert.equal(new BN([ 1, 2, 3, 4 ], 10, 'le').toString(16), '4030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 10, 'le').toString(16), + '504030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ], 'le').toString(16), + '807060504030201'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray('le').join(','), '4,3,2,1'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray('le').join(','), + '8,7,6,5,4,3,2,1'); + }); + + it('should import big endian with implicit base', function () { + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 'le').toString(16), '504030201'); + }); + }); + + // the Array code is able to handle Buffer + describe('with Buffer input', function () { + it('should not fail on empty Buffer', function () { + assert.equal(new BN(new Buffer(0)).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex')).toString(16), '10203'); + }); + + it('should import little endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex'), 'le').toString(16), '30201'); + }); + }); + + describe('with BN input', function () { + it('should clone BN', function () { + var num = new BN(12345); + assert.equal(new BN(num).toString(10), '12345'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/fixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/fixtures.js new file mode 100644 index 0000000..39fd661 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/fixtures.js @@ -0,0 +1,264 @@ +exports.dhGroups = { + p16: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199' + + 'ffffffffffffffff', + priv: '6d5923e6449122cbbcc1b96093e0b7e4fd3e469f58daddae' + + '53b49b20664f4132675df9ce98ae0cfdcac0f4181ccb643b' + + '625f98104dcf6f7d8e81961e2cab4b5014895260cb977c7d' + + '2f981f8532fb5da60b3676dfe57f293f05d525866053ac7e' + + '65abfd19241146e92e64f309a97ef3b529af4d6189fa416c' + + '9e1a816c3bdf88e5edf48fbd8233ef9038bb46faa95122c0' + + '5a426be72039639cd2d53d37254b3d258960dcb33c255ede' + + '20e9d7b4b123c8b4f4b986f53cdd510d042166f7dd7dca98' + + '7c39ab36381ba30a5fdd027eb6128d2ef8e5802a2194d422' + + 'b05fe6e1cb4817789b923d8636c1ec4b7601c90da3ddc178' + + '52f59217ae070d87f2e75cbfb6ff92430ad26a71c8373452' + + 'ae1cc5c93350e2d7b87e0acfeba401aaf518580937bf0b6c' + + '341f8c49165a47e49ce50853989d07171c00f43dcddddf72' + + '94fb9c3f4e1124e98ef656b797ef48974ddcd43a21fa06d0' + + '565ae8ce494747ce9e0ea0166e76eb45279e5c6471db7df8' + + 'cc88764be29666de9c545e72da36da2f7a352fb17bdeb982' + + 'a6dc0193ec4bf00b2e533efd6cd4d46e6fb237b775615576' + + 'dd6c7c7bbc087a25e6909d1ebc6e5b38e5c8472c0fc429c6' + + 'f17da1838cbcd9bbef57c5b5522fd6053e62ba21fe97c826' + + 'd3889d0cc17e5fa00b54d8d9f0f46fb523698af965950f4b' + + '941369e180f0aece3870d9335f2301db251595d173902cad' + + '394eaa6ffef8be6c', + pub: 'd53703b7340bc89bfc47176d351e5cf86d5a18d9662eca3c' + + '9759c83b6ccda8859649a5866524d77f79e501db923416ca' + + '2636243836d3e6df752defc0fb19cc386e3ae48ad647753f' + + 'bf415e2612f8a9fd01efe7aca249589590c7e6a0332630bb' + + '29c5b3501265d720213790556f0f1d114a9e2071be3620bd' + + '4ee1e8bb96689ac9e226f0a4203025f0267adc273a43582b' + + '00b70b490343529eaec4dcff140773cd6654658517f51193' + + '13f21f0a8e04fe7d7b21ffeca85ff8f87c42bb8d9cb13a72' + + 'c00e9c6e9dfcedda0777af951cc8ccab90d35e915e707d8e' + + '4c2aca219547dd78e9a1a0730accdc9ad0b854e51edd1e91' + + '4756760bab156ca6e3cb9c625cf0870def34e9ac2e552800' + + 'd6ce506d43dbbc75acfa0c8d8fb12daa3c783fb726f187d5' + + '58131779239c912d389d0511e0f3a81969d12aeee670e48f' + + 'ba41f7ed9f10705543689c2506b976a8ffabed45e33795b0' + + '1df4f6b993a33d1deab1316a67419afa31fbb6fdd252ee8c' + + '7c7d1d016c44e3fcf6b41898d7f206aa33760b505e4eff2e' + + 'c624bc7fe636b1d59e45d6f904fc391419f13d1f0cdb5b6c' + + '2378b09434159917dde709f8a6b5dc30994d056e3f964371' + + '11587ac7af0a442b8367a7bd940f752ddabf31cf01171e24' + + 'd78df136e9681cd974ce4f858a5fb6efd3234a91857bb52d' + + '9e7b414a8bc66db4b5a73bbeccfb6eb764b4f0cbf0375136' + + 'b024b04e698d54a5' + }, + p17: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934028492' + + '36c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bd' + + 'f8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831' + + '179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1b' + + 'db7f1447e6cc254b332051512bd7af426fb8f401378cd2bf' + + '5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6' + + 'd55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f3' + + '23a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aa' + + 'cc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be328' + + '06a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55c' + + 'da56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee' + + '12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff', + priv: '6017f2bc23e1caff5b0a8b4e1fc72422b5204415787801dc' + + '025762b8dbb98ab57603aaaa27c4e6bdf742b4a1726b9375' + + 'a8ca3cf07771779589831d8bd18ddeb79c43e7e77d433950' + + 'e652e49df35b11fa09644874d71d62fdaffb580816c2c88c' + + '2c4a2eefd4a660360316741b05a15a2e37f236692ad3c463' + + 'fff559938fc6b77176e84e1bb47fb41af691c5eb7bb81bd8' + + 'c918f52625a1128f754b08f5a1403b84667231c4dfe07ed4' + + '326234c113931ce606037e960f35a2dfdec38a5f057884d3' + + '0af8fab3be39c1eeb390205fd65982191fc21d5aa30ddf51' + + 'a8e1c58c0c19fc4b4a7380ea9e836aaf671c90c29bc4bcc7' + + '813811aa436a7a9005de9b507957c56a9caa1351b6efc620' + + '7225a18f6e97f830fb6a8c4f03b82f4611e67ab9497b9271' + + 'd6ac252793cc3e5538990dbd894d2dbc2d152801937d9f74' + + 'da4b741b50b4d40e4c75e2ac163f7b397fd555648b249f97' + + 'ffe58ffb6d096aa84534c4c5729cff137759bd34e80db4ab' + + '47e2b9c52064e7f0bf677f72ac9e5d0c6606943683f9d12f' + + '180cf065a5cb8ec3179a874f358847a907f8471d15f1e728' + + '7023249d6d13c82da52628654438f47b8b5cdf4761fbf6ad' + + '9219eceac657dbd06cf2ab776ad4c968f81c3d039367f0a4' + + 'd77c7ec4435c27b6c147071665100063b5666e06eb2fb2cc' + + '3159ba34bc98ca346342195f6f1fb053ddc3bc1873564d40' + + '1c6738cdf764d6e1ff25ca5926f80102ea6593c17170966b' + + 'b5d7352dd7fb821230237ea3ebed1f920feaadbd21be295a' + + '69f2083deae9c5cdf5f4830eb04b7c1f80cc61c17232d79f' + + '7ecc2cc462a7965f804001c89982734e5abba2d31df1b012' + + '152c6b226dff34510b54be8c2cd68d795def66c57a3abfb6' + + '896f1d139e633417f8c694764974d268f46ece3a8d6616ea' + + 'a592144be48ee1e0a1595d3e5edfede5b27cec6c48ceb2ff' + + 'b42cb44275851b0ebf87dfc9aa2d0cb0805e9454b051dfe8' + + 'a29fadd82491a4b4c23f2d06ba45483ab59976da1433c9ce' + + '500164b957a04cf62dd67595319b512fc4b998424d1164dd' + + 'bbe5d1a0f7257cbb04ec9b5ed92079a1502d98725023ecb2', + pub: '3bf836229c7dd874fe37c1790d201e82ed8e192ed61571ca' + + '7285264974eb2a0171f3747b2fc23969a916cbd21e14f7e2' + + 'f0d72dcd2247affba926f9e7bb99944cb5609aed85e71b89' + + 'e89d2651550cb5bd8281bd3144066af78f194032aa777739' + + 'cccb7862a1af401f99f7e5c693f25ddce2dedd9686633820' + + 'd28d0f5ed0c6b5a094f5fe6170b8e2cbc9dff118398baee6' + + 'e895a6301cb6e881b3cae749a5bdf5c56fc897ff68bc73f2' + + '4811bb108b882872bade1f147d886a415cda2b93dd90190c' + + 'be5c2dd53fe78add5960e97f58ff2506afe437f4cf4c912a' + + '397c1a2139ac6207d3ab76e6b7ffd23bb6866dd7f87a9ae5' + + '578789084ff2d06ea0d30156d7a10496e8ebe094f5703539' + + '730f5fdbebc066de417be82c99c7da59953071f49da7878d' + + 'a588775ff2a7f0084de390f009f372af75cdeba292b08ea8' + + '4bd13a87e1ca678f9ad148145f7cef3620d69a891be46fbb' + + 'cad858e2401ec0fd72abdea2f643e6d0197b7646fbb83220' + + '0f4cf7a7f6a7559f9fb0d0f1680822af9dbd8dec4cd1b5e1' + + '7bc799e902d9fe746ddf41da3b7020350d3600347398999a' + + 'baf75d53e03ad2ee17de8a2032f1008c6c2e6618b62f225b' + + 'a2f350179445debe68500fcbb6cae970a9920e321b468b74' + + '5fb524fb88abbcacdca121d737c44d30724227a99745c209' + + 'b970d1ff93bbc9f28b01b4e714d6c9cbd9ea032d4e964d8e' + + '8fff01db095160c20b7646d9fcd314c4bc11bcc232aeccc0' + + 'fbedccbc786951025597522eef283e3f56b44561a0765783' + + '420128638c257e54b972a76e4261892d81222b3e2039c61a' + + 'ab8408fcaac3d634f848ab3ee65ea1bd13c6cd75d2e78060' + + 'e13cf67fbef8de66d2049e26c0541c679fff3e6afc290efe' + + '875c213df9678e4a7ec484bc87dae5f0a1c26d7583e38941' + + 'b7c68b004d4df8b004b666f9448aac1cc3ea21461f41ea5d' + + 'd0f7a9e6161cfe0f58bcfd304bdc11d78c2e9d542e86c0b5' + + '6985cc83f693f686eaac17411a8247bf62f5ccc7782349b5' + + 'cc1f20e312fa2acc0197154d1bfee507e8db77e8f2732f2d' + + '641440ccf248e8643b2bd1e1f9e8239356ab91098fcb431d', + q: 'a899c59999bf877d96442d284359783bdc64b5f878b688fe' + + '51407f0526e616553ad0aaaac4d5bed3046f10a1faaf42bb' + + '2342dc4b7908eea0c46e4c4576897675c2bfdc4467870d3d' + + 'cd90adaed4359237a4bc6924bfb99aa6bf5f5ede15b574ea' + + 'e977eac096f3c67d09bda574c6306c6123fa89d2f086b8dc' + + 'ff92bc570c18d83fe6c810ccfd22ce4c749ef5e6ead3fffe' + + 'c63d95e0e3fde1df9db6a35fa1d107058f37e41957769199' + + 'd945dd7a373622c65f0af3fd9eb1ddc5c764bbfaf7a3dc37' + + '2548e683b970dac4aa4b9869080d2376c9adecebb84e172c' + + '09aeeb25fb8df23e60033260c4f8aac6b8b98ab894b1fb84' + + 'ebb83c0fb2081c3f3eee07f44e24d8fabf76f19ed167b0d7' + + 'ff971565aa4efa3625fce5a43ceeaa3eebb3ce88a00f597f' + + '048c69292b38dba2103ecdd5ec4ccfe3b2d87fa6202f334b' + + 'c1cab83b608dfc875b650b69f2c7e23c0b2b4adf149a6100' + + 'db1b6dbad4679ecb1ea95eafaba3bd00db11c2134f5a8686' + + '358b8b2ab49a1b2e85e1e45caeac5cd4dc0b3b5fffba8871' + + '1c6baf399edd48dad5e5c313702737a6dbdcede80ca358e5' + + '1d1c4fe42e8948a084403f61baed38aa9a1a5ce2918e9f33' + + '100050a430b47bc592995606440272a4994677577a6aaa1b' + + 'a101045dbec5a4e9566dab5445d1af3ed19519f07ac4e2a8' + + 'bd0a84b01978f203a9125a0be020f71fab56c2c9e344d4f4' + + '12d53d3cd8eb74ca5122002e931e3cb0bd4b7492436be17a' + + 'd7ebe27148671f59432c36d8c56eb762655711cfc8471f70' + + '83a8b7283bcb3b1b1d47d37c23d030288cfcef05fbdb4e16' + + '652ee03ee7b77056a808cd700bc3d9ef826eca9a59be959c' + + '947c865d6b372a1ca2d503d7df6d7611b12111665438475a' + + '1c64145849b3da8c2d343410df892d958db232617f9896f1' + + 'de95b8b5a47132be80dd65298c7f2047858409bf762dbc05' + + 'a62ca392ac40cfb8201a0607a2cae07d99a307625f2b2d04' + + 'fe83fbd3ab53602263410f143b73d5b46fc761882e78c782' + + 'd2c36e716a770a7aefaf7f76cea872db7bffefdbc4c2f9e0' + + '39c19adac915e7a63dcb8c8c78c113f29a3e0bc10e100ce0', + qs: '6f0a2fb763eaeb8eb324d564f03d4a55fdcd709e5f1b65e9' + + '5702b0141182f9f945d71bc3e64a7dfdae7482a7dd5a4e58' + + 'bc38f78de2013f2c468a621f08536969d2c8d011bb3bc259' + + '2124692c91140a5472cad224acdacdeae5751dadfdf068b8' + + '77bfa7374694c6a7be159fc3d24ff9eeeecaf62580427ad8' + + '622d48c51a1c4b1701d768c79d8c819776e096d2694107a2' + + 'f3ec0c32224795b59d32894834039dacb369280afb221bc0' + + '90570a93cf409889b818bb30cccee98b2aa26dbba0f28499' + + '08e1a3cd43fa1f1fb71049e5c77c3724d74dc351d9989057' + + '37bbda3805bd6b1293da8774410fb66e3194e18cdb304dd9' + + 'a0b59b583dcbc9fc045ac9d56aea5cfc9f8a0b95da1e11b7' + + '574d1f976e45fe12294997fac66ca0b83fc056183549e850' + + 'a11413cc4abbe39a211e8c8cbf82f2a23266b3c10ab9e286' + + '07a1b6088909cddff856e1eb6b2cde8bdac53fa939827736' + + 'ca1b892f6c95899613442bd02dbdb747f02487718e2d3f22' + + 'f73734d29767ed8d0e346d0c4098b6fdcb4df7d0c4d29603' + + '5bffe80d6c65ae0a1b814150d349096baaf950f2caf298d2' + + 'b292a1d48cf82b10734fe8cedfa16914076dfe3e9b51337b' + + 'ed28ea1e6824bb717b641ca0e526e175d3e5ed7892aebab0' + + 'f207562cc938a821e2956107c09b6ce4049adddcd0b7505d' + + '49ae6c69a20122461102d465d93dc03db026be54c303613a' + + 'b8e5ce3fd4f65d0b6162ff740a0bf5469ffd442d8c509cd2' + + '3b40dab90f6776ca17fc0678774bd6eee1fa85ababa52ec1' + + 'a15031eb677c6c488661dddd8b83d6031fe294489ded5f08' + + '8ad1689a14baeae7e688afa3033899c81f58de39b392ca94' + + 'af6f15a46f19fa95c06f9493c8b96a9be25e78b9ea35013b' + + 'caa76de6303939299d07426a88a334278fc3d0d9fa71373e' + + 'be51d3c1076ab93a11d3d0d703366ff8cde4c11261d488e5' + + '60a2bdf3bfe2476032294800d6a4a39d306e65c6d7d8d66e' + + '5ec63eee94531e83a9bddc458a2b508285c0ee10b7bd94da' + + '2815a0c5bd5b2e15cbe66355e42f5af8955cdfc0b3a4996d' + + '288db1f4b32b15643b18193e378cb7491f3c3951cdd044b1' + + 'a519571bffac2da986f5f1d506c66530a55f70751e24fa8e' + + 'd83ac2347f4069fb561a5565e78c6f0207da24e889a93a96' + + '65f717d9fe8a2938a09ab5f81be7ccecf466c0397fc15a57' + + '469939793f302739765773c256a3ca55d0548afd117a7cae' + + '98ca7e0d749a130c7b743d376848e255f8fdbe4cb4480b63' + + 'cd2c015d1020cf095d175f3ca9dcdfbaf1b2a6e6468eee4c' + + 'c750f2132a77f376bd9782b9d0ff4da98621b898e251a263' + + '4301ba2214a8c430b2f7a79dbbfd6d7ff6e9b0c137b025ff' + + '587c0bf912f0b19d4fff96b1ecd2ca990c89b386055c60f2' + + '3b94214bd55096f17a7b2c0fa12b333235101cd6f28a128c' + + '782e8a72671adadebbd073ded30bd7f09fb693565dcf0bf3' + + '090c21d13e5b0989dd8956f18f17f4f69449a13549c9d80a' + + '77e5e61b5aeeee9528634100e7bc390672f0ded1ca53555b' + + 'abddbcf700b9da6192255bddf50a76b709fbed251dce4c7e' + + '1ca36b85d1e97c1bc9d38c887a5adf140f9eeef674c31422' + + 'e65f63cae719f8c1324e42fa5fd8500899ef5aa3f9856aa7' + + 'ce10c85600a040343204f36bfeab8cfa6e9deb8a2edd2a8e' + + '018d00c7c9fa3a251ad0f57183c37e6377797653f382ec7a' + + '2b0145e16d3c856bc3634b46d90d7198aff12aff88a30e34' + + 'e2bfaf62705f3382576a9d3eeb0829fca2387b5b654af46e' + + '5cf6316fb57d59e5ea6c369061ac64d99671b0e516529dd5' + + 'd9c48ea0503e55fee090d36c5ea8b5954f6fcc0060794e1c' + + 'b7bc24aa1e5c0142fd4ce6e8fd5aa92a7bf84317ea9e1642' + + 'b6995bac6705adf93cbce72433ed0871139970d640f67b78' + + 'e63a7a6d849db2567df69ac7d79f8c62664ac221df228289' + + 'd0a4f9ebd9acb4f87d49da64e51a619fd3f3baccbd9feb12' + + '5abe0cc2c8d17ed1d8546da2b6c641f4d3020a5f9b9f26ac' + + '16546c2d61385505612275ea344c2bbf1ce890023738f715' + + '5e9eba6a071678c8ebd009c328c3eb643679de86e69a9fa5' + + '67a9e146030ff03d546310a0a568c5ba0070e0da22f2cef8' + + '54714b04d399bbc8fd261f9e8efcd0e83bdbc3f5cfb2d024' + + '3e398478cc598e000124eb8858f9df8f52946c2a1ca5c400' + } +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/pummel/dh-group-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/pummel/dh-group-test.js new file mode 100644 index 0000000..37a259f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/pummel/dh-group-test.js @@ -0,0 +1,23 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../../').BN; +var fixtures = require('../fixtures'); + +describe('BN.js/Slow DH test', function () { + var groups = fixtures.dhGroups; + Object.keys(groups).forEach(function (name) { + it('should match public key for ' + name + ' group', function () { + var group = groups[name]; + + this.timeout(3600 * 1000); + + var base = new BN(2); + var mont = BN.red(new BN(group.prime, 16)); + var priv = new BN(group.priv, 16); + var multed = base.toRed(mont).redPow(priv).fromRed(); + var actual = new Buffer(multed.toArray()); + assert.equal(actual.toString('hex'), group.pub); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/red-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/red-test.js new file mode 100644 index 0000000..5f78b83 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/red-test.js @@ -0,0 +1,249 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Reduction context', function () { + function testMethod (name, fn) { + describe(name + ' method', function () { + it('should support add, iadd, sub, isub operations', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(123).toRed(m); + var b = new BN(231).toRed(m); + + assert.equal(a.redAdd(b).fromRed().toString(10), '97'); + assert.equal(a.redSub(b).fromRed().toString(10), '149'); + assert.equal(b.redSub(a).fromRed().toString(10), '108'); + + assert.equal(a.clone().redIAdd(b).fromRed().toString(10), '97'); + assert.equal(a.clone().redISub(b).fromRed().toString(10), '149'); + assert.equal(b.clone().redISub(a).fromRed().toString(10), '108'); + }); + + it('should support pow and mul operations', function () { + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p192); + var a = new BN(123); + var b = new BN(231); + var c = a.toRed(m).redMul(b.toRed(m)).fromRed(); + assert(c.cmp(a.mul(b).mod(p192)) === 0); + + assert.equal(a.toRed(m).redPow(new BN(3)).fromRed() + .cmp(a.sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(4)).fromRed() + .cmp(a.sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(8)).fromRed() + .cmp(a.sqr().sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(9)).fromRed() + .cmp(a.sqr().sqr().sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(17)).fromRed() + .cmp(a.sqr().sqr().sqr().sqr().mul(a)), 0); + assert.equal( + a.toRed(m).redPow(new BN('deadbeefabbadead', 16)).fromRed() + .toString(16), + '3aa0e7e304e320b68ef61592bcb00341866d6fa66e11a4d6'); + }); + + it('should sqrtm numbers', function () { + var p = new BN(263); + var m = fn(p); + var q = new BN(11).toRed(m); + + var qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + m = fn(p); + + q = new BN(13).toRed(m); + qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + // Tonelli-shanks + p = new BN(13); + m = fn(p); + q = new BN(10).toRed(m); + assert.equal(q.redSqrt().fromRed().toString(10), '7'); + }); + + it('should invm numbers', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(3).toRed(m); + var b = a.redInvm(); + assert.equal(a.redMul(b).fromRed().toString(16), '1'); + }); + + it('should invm numbers (regression)', function () { + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'e1d969b8192fbac73ea5b7921896d6a2263d4d4077bb8e5055361d1f7f8163f3', + 16); + + var m = fn(p); + a = a.toRed(m); + + assert.equal(a.redInvm().fromRed().negative, 0); + }); + + it('should imul numbers', function () { + var p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p); + + var a = new BN('deadbeefabbadead', 16); + var b = new BN('abbadeadbeefdead', 16); + var c = a.mul(b).mod(p); + + assert.equal(a.toRed(m).redIMul(b.toRed(m)).fromRed().toString(16), + c.toString(16)); + }); + + it('should pow(base, 0) == 1', function () { + var base = new BN(256).toRed(BN.red('k256')); + var exponent = new BN(0); + var result = base.redPow(exponent); + assert.equal(result.toString(), '1'); + }); + + it('should shl numbers', function () { + var base = new BN(256).toRed(BN.red('k256')); + var result = base.redShl(1); + assert.equal(result.toString(), '512'); + }); + + it('should reduce when converting to red', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(5).toRed(m); + + assert.doesNotThrow(function () { + var b = a.redISub(new BN(512).toRed(m)); + b.redISub(new BN(512).toRed(m)); + }); + }); + + it('redNeg and zero value', function () { + var a = new BN(0).toRed(BN.red('k256')).redNeg(); + assert.equal(a.isZero(), true); + }); + }); + } + + testMethod('Plain', BN.red); + testMethod('Montgomery', BN.mont); + + describe('Pseudo-Mersenne Primes', function () { + it('should reduce numbers mod k256', function () { + var p = BN._prime('k256'); + + assert.equal(p.ireduce(new BN(0xdead)).toString(16), 'dead'); + assert.equal(p.ireduce(new BN('deadbeef', 16)).toString(16), 'deadbeef'); + + var num = new BN('fedcba9876543210fedcba9876543210dead' + + 'fedcba9876543210fedcba9876543210dead', + 16); + var exp = num.mod(p.p).toString(16); + assert.equal(p.ireduce(num).toString(16), exp); + + var regr = new BN('f7e46df64c1815962bf7bc9c56128798' + + '3f4fcef9cb1979573163b477eab93959' + + '335dfb29ef07a4d835d22aa3b6797760' + + '70a8b8f59ba73d56d01a79af9', + 16); + exp = regr.mod(p.p).toString(16); + + assert.equal(p.ireduce(regr).toString(16), exp); + }); + + it('should not fail to invm number mod k256', function () { + var regr2 = new BN( + '6c150c4aa9a8cf1934485d40674d4a7cd494675537bda36d49405c5d2c6f496f', 16); + regr2 = regr2.toRed(BN.red('k256')); + assert.equal(regr2.redInvm().redMul(regr2).fromRed().cmpn(1), 0); + }); + + it('should correctly square the number', function () { + var p = BN._prime('k256').p; + var red = BN.red('k256'); + + var n = new BN('9cd8cb48c3281596139f147c1364a3ed' + + 'e88d3f310fdb0eb98c924e599ca1b3c9', + 16); + var expected = n.sqr().mod(p); + var actual = n.toRed(red).redSqr().fromRed(); + + assert.equal(actual.toString(16), expected.toString(16)); + }); + + it('redISqr should return right result', function () { + var n = new BN('30f28939', 16); + var actual = n.toRed(BN.red('k256')).redISqr().fromRed(); + assert.equal(actual.toString(16), '95bd93d19520eb1'); + }); + }); + + it('should avoid 4.1.0 regresion', function () { + function bits2int (obits, q) { + var bits = new BN(obits); + var shift = (obits.length << 3) - q.bitLength(); + if (shift > 0) { + bits.ishrn(shift); + } + return bits; + } + var t = new Buffer('aff1651e4cd6036d57aa8b2a05ccf1a9d5a40166340ecbbdc55' + + 'be10b568aa0aa3d05ce9a2fcec9df8ed018e29683c6051cb83e' + + '46ce31ba4edb045356a8d0d80b', 'hex'); + var g = new BN('5c7ff6b06f8f143fe8288433493e4769c4d988ace5be25a0e24809670' + + '716c613d7b0cee6932f8faa7c44d2cb24523da53fbe4f6ec3595892d1' + + 'aa58c4328a06c46a15662e7eaa703a1decf8bbb2d05dbe2eb956c142a' + + '338661d10461c0d135472085057f3494309ffa73c611f78b32adbb574' + + '0c361c9f35be90997db2014e2ef5aa61782f52abeb8bd6432c4dd097b' + + 'c5423b285dafb60dc364e8161f4a2a35aca3a10b1c4d203cc76a470a3' + + '3afdcbdd92959859abd8b56e1725252d78eac66e71ba9ae3f1dd24871' + + '99874393cd4d832186800654760e1e34c09e4d155179f9ec0dc4473f9' + + '96bdce6eed1cabed8b6f116f7ad9cf505df0f998e34ab27514b0ffe7', + 16); + var p = new BN('9db6fb5951b66bb6fe1e140f1d2ce5502374161fd6538df1648218642' + + 'f0b5c48c8f7a41aadfa187324b87674fa1822b00f1ecf8136943d7c55' + + '757264e5a1a44ffe012e9936e00c1d3e9310b01c7d179805d3058b2a9' + + 'f4bb6f9716bfe6117c6b5b3cc4d9be341104ad4a80ad6c94e005f4b99' + + '3e14f091eb51743bf33050c38de235567e1b34c3d6a5c0ceaa1a0f368' + + '213c3d19843d0b4b09dcb9fc72d39c8de41f1bf14d4bb4563ca283716' + + '21cad3324b6a2d392145bebfac748805236f5ca2fe92b871cd8f9c36d' + + '3292b5509ca8caa77a2adfc7bfd77dda6f71125a7456fea153e433256' + + 'a2261c6a06ed3693797e7995fad5aabbcfbe3eda2741e375404ae25b', + 16); + var q = new BN('f2c3119374ce76c9356990b465374a17f23f9ed35089bd969f61c6dde' + + '9998c1f', 16); + var k = bits2int(t, q); + var expectedR = '89ec4bb1400eccff8e7d9aa515cd1de7803f2daff09693ee7fd1353e' + + '90a68307'; + var r = g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); + assert.equal(r.toString(16), expectedR); + }); + + it('K256.split for 512 bits number should return equal numbers', function () { + var red = BN.red('k256'); + var input = new BN(1).iushln(512).subn(1); + assert.equal(input.bitLength(), 512); + var output = new BN(0); + red.prime.split(input, output); + assert.equal(input.cmp(output), 0); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/utils-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/utils-test.js new file mode 100644 index 0000000..f51ce4b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/test/utils-test.js @@ -0,0 +1,345 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Utils', function () { + describe('.toString()', function () { + describe('binary padding', function () { + it('should have a length of 256', function () { + var a = new BN(0); + + assert.equal(a.toString(2, 256).length, 256); + }); + }); + describe('hex padding', function () { + it('should have length of 8 from leading 15', function () { + var a = new BN('ffb9602', 16); + + assert.equal(a.toString('hex', 2).length, 8); + }); + + it('should have length of 8 from leading zero', function () { + var a = new BN('fb9604', 16); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 8 from leading zeros', function () { + var a = new BN(0); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 64 from leading 15', function () { + var a = new BN( + 'ffb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 2).length, 64); + }); + + it('should have length of 64 from leading zero', function () { + var a = new BN( + 'fb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 64).length, 64); + }); + }); + }); + + describe('.isNeg()', function () { + it('should return true for negative numbers', function () { + assert.equal(new BN(-1).isNeg(), true); + assert.equal(new BN(1).isNeg(), false); + assert.equal(new BN(0).isNeg(), false); + assert.equal(new BN('-0', 10).isNeg(), false); + }); + }); + + describe('.isOdd()', function () { + it('should return true for odd numbers', function () { + assert.equal(new BN(0).isOdd(), false); + assert.equal(new BN(1).isOdd(), true); + assert.equal(new BN(2).isOdd(), false); + assert.equal(new BN('-0', 10).isOdd(), false); + assert.equal(new BN('-1', 10).isOdd(), true); + assert.equal(new BN('-2', 10).isOdd(), false); + }); + }); + + describe('.isEven()', function () { + it('should return true for even numbers', function () { + assert.equal(new BN(0).isEven(), true); + assert.equal(new BN(1).isEven(), false); + assert.equal(new BN(2).isEven(), true); + assert.equal(new BN('-0', 10).isEven(), true); + assert.equal(new BN('-1', 10).isEven(), false); + assert.equal(new BN('-2', 10).isEven(), true); + }); + }); + + describe('.isZero()', function () { + it('should return true for zero', function () { + assert.equal(new BN(0).isZero(), true); + assert.equal(new BN(1).isZero(), false); + assert.equal(new BN(0xffffffff).isZero(), false); + }); + }); + + describe('.bitLength()', function () { + it('should return proper bitLength', function () { + assert.equal(new BN(0).bitLength(), 0); + assert.equal(new BN(0x1).bitLength(), 1); + assert.equal(new BN(0x2).bitLength(), 2); + assert.equal(new BN(0x3).bitLength(), 2); + assert.equal(new BN(0x4).bitLength(), 3); + assert.equal(new BN(0x8).bitLength(), 4); + assert.equal(new BN(0x10).bitLength(), 5); + assert.equal(new BN(0x100).bitLength(), 9); + assert.equal(new BN(0x123456).bitLength(), 21); + assert.equal(new BN('123456789', 16).bitLength(), 33); + assert.equal(new BN('8023456789', 16).bitLength(), 40); + }); + }); + + describe('.byteLength()', function () { + it('should return proper byteLength', function () { + assert.equal(new BN(0).byteLength(), 0); + assert.equal(new BN(0x1).byteLength(), 1); + assert.equal(new BN(0x2).byteLength(), 1); + assert.equal(new BN(0x3).byteLength(), 1); + assert.equal(new BN(0x4).byteLength(), 1); + assert.equal(new BN(0x8).byteLength(), 1); + assert.equal(new BN(0x10).byteLength(), 1); + assert.equal(new BN(0x100).byteLength(), 2); + assert.equal(new BN(0x123456).byteLength(), 3); + assert.equal(new BN('123456789', 16).byteLength(), 5); + assert.equal(new BN('8023456789', 16).byteLength(), 5); + }); + }); + + describe('.toArray()', function () { + it('should return [ 0 ] for `0`', function () { + var n = new BN(0); + assert.deepEqual(n.toArray('be'), [ 0 ]); + assert.deepEqual(n.toArray('le'), [ 0 ]); + }); + + it('should zero pad to desired lengths', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toArray('be', 5), [ 0x00, 0x00, 0x12, 0x34, 0x56 ]); + assert.deepEqual(n.toArray('le', 5), [ 0x56, 0x34, 0x12, 0x00, 0x00 ]); + }); + + it('should throw when naturally larger than desired length', function () { + var n = new BN(0x123456); + assert.throws(function () { + n.toArray('be', 2); + }); + }); + }); + + describe('.toBuffer', function () { + it('should return proper Buffer', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toBuffer('be', 5).toString('hex'), '0000123456'); + assert.deepEqual(n.toBuffer('le', 5).toString('hex'), '5634120000'); + }); + }); + + describe('.toNumber()', function () { + it('should return proper Number if below the limit', function () { + assert.deepEqual(new BN(0x123456).toNumber(), 0x123456); + assert.deepEqual(new BN(0x3ffffff).toNumber(), 0x3ffffff); + assert.deepEqual(new BN(0x4000000).toNumber(), 0x4000000); + assert.deepEqual(new BN(0x10000000000000).toNumber(), 0x10000000000000); + assert.deepEqual(new BN(0x10040004004000).toNumber(), 0x10040004004000); + assert.deepEqual(new BN(-0x123456).toNumber(), -0x123456); + assert.deepEqual(new BN(-0x3ffffff).toNumber(), -0x3ffffff); + assert.deepEqual(new BN(-0x4000000).toNumber(), -0x4000000); + assert.deepEqual(new BN(-0x10000000000000).toNumber(), -0x10000000000000); + assert.deepEqual(new BN(-0x10040004004000).toNumber(), -0x10040004004000); + }); + + it('should throw when number exceeds 53 bits', function () { + var n = new BN(1).iushln(54); + assert.throws(function () { + n.toNumber(); + }); + }); + }); + + describe('.zeroBits()', function () { + it('should return proper zeroBits', function () { + assert.equal(new BN(0).zeroBits(), 0); + assert.equal(new BN(0x1).zeroBits(), 0); + assert.equal(new BN(0x2).zeroBits(), 1); + assert.equal(new BN(0x3).zeroBits(), 0); + assert.equal(new BN(0x4).zeroBits(), 2); + assert.equal(new BN(0x8).zeroBits(), 3); + assert.equal(new BN(0x10).zeroBits(), 4); + assert.equal(new BN(0x100).zeroBits(), 8); + assert.equal(new BN(0x1000000).zeroBits(), 24); + assert.equal(new BN(0x123456).zeroBits(), 1); + }); + }); + + describe('.toJSON', function () { + it('should return hex string', function () { + assert.equal(new BN(0x123).toJSON(), '123'); + }); + }); + + describe('.cmpn', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmpn(42), 0); + assert.equal(new BN(42).cmpn(43), -1); + assert.equal(new BN(42).cmpn(41), 1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffe), 0); + assert.equal(new BN(0x3fffffe).cmpn(0x3ffffff), -1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffd), 1); + assert.throws(function () { + new BN(0x3fffffe).cmpn(0x4000000); + }); + assert.equal(new BN(42).cmpn(-42), 1); + assert.equal(new BN(-42).cmpn(42), -1); + assert.equal(new BN(-42).cmpn(-42), 0); + assert.equal(1 / new BN(-42).cmpn(-42), Infinity); + }); + }); + + describe('.cmp', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmp(new BN(42)), 0); + assert.equal(new BN(42).cmp(new BN(43)), -1); + assert.equal(new BN(42).cmp(new BN(41)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffe)), 0); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3ffffff)), -1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffd)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x4000000)), -1); + assert.equal(new BN(42).cmp(new BN(-42)), 1); + assert.equal(new BN(-42).cmp(new BN(42)), -1); + assert.equal(new BN(-42).cmp(new BN(-42)), 0); + assert.equal(1 / new BN(-42).cmp(new BN(-42)), Infinity); + }); + }); + + describe('comparison shorthands', function () { + it('.gtn greater than', function () { + assert.equal(new BN(3).gtn(2), true); + assert.equal(new BN(3).gtn(3), false); + assert.equal(new BN(3).gtn(4), false); + }); + it('.gt greater than', function () { + assert.equal(new BN(3).gt(new BN(2)), true); + assert.equal(new BN(3).gt(new BN(3)), false); + assert.equal(new BN(3).gt(new BN(4)), false); + }); + it('.gten greater than or equal', function () { + assert.equal(new BN(3).gten(3), true); + assert.equal(new BN(3).gten(2), true); + assert.equal(new BN(3).gten(4), false); + }); + it('.gte greater than or equal', function () { + assert.equal(new BN(3).gte(new BN(3)), true); + assert.equal(new BN(3).gte(new BN(2)), true); + assert.equal(new BN(3).gte(new BN(4)), false); + }); + it('.ltn less than', function () { + assert.equal(new BN(2).ltn(3), true); + assert.equal(new BN(2).ltn(2), false); + assert.equal(new BN(2).ltn(1), false); + }); + it('.lt less than', function () { + assert.equal(new BN(2).lt(new BN(3)), true); + assert.equal(new BN(2).lt(new BN(2)), false); + assert.equal(new BN(2).lt(new BN(1)), false); + }); + it('.lten less than or equal', function () { + assert.equal(new BN(3).lten(3), true); + assert.equal(new BN(3).lten(2), false); + assert.equal(new BN(3).lten(4), true); + }); + it('.lte less than or equal', function () { + assert.equal(new BN(3).lte(new BN(3)), true); + assert.equal(new BN(3).lte(new BN(2)), false); + assert.equal(new BN(3).lte(new BN(4)), true); + }); + it('.eqn equal', function () { + assert.equal(new BN(3).eqn(3), true); + assert.equal(new BN(3).eqn(2), false); + assert.equal(new BN(3).eqn(4), false); + }); + it('.eq equal', function () { + assert.equal(new BN(3).eq(new BN(3)), true); + assert.equal(new BN(3).eq(new BN(2)), false); + assert.equal(new BN(3).eq(new BN(4)), false); + }); + }); + + describe('.fromTwos', function () { + it('should convert from two\'s complement to negative number', function () { + assert.equal(new BN('00000000', 16).fromTwos(32).toNumber(), 0); + assert.equal(new BN('00000001', 16).fromTwos(32).toNumber(), 1); + assert.equal(new BN('7fffffff', 16).fromTwos(32).toNumber(), 2147483647); + assert.equal(new BN('80000000', 16).fromTwos(32).toNumber(), -2147483648); + assert.equal(new BN('f0000000', 16).fromTwos(32).toNumber(), -268435456); + assert.equal(new BN('f1234567', 16).fromTwos(32).toNumber(), -249346713); + assert.equal(new BN('ffffffff', 16).fromTwos(32).toNumber(), -1); + assert.equal(new BN('fffffffe', 16).fromTwos(32).toNumber(), -2); + assert.equal(new BN('fffffffffffffffffffffffffffffffe', 16) + .fromTwos(128).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'fffffffffffffffffffffffffffffffe', 16).fromTwos(256).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toNumber(), -1); + assert.equal(new BN('7fffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toString(10), + new BN('5789604461865809771178549250434395392663499' + + '2332820282019728792003956564819967', 10).toString(10)); + assert.equal(new BN('80000000000000000000000000000000' + + '00000000000000000000000000000000', 16).fromTwos(256).toString(10), + new BN('-578960446186580977117854925043439539266349' + + '92332820282019728792003956564819968', 10).toString(10)); + }); + }); + + describe('.toTwos', function () { + it('should convert from negative number to two\'s complement', function () { + assert.equal(new BN(0).toTwos(32).toString(16), '0'); + assert.equal(new BN(1).toTwos(32).toString(16), '1'); + assert.equal(new BN(2147483647).toTwos(32).toString(16), '7fffffff'); + assert.equal(new BN('-2147483648', 10).toTwos(32).toString(16), '80000000'); + assert.equal(new BN('-268435456', 10).toTwos(32).toString(16), 'f0000000'); + assert.equal(new BN('-249346713', 10).toTwos(32).toString(16), 'f1234567'); + assert.equal(new BN('-1', 10).toTwos(32).toString(16), 'ffffffff'); + assert.equal(new BN('-2', 10).toTwos(32).toString(16), 'fffffffe'); + assert.equal(new BN('-2', 10).toTwos(128).toString(16), + 'fffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-2', 10).toTwos(256).toString(16), + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-1', 10).toTwos(256).toString(16), + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('5789604461865809771178549250434395392663' + + '4992332820282019728792003956564819967', 10).toTwos(256).toString(16), + '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('-578960446186580977117854925043439539266' + + '34992332820282019728792003956564819968', 10).toTwos(256).toString(16), + '8000000000000000000000000000000000000000000000000000000000000000'); + }); + }); + + describe('.isBN', function () { + it('should return true for BN', function () { + assert.equal(BN.isBN(new BN()), true); + }); + + it('should return false for everything else', function () { + assert.equal(BN.isBN(1), false); + assert.equal(BN.isBN([]), false); + assert.equal(BN.isBN({}), false); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/util/genCombMulTo.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/util/genCombMulTo.js new file mode 100644 index 0000000..8b456c7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/util/genCombMulTo.js @@ -0,0 +1,65 @@ +'use strict'; + +// NOTE: This could be potentionally used to generate loop-less multiplications +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('var w' + k + ' = c;'); + src.push('c = 0;'); + for (var j = minJ; j <= maxJ; j++) { + i = k - j; + + src.push('lo = Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid = Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;'); + src.push('hi = Math.imul(ah' + i + ', bh' + j + ');'); + + src.push('w' + k + ' = (w' + k + ' + lo) | 0;'); + src.push('w' + k + ' = (w' + k + ' + ((mid & 0x1fff) << 13)) | 0;'); + src.push('c = (c + hi) | 0;'); + src.push('c = (c + (mid >>> 13)) | 0;'); + src.push('c = (c + (w' + k + ' >>> 26)) | 0;'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/util/genCombMulTo10.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/util/genCombMulTo10.js new file mode 100644 index 0000000..4214ffd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/bn.js/util/genCombMulTo10.js @@ -0,0 +1,64 @@ +'use strict'; + +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('lo = Math.imul(al' + (k - minJ) + ', bl' + minJ + ');'); + src.push('mid = Math.imul(al' + (k - minJ) + ', bh' + minJ + ');'); + src.push('mid += Math.imul(ah' + (k - minJ) + ', bl' + minJ + ');'); + src.push('hi = Math.imul(ah' + (k - minJ) + ', bh' + minJ + ');'); + + for (var j = minJ + 1; j <= maxJ; j++) { + i = k - j; + + src.push('lo += Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid += Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid += Math.imul(ah' + i + ', bl' + j + ');'); + src.push('hi += Math.imul(ah' + i + ', bh' + j + ');'); + } + + src.push('var w' + k + ' = c + lo + ((mid & 0x1fff) << 13);'); + src.push('c = hi + (mid >>> 13) + (w' + k + ' >>> 26);'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/.npmignore new file mode 100644 index 0000000..1ca9571 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/README.md new file mode 100644 index 0000000..e9d76f6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/README.md @@ -0,0 +1,26 @@ +# Miller-Rabin + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/bin/miller-rabin b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/bin/miller-rabin new file mode 100644 index 0000000..2e18dfd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/bin/miller-rabin @@ -0,0 +1,29 @@ +#!/usr/bin/env node +var bn = require('bn.js'); +var fs = require('fs'); +var mr = require('../').create(); + +var num = ''; +if (process.argv[2]) { + num += fs.readFileSync(process.argv[2]); + start(num); +} else { + process.stdin.on('data', function(chunk) { + num += chunk.toString().replace(/[^0-9a-f]/gi, ''); + }); + process.stdin.once('end', function() { + start(num); + }); +} + +function start(text) { + var num = new bn(text, 16); + + var divisor = mr.getDivisor(num); + if (!divisor) + process.exit(1); + if (divisor.cmpn(1) === 0) + process.exit(0); + + console.log(divisor.toString(16)); +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/lib/mr.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/lib/mr.js new file mode 100644 index 0000000..a9e935b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/lib/mr.js @@ -0,0 +1,113 @@ +var bn = require('bn.js'); +var brorand = require('brorand'); + +function MillerRabin(rand) { + this.rand = rand || new brorand.Rand(); +} +module.exports = MillerRabin; + +MillerRabin.create = function create(rand) { + return new MillerRabin(rand); +}; + +MillerRabin.prototype._rand = function _rand(n) { + var len = n.bitLength(); + var buf = this.rand.generate(Math.ceil(len / 8)); + + // Set low bits + buf[0] |= 3; + + // Mask high bits + var mask = len & 0x7; + if (mask !== 0) + buf[buf.length - 1] >>= 7 - mask; + + return new bn(buf); +} + +MillerRabin.prototype.test = function test(n, k, cb) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + var n2 = n1.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + var prime = true; + for (; k > 0; k--) { + var a = this._rand(n2); + if (cb) + cb(a); + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return false; + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) + return false; + } + + return prime; +}; + +MillerRabin.prototype.getDivisor = function getDivisor(n, k) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + var n2 = n1.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + for (; k > 0; k--) { + var a = this._rand(n2); + + var g = n.gcd(a); + if (g.cmpn(1) !== 0) + return g; + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return x.fromRed().subn(1).gcd(n); + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) { + x = x.redSqr(); + return x.fromRed().subn(1).gcd(n); + } + } + + return false; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/.npmignore new file mode 100644 index 0000000..1ca9571 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/README.md new file mode 100644 index 0000000..f80437d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/README.md @@ -0,0 +1,26 @@ +# Brorand + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2014. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/index.js new file mode 100644 index 0000000..436f040 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/index.js @@ -0,0 +1,57 @@ +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +if (typeof window === 'object') { + if (window.crypto && window.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.crypto.getRandomValues(arr); + return arr; + }; + } else if (window.msCrypto && window.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + window.msCrypto.getRandomValues(arr); + return arr; + }; + } else { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker + try { + var crypto = require('cry' + 'pto'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + // Emulate crypto API using randy + Rand.prototype._rand = function _rand(n) { + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; + }; + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/package.json new file mode 100644 index 0000000..52d4305 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/package.json @@ -0,0 +1,37 @@ +{ + "name": "brorand", + "version": "1.0.5", + "description": "Random number generator for browsers and node.js", + "main": "index.js", + "scripts": { + "test": "mocha --reporter=spec test/**/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/brorand.git" + }, + "keywords": [ + "Random", + "RNG", + "browser", + "crypto" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/brorand/issues" + }, + "homepage": "https://github.com/indutny/brorand", + "devDependencies": { + "mocha": "^2.0.1" + }, + "readme": "# Brorand\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "brorand@1.0.5", + "_shasum": "07b54ca30286abd1718a0e2a830803efdc9bfa04", + "_resolved": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz", + "_from": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/test/api-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/test/api-test.js new file mode 100644 index 0000000..b6c876d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/node_modules/brorand/test/api-test.js @@ -0,0 +1,8 @@ +var brorand = require('../'); +var assert = require('assert'); + +describe('Brorand', function() { + it('should generate random numbers', function() { + assert.equal(brorand(100).length, 100); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/package.json new file mode 100644 index 0000000..c85c2e7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/package.json @@ -0,0 +1,43 @@ +{ + "name": "miller-rabin", + "version": "4.0.0", + "description": "Miller Rabin algorithm for primality test", + "main": "lib/mr.js", + "bin": { + "miller-rabin": "bin/miller-rabin" + }, + "scripts": { + "test": "mocha --reporter=spec test/**/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/miller-rabin.git" + }, + "keywords": [ + "prime", + "miller-rabin", + "bignumber" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/miller-rabin/issues" + }, + "homepage": "https://github.com/indutny/miller-rabin", + "devDependencies": { + "mocha": "^2.0.1" + }, + "dependencies": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + }, + "readme": "# Miller-Rabin\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "miller-rabin@4.0.0", + "_shasum": "4a62fb1d42933c05583982f4c716f6fb9e6c6d3d", + "_resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.0.tgz", + "_from": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/test/api-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/test/api-test.js new file mode 100644 index 0000000..dee094d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/node_modules/miller-rabin/test/api-test.js @@ -0,0 +1,18 @@ +var assert = require('assert'); +var mr = require('../').create(); +var bn = require('bn.js'); + +describe('Miller-Rabin', function() { + it('should test number for primality', function() { + assert(!mr.test(new bn(221))); + assert(mr.test(new bn(257))); + + var p = new bn('dba8191813fe8f51eaae1de70213aafede8f323f95f32cff' + + '8b64ebada275cfb18a446a0150e5fdaee246244c5f002ce0' + + 'aca97584be1745f2dd1eea2849c52aac8c4b5fb78a1c4da7' + + '052774338d3310a6e020c46168cb1f94014e9312511cc4fb' + + '79d695bb732449f0e015745b86bfa371dc6ca7386e9c7309' + + '5549c2e4b8002873', 16); + assert(mr.test(p)); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/package.json new file mode 100644 index 0000000..d73c135 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/package.json @@ -0,0 +1,43 @@ +{ + "name": "diffie-hellman", + "version": "5.0.2", + "description": "pure js diffie-hellman", + "main": "index.js", + "browser": "browser.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/diffie-hellman.git" + }, + "keywords": [ + "diffie", + "hellman", + "diffiehellman", + "dh" + ], + "author": { + "name": "Calvin Metcalf" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/diffie-hellman/issues" + }, + "homepage": "https://github.com/crypto-browserify/diffie-hellman", + "dependencies": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + }, + "devDependencies": { + "tap-spec": "^1.0.1", + "tape": "^3.0.1" + }, + "readme": "diffie hellman [![Build Status](https://travis-ci.org/crypto-browserify/diffie-hellman.svg)](https://travis-ci.org/crypto-browserify/diffie-hellman)\n====\n\npure js diffie-hellman, same api as node, most hard parts thanks to [bn.js](https://www.npmjs.org/package/bn.js) by [@indutny](https://github.com/indutny). In node just returns an object with `crypto.createDiffieHellman` and `crypto.getDiffieHellman` in the browser returns a shim. To require the pure JavaScript one in node `require('diffie-hellman/browser');`;", + "readmeFilename": "readme.md", + "_id": "diffie-hellman@5.0.2", + "_shasum": "b5835739270cfe26acf632099fded2a07f209e5e", + "_resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.2.tgz", + "_from": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/readme.md new file mode 100644 index 0000000..afba499 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/diffie-hellman/readme.md @@ -0,0 +1,4 @@ +diffie hellman [![Build Status](https://travis-ci.org/crypto-browserify/diffie-hellman.svg)](https://travis-ci.org/crypto-browserify/diffie-hellman) +==== + +pure js diffie-hellman, same api as node, most hard parts thanks to [bn.js](https://www.npmjs.org/package/bn.js) by [@indutny](https://github.com/indutny). In node just returns an object with `crypto.createDiffieHellman` and `crypto.getDiffieHellman` in the browser returns a shim. To require the pure JavaScript one in node `require('diffie-hellman/browser');`; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/inherits.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/inherits_browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/package.json new file mode 100644 index 0000000..bad1183 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/.npmignore new file mode 100644 index 0000000..c2757b0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/.npmignore @@ -0,0 +1,28 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Deployed apps should consider commenting this line out: +# see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git +node_modules + +# build artifact +test/bundle.js \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/.travis.yml new file mode 100644 index 0000000..73261dc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/.travis.yml @@ -0,0 +1,13 @@ +language: node_js +before_install: + - "npm install npm -g" +node_js: + - "0.10" + - "0.11" + - "0.12" + - "iojs" +env: + - TEST_SUITE=test + - TEST_SUITE=coveralls + - TEST_SUITE=standard +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/LICENSE new file mode 100644 index 0000000..a115b52 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Daniel Cousens + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/README.md new file mode 100644 index 0000000..bb164f1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/README.md @@ -0,0 +1,24 @@ +# pbkdf2 + +[![build status](https://secure.travis-ci.org/crypto-browserify/pbkdf2.png)](http://travis-ci.org/crypto-browserify/pbkdf2) +[![Coverage Status](https://img.shields.io/coveralls/crypto-browserify/pbkdf2.svg)](https://coveralls.io/r/crypto-browserify/pbkdf2) +[![Version](http://img.shields.io/npm/v/pbkdf2.svg)](https://www.npmjs.org/package/pbkdf2) + +This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from `crypto.getHashes()` + + +## Usage + +``` +var pbkd2f = require('pbkd2f') +var derivedKey = pbkd2f.pbkdf2Sync('password', 'salt', 1, 32, 'sha512') + +... +``` + + +## Credits + +This module is a derivative of https://github.com/cryptocoinjs/pbkdf2-sha256/, so thanks to [JP Richardson](https://github.com/cryptocoinjs/pbkdf2-sha256/) for laying the ground work. + +Thank you to [FangDun Cai](https://github.com/fundon) for donating the package name on npm, if you're looking for his previous module it is located at [fundon/pbkdf2](https://github.com/fundon/pbkdf2). \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/async-shim.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/async-shim.js new file mode 100644 index 0000000..d12a4a4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/async-shim.js @@ -0,0 +1,19 @@ +var compat = require('./browser') + +process.on('message', function (m) { + try { + var result = compat.pbkdf2Sync(new Buffer(m.password, 'hex'), new Buffer(m.salt, 'hex'), m.iterations, m.keylen, m.digest) + + process.send({ + data: result.toString('hex'), + type: 'success' + }) + } catch (e) { + process.send({ + data: e && e.message, + type: 'fail' + }) + } finally { + process.exit() + } +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/browser.js new file mode 100644 index 0000000..3237450 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/browser.js @@ -0,0 +1,80 @@ +var createHmac = require('create-hmac') +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs + +exports.pbkdf2 = pbkdf2 +function pbkdf2 (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + + if (typeof callback !== 'function') { + throw new Error('No callback provided to pbkdf2') + } + + var result = pbkdf2Sync(password, salt, iterations, keylen, digest) + setTimeout(function () { + callback(undefined, result) + }) +} + +exports.pbkdf2Sync = pbkdf2Sync +function pbkdf2Sync (password, salt, iterations, keylen, digest) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC) { + throw new TypeError('Bad key length') + } + + digest = digest || 'sha1' + + if (!Buffer.isBuffer(password)) password = new Buffer(password, 'binary') + if (!Buffer.isBuffer(salt)) salt = new Buffer(salt, 'binary') + + var hLen + var l = 1 + var DK = new Buffer(keylen) + var block1 = new Buffer(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + var r + var T + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + var U = createHmac(digest, password).update(block1).digest() + + if (!hLen) { + hLen = U.length + T = new Buffer(hLen) + l = Math.ceil(keylen / hLen) + r = keylen - (l - 1) * hLen + } + + U.copy(T, 0, 0, hLen) + + for (var j = 1; j < iterations; j++) { + U = createHmac(digest, password).update(U).digest() + + for (var k = 0; k < hLen; k++) { + T[k] ^= U[k] + } + } + + var destPos = (i - 1) * hLen + var len = (i === l ? r : hLen) + T.copy(DK, destPos, 0, len) + } + + return DK +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/index.js new file mode 100644 index 0000000..ad86119 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/index.js @@ -0,0 +1,92 @@ +var compat = require('./browser') +var crypto = require('crypto') +var fork = require('child_process').fork +var path = require('path') + +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs + +function asyncPBKDF2 (password, salt, iterations, keylen, digest, callback) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC) { + throw new TypeError('Bad key length') + } + + if (typeof password === 'string') { + password = new Buffer(password, 'binary') + } + + if (typeof salt === 'string') { + salt = new Buffer(salt, 'binary') + } + + var child = fork(path.resolve(__dirname, 'async-shim.js')) + + child.on('message', function (result) { + if (result.type === 'success') { + callback(null, new Buffer(result.data, 'hex')) + } else if (result.type === 'fail') { + callback(new TypeError(result.data)) + } + }) + + child.send({ + password: password.toString('hex'), + salt: salt.toString('hex'), + iterations: iterations, + keylen: keylen, + digest: digest + }) +} + +exports.pbkdf2Sync = function pbkdf2Sync (password, salt, iterations, keylen, digest) { + digest = digest || 'sha1' + + if (isNode10()) { + if (digest === 'sha1') { + return crypto.pbkdf2Sync(password, salt, iterations, keylen) + } else { + return compat.pbkdf2Sync(password, salt, iterations, keylen, digest) + } + } else { + return crypto.pbkdf2Sync(password, salt, iterations, keylen, digest) + } +} + +exports.pbkdf2 = function pbkdf2 (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = 'sha1' + } + + if (isNode10()) { + if (digest === 'sha1') { + return crypto.pbkdf2(password, salt, iterations, keylen, callback) + } else { + return asyncPBKDF2(password, salt, iterations, keylen, digest, callback) + } + } else { + return crypto.pbkdf2(password, salt, iterations, keylen, digest, callback) + } +} + +var sha1 = '0c60c80f961f0e71f3a9b524af6012062fe037a6e0f0eb94fe8fc46bdc637164' +var isNode10Result + +function isNode10 () { + if (typeof isNode10Result === 'undefined') { + isNode10Result = crypto.pbkdf2Sync('password', 'salt', 1, 32, 'sha256').toString('hex') === sha1 + } + + return isNode10Result +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/package.json new file mode 100644 index 0000000..ee22ae0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/package.json @@ -0,0 +1,53 @@ +{ + "name": "pbkdf2", + "version": "3.0.4", + "description": "This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from crypto.getHashes()", + "main": "./index.js", + "browser": "./browser.js", + "keywords": [ + "pbkdf2", + "kdf", + "salt", + "hash" + ], + "scripts": { + "coverage": "istanbul cover _mocha -- -t 20000 test/index.js", + "coveralls": "npm run coverage && coveralls < coverage/lcov.info", + "standard": "standard", + "test": "mocha --reporter list -t 20000 test/index.js", + "bundle-test": "browserify test/index.js > test/bundle.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/pbkdf2.git" + }, + "author": { + "name": "Daniel Cousens" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/pbkdf2/issues" + }, + "homepage": "https://github.com/crypto-browserify/pbkdf2", + "devDependencies": { + "browserify": "^8.1.1", + "coveralls": "^2.11.2", + "istanbul": "^0.3.5", + "mocha": "^2.1.0", + "standard": "^3.0.0" + }, + "dependencies": { + "create-hmac": "^1.1.2" + }, + "standard": { + "ignore": [ + "test/**" + ] + }, + "readme": "# pbkdf2\n\n[![build status](https://secure.travis-ci.org/crypto-browserify/pbkdf2.png)](http://travis-ci.org/crypto-browserify/pbkdf2)\n[![Coverage Status](https://img.shields.io/coveralls/crypto-browserify/pbkdf2.svg)](https://coveralls.io/r/crypto-browserify/pbkdf2)\n[![Version](http://img.shields.io/npm/v/pbkdf2.svg)](https://www.npmjs.org/package/pbkdf2)\n\nThis library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from `crypto.getHashes()`\n\n\n## Usage\n\n```\nvar pbkd2f = require('pbkd2f')\nvar derivedKey = pbkd2f.pbkdf2Sync('password', 'salt', 1, 32, 'sha512')\n\n...\n```\n\n\n## Credits\n\nThis module is a derivative of https://github.com/cryptocoinjs/pbkdf2-sha256/, so thanks to [JP Richardson](https://github.com/cryptocoinjs/pbkdf2-sha256/) for laying the ground work.\n\nThank you to [FangDun Cai](https://github.com/fundon) for donating the package name on npm, if you're looking for his previous module it is located at [fundon/pbkdf2](https://github.com/fundon/pbkdf2).", + "readmeFilename": "README.md", + "_id": "pbkdf2@3.0.4", + "_shasum": "12c8bfaf920543786a85150b03f68d5f1aa982fc", + "_resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.4.tgz", + "_from": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.4.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/fixtures.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/fixtures.json new file mode 100644 index 0000000..410bb75 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/fixtures.json @@ -0,0 +1,171 @@ +{ + "valid": [ + { + "key": "password", + "salt": "salt", + "iterations": 1, + "dkLen": 32, + "results": { + "sha1": "0c60c80f961f0e71f3a9b524af6012062fe037a6e0f0eb94fe8fc46bdc637164", + "sha256": "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b", + "sha512": "867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5d513554e1c8cf252", + "sha224": "3c198cbdb9464b7857966bd05b7bc92bc1cc4e6e63155d4e490557fd85989497", + "sha384": "c0e14f06e49e32d73f9f52ddf1d0c5c7191609233631dadd76a567db42b78676" + } + }, + { + "key": "password", + "salt": "salt", + "iterations": 2, + "dkLen": 32, + "results": { + "sha1": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957cae93136266537a8d7bf4b76", + "sha256": "ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43", + "sha512": "e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f0040713f18aefdb866d53c", + "sha224": "93200ffa96c5776d38fa10abdf8f5bfc0054b9718513df472d2331d2d1e66a3f", + "sha384": "54f775c6d790f21930459162fc535dbf04a939185127016a04176a0730c6f1f4" + } + }, + { + "key": "password", + "salt": "salt", + "iterations": 1, + "dkLen": 64, + "results": { + "sha1": "0c60c80f961f0e71f3a9b524af6012062fe037a6e0f0eb94fe8fc46bdc637164ac2e7a8e3f9d2e83ace57e0d50e5e1071367c179bc86c767fc3f78ddb561363f", + "sha256": "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b4dbf3a2f3dad3377264bb7b8e8330d4efc7451418617dabef683735361cdc18c", + "sha512": "867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5d513554e1c8cf252c02d470a285a0501bad999bfe943c08f050235d7d68b1da55e63f73b60a57fce", + "sha224": "3c198cbdb9464b7857966bd05b7bc92bc1cc4e6e63155d4e490557fd859894978ab846d52a1083ac610c36c2c5ea8ce4a024dd691064d5453bd17b15ea1ac194", + "sha384": "c0e14f06e49e32d73f9f52ddf1d0c5c7191609233631dadd76a567db42b78676b38fc800cc53ddb642f5c74442e62be44d727702213e3bb9223c53b767fbfb5d" + } + }, + { + "key": "password", + "salt": "salt", + "iterations": 2, + "dkLen": 64, + "results": { + "sha1": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957cae93136266537a8d7bf4b76c51094cc1ae010b19923ddc4395cd064acb023ffd1edd5ef4be8ffe61426c28e", + "sha256": "ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43830651afcb5c862f0b249bd031f7a67520d136470f5ec271ece91c07773253d9", + "sha512": "e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f0040713f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82be67335c77a6068e04112754f27ccf4e", + "sha224": "93200ffa96c5776d38fa10abdf8f5bfc0054b9718513df472d2331d2d1e66a3f97b510224f700ce72581ffb10a1c99ec99a8cc1b951851a71f30d9265fccf912", + "sha384": "54f775c6d790f21930459162fc535dbf04a939185127016a04176a0730c6f1f4fb48832ad1261baadd2cedd50814b1c806ad1bbf43ebdc9d047904bf7ceafe1e" + } + }, + { + "key": "password", + "salt": "salt", + "iterations": 4096, + "dkLen": 32, + "results": { + "sha1": "4b007901b765489abead49d926f721d065a429c12e463f6c4cd79401085b03db", + "sha256": "c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a", + "sha512": "d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f87f6902e072f457b5", + "sha224": "218c453bf90635bd0a21a75d172703ff6108ef603f65bb821aedade1d6961683", + "sha384": "559726be38db125bc85ed7895f6e3cf574c7a01c080c3447db1e8a76764deb3c" + } + }, + { + "key": "passwordPASSWORDpassword", + "salt": "saltSALTsaltSALTsaltSALTsaltSALTsalt", + "iterations": 4096, + "dkLen": 40, + "results": { + "sha1": "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038b6b89a48612c5a25284e6605e12329", + "sha256": "348c89dbcbd32b2f32d814b8116e84cf2b17347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9", + "sha512": "8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b868c005174dc4ee71115b59f9e60cd953", + "sha224": "056c4ba438ded91fc14e0594e6f52b87e1f3690c0dc0fbc05784ed9a754ca780e6c017e80c8de278", + "sha384": "819143ad66df9a552559b9e131c52ae6c5c1b0eed18f4d283b8c5c9eaeb92b392c147cc2d2869d58" + } + }, + { + "key": "pass\u00000word", + "salt": "sa\u00000lt", + "iterations": 4096, + "dkLen": 16, + "results": { + "sha1": "345cbad979dfccb90cac5257bea6ea46", + "sha256": "1df6274d3c0bd2fc7f54fb46f149dda4", + "sha512": "336d14366099e8aac2c46c94a8f178d2", + "sha224": "0aca9ca9634db6ef4927931f633c6453", + "sha384": "b6ab6f8f6532fd9c5c30a79e1f93dcc6" + } + }, + { + "keyHex": "63ffeeddccbbaa", + "salt": "salt", + "iterations": 1, + "dkLen": 32, + "results": { + "sha1": "f6635023b135a57fb8caa89ef8ad93a29d9debb1b011e6e88bffbb212de7c01c", + "sha256": "dadd4a2638c1cf90a220777bc85d81859459513eb83063e3fce7d081490f259a", + "sha512": "f69de451247225a7b30cc47632899572bb980f500d7c606ac9b1c04f928a3488", + "sha224": "9cdee023b5d5e06ccd6c5467463e34fe461a7ed43977f8237f97b0bc7ebfd280", + "sha384": "25c72b6f0e052c883a9273a54cfd41fab86759fa3b33eb7920b923abaad62f99" + } + }, + { + "key": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", + "saltHex": "6d6e656d6f6e6963e383a1e383bce38388e383abe382abe38299e3838fe38299e382a6e38299e382a1e381afe3829ae381afe38299e3818fe38299e3829de38299e381a1e381a1e38299e58d81e4babae58d81e889b2", + "iterations": 2048, + "dkLen": 64, + "results": { + "sha1": "7e042a2f41ba17e2235fbc794e22a150816b0f54a1dfe113919fccb7a056066a109385e538f183c92bad896ae8b7d8e0f4cd66df359c77c8c7785cd1001c9a2c", + "sha256": "0b57118f2b6b079d9371c94da3a8315c3ada87a1e819b40c4c4e90b36ff2d3c8fd7555538b5119ac4d3da7844aa4259d92f9dd2188e78ac33c4b08d8e6b5964b", + "sha512": "ba553eedefe76e67e2602dc20184c564010859faada929a090dd2c57aacb204ceefd15404ab50ef3e8dbeae5195aeae64b0def4d2eead1cdc728a33ced520ffd", + "sha224": "d76474c525616ce2a527d23df8d6f6fcc4251cc3535cae4e955810a51ead1ec6acbe9c9619187ca5a3c4fd636de5b5fe58d031714731290bbc081dbf0fcb8fc1", + "sha384": "15010450f456769467e834db7fa93dd9d353e8bb733b63b0621090f96599ac3316908eb64ac9366094f0787cd4bfb2fea25be41dc271a19309710db6144f9b34" + } + }, + { + "key": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", + "salt": "mnemonicメートルガバヴァぱばぐゞちぢ十人十色", + "iterations": 2048, + "dkLen": 64, + "results": { + "sha1": "d85d14adcb7bdb5d976160e504f520a98cf71aca4cd5fceadf37759743bd6e1d2ff78bdd4403552aef7658094384b341ede80fffd334182be076f9d988a0a40f", + "sha256": "b86b5b900c29ed2724359afd793e10ffc1eb0e7d6f624fc9c85b8ac1785d9a2f0575af52a2338e611f2e6cffdee544adfff6f3d4f43be2ba0e2bd7e917b38a14", + "sha512": "3a863fa00f2e97a83fa9b18805e0047a6282cbae0ff48438b33a14475771c52d05137daa12e364cb34d84547ac07568b801c5c7f8dd4baaeee18a67a5c6a3377", + "sha224": "95727793842437774ad9ae27b8154a6f37f208b75a03d3a4d4a2443422bb6bc85efcfa92aa4376926ea89a8f5a63118eecdb58c8ca28ab31007da79437e0a1ef", + "sha384": "1a7e02e8ba0e357269a55642024b85738b95238d6cdc49bc440204995aefeff499e22cba76d4c7e96b7d4a9596a70e744f53fa94f3547e7dc506fcaf16ceb4a2" + } + } + ], + "invalid": [ + { + "key": "password", + "salt": "salt", + "iterations": "NaN", + "dkLen": 16, + "exception": "Iterations not a number" + }, + { + "key": "password", + "salt": "salt", + "iterations": -1, + "dkLen": 16, + "exception": "Bad iterations" + }, + { + "key": "password", + "salt": "salt", + "iterations": 1, + "dkLen": "NaN", + "exception": "Key length not a number" + }, + { + "key": "password", + "salt": "salt", + "iterations": 1, + "dkLen": -1, + "exception": "Bad key length" + }, + { + "key": "password", + "salt": "salt", + "iterations": 1, + "dkLen": 4073741824, + "exception": "Bad key length" + } + ] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/index.html b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/index.html new file mode 100644 index 0000000..8236391 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/index.html @@ -0,0 +1,13 @@ + + +
+ + + \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/index.js new file mode 100644 index 0000000..de2363b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/pbkdf2/test/index.js @@ -0,0 +1,93 @@ +var assert = require('assert') +var compatNode = require('../') +var compatBrowser = require('../browser') +var fixtures = require('./fixtures') + +// SHA-1 vectors generated by Node.js +// SHA-256/SHA-512 test vectors from: +// https://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors +// https://stackoverflow.com/questions/15593184/pbkdf2-hmac-sha-512-test-vectors +function runTests(compat, name) { + describe(name, function () { + var algos = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512'] + describe('pbkdf2-compat', function() { + it('defaults to sha1 and handles buffers', function(done) { + compat.pbkdf2(new Buffer('password'), new Buffer('salt'), 1, 32, function (err, result) { + assert.equal(result.toString('hex'), "0c60c80f961f0e71f3a9b524af6012062fe037a6e0f0eb94fe8fc46bdc637164") + done() + }) + }) + + describe('pbkdf2', function() { + algos.forEach(function(algorithm) { + describe(algorithm, function() { + fixtures.valid.forEach(function(f) { + var key = f.key || new Buffer(f.keyHex, 'hex') + var salt = f.salt || new Buffer(f.saltHex, 'hex') + var expected = f.results[algorithm] + + it('encodes ' + key + '(' + f.salt + ') with ' + algorithm + ' to ' + expected, function(done) { + compat.pbkdf2(key, salt, f.iterations, f.dkLen, algorithm, function(err, result) { + assert.equal(result.toString('hex'), expected) + + done() + }) + }) + }) + + fixtures.invalid.forEach(function(f) { + it('should throw ' + f.exception, function() { + assert.throws(function() { + compat.pbkdf2(f.key, f.salt, f.iterations, f.dkLen, f.algo, function (){}) + }, new RegExp(f.exception)) + }) + }) + }) + }) + + it('should throw if no callback is provided', function() { + assert.throws(function() { + compat.pbkdf2('password', 'salt', 1, 32, 'sha1') + }, /No callback provided to pbkdf2/) + }) + }) + + describe('pbkdf2Sync', function() { + it('defaults to sha1', function() { + var result = compat.pbkdf2Sync('password', 'salt', 1, 32) + + assert.equal(result.toString('hex'), "0c60c80f961f0e71f3a9b524af6012062fe037a6e0f0eb94fe8fc46bdc637164") + }) + + algos.forEach(function(algorithm) { + describe(algorithm, function() { + fixtures.valid.forEach(function(f) { + var key = f.key || new Buffer(f.keyHex, 'hex') + var salt = f.salt || new Buffer(f.saltHex, 'hex') + var expected = f.results[algorithm] + + it('encodes ' + key + '(' + f.salt + ') with ' + algorithm + ' to ' + expected, function() { + var result = compat.pbkdf2Sync(key, salt, f.iterations, f.dkLen, algorithm) + + assert.equal(result.toString('hex'), expected) + }) + }) + + fixtures.invalid.forEach(function(f) { + it('should throw ' + f.exception, function() { + assert.throws(function() { + compat.pbkdf2Sync(f.key, f.salt, f.iterations, f.dkLen, f.algo) + }, new RegExp(f.exception)) + }) + }) + }) + }) + }) + }) + }) +} + +runTests(compatBrowser, 'JavaScript pbkdf2') +if (compatBrowser !== compatNode) { + runTests(compatNode, 'node pbkdf2') +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/.travis.yml new file mode 100644 index 0000000..1b72666 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.10" + - "0.11" + - "0.12" + - iojs \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/browser.js new file mode 100644 index 0000000..0e4fabf --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/browser.js @@ -0,0 +1,10 @@ +exports.publicEncrypt = require('./publicEncrypt'); +exports.privateDecrypt = require('./privateDecrypt'); + +exports.privateEncrypt = function privateEncrypt(key, buf) { + return exports.publicEncrypt(key, buf, true); +}; + +exports.publicDecrypt = function publicDecrypt(key, buf) { + return exports.privateDecrypt(key, buf, true); +}; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/index.js new file mode 100644 index 0000000..bec688e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/index.js @@ -0,0 +1,18 @@ +var crypto = require('crypto'); +if (typeof crypto.publicEncrypt !== 'function') { + crypto = require('./browser'); +} +exports.publicEncrypt = crypto.publicEncrypt; +exports.privateDecrypt = crypto.privateDecrypt; + +if (typeof crypto.privateEncrypt !== 'function') { + exports.privateEncrypt = require('./browser').privateEncrypt; +} else { + exports.privateEncrypt = crypto.privateEncrypt; +} + +if (typeof crypto.publicDecrypt !== 'function') { + exports.publicDecrypt = require('./browser').publicDecrypt; +} else { + exports.publicDecrypt = crypto.publicDecrypt; +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/mgf.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/mgf.js new file mode 100644 index 0000000..ff72744 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/mgf.js @@ -0,0 +1,16 @@ +var createHash = require('create-hash'); +module.exports = function (seed, len) { + var t = new Buffer(''); + var i = 0, c; + while (t.length < len) { + c = i2ops(i++); + t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]); + } + return t.slice(0, len); +}; + +function i2ops(c) { + var out = new Buffer(4); + out.writeUInt32BE(c,0); + return out; +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/.npmignore new file mode 100644 index 0000000..6d1eebb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/.npmignore @@ -0,0 +1,6 @@ +benchmarks/ +coverage/ +node_modules/ +npm-debug.log +1.js +logo.png diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/.travis.yml new file mode 100644 index 0000000..936b7b7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "5" +env: + matrix: + - TEST_SUITE=unit +matrix: + include: + - node_js: "4" + env: TEST_SUITE=lint +script: npm run $TEST_SUITE diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/README.md new file mode 100644 index 0000000..fee65ba --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/README.md @@ -0,0 +1,219 @@ +# bn.js + +> BigNum in pure javascript + +[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) + +## Install +`npm install --save bn.js` + +## Usage + +```js +const BN = require('bn.js'); + +var a = new BN('dead', 16); +var b = new BN('101010', 2); + +var res = a.add(b); +console.log(res.toString(10)); // 57047 +``` + +**Note**: decimals are not supported in this library. + +## Notation + +### Prefixes + +There are several prefixes to instructions that affect the way the work. Here +is the list of them in the order of appearance in the function name: + +* `i` - perform operation in-place, storing the result in the host object (on + which the method was invoked). Might be used to avoid number allocation costs +* `u` - unsigned, ignore the sign of operands when performing operation, or + always return positive value. Second case applies to reduction operations + like `mod()`. In such cases if the result will be negative - modulo will be + added to the result to make it positive + +### Postfixes + +The only available postfix at the moment is: + +* `n` - which means that the argument of the function must be a plain JavaScript + number + +### Examples + +* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` +* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value +* `a.iushln(13)` - shift bits of `a` left by 13 + +## Instructions + +Prefixes/postfixes are put in parens at the of the line. `endian` - could be +either `le` (little-endian) or `be` (big-endian). + +### Utilities + +* `a.clone()` - clone number +* `a.toString(base, length)` - convert to base-string and pad with zeroes +* `a.toNumber()` - convert to Javascript Number (limited to 53 bits) +* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) +* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero + pad to length, throwing if already exceeding +* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, + which must behave like an `Array` +* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available) +* `a.bitLength()` - get number of bits occupied +* `a.zeroBits()` - return number of less-significant consequent zero bits + (example: `1010000` has 4 zero bits) +* `a.byteLength()` - return number of bytes occupied +* `a.isNeg()` - true if the number is negative +* `a.isEven()` - no comments +* `a.isOdd()` - no comments +* `a.isZero()` - no comments +* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) + depending on the comparison result (`ucmp`, `cmpn`) +* `a.lt(b)` - `a` less than `b` (`n`) +* `a.lte(b)` - `a` less than or equals `b` (`n`) +* `a.gt(b)` - `a` greater than `b` (`n`) +* `a.gte(b)` - `a` greater than or equals `b` (`n`) +* `a.eq(b)` - `a` equals `b` (`n`) +* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width +* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width +* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance + +### Arithmetics + +* `a.neg()` - negate sign (`i`) +* `a.abs()` - absolute value (`i`) +* `a.add(b)` - addition (`i`, `n`, `in`) +* `a.sub(b)` - subtraction (`i`, `n`, `in`) +* `a.mul(b)` - multiply (`i`, `n`, `in`) +* `a.sqr()` - square (`i`) +* `a.pow(b)` - raise `a` to the power of `b` +* `a.div(b)` - divide (`divn`, `idivn`) +* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) +* `a.divRound(b)` - rounded division + +### Bit operations + +* `a.or(b)` - or (`i`, `u`, `iu`) +* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced + with `andn` in future) +* `a.xor(b)` - xor (`i`, `u`, `iu`) +* `a.setn(b)` - set specified bit to `1` +* `a.shln(b)` - shift left (`i`, `u`, `iu`) +* `a.shrn(b)` - shift right (`i`, `u`, `iu`) +* `a.testn(b)` - test if specified bit is set +* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) +* `a.bincn(b)` - add `1 << b` to the number +* `a.notn(w)` - not (for the width specified by `w`) (`i`) + +### Reduction + +* `a.gcd(b)` - GCD +* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) +* `a.invm(b)` - inverse `a` modulo `b` + +## Fast reduction + +When doing lots of reductions using the same modulo, it might be beneficial to +use some tricks: like [Montgomery multiplication][0], or using special algorithm +for [Mersenne Prime][1]. + +### Reduction context + +To enable this tricks one should create a reduction context: + +```js +var red = BN.red(num); +``` +where `num` is just a BN instance. + +Or: + +```js +var red = BN.red(primeName); +``` + +Where `primeName` is either of these [Mersenne Primes][1]: + +* `'k256'` +* `'p224'` +* `'p192'` +* `'p25519'` + +Or: + +```js +var red = BN.mont(num); +``` + +To reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than +`.red(num)`, but slower than `BN.red(primeName)`. + +### Converting numbers + +Before performing anything in reduction context - numbers should be converted +to it. Usually, this means that one should: + +* Convert inputs to reducted ones +* Operate on them in reduction context +* Convert outputs back from the reduction context + +Here is how one may convert numbers to `red`: + +```js +var redA = a.toRed(red); +``` +Where `red` is a reduction context created using instructions above + +Here is how to convert them back: + +```js +var a = redA.fromRed(); +``` + +### Red instructions + +Most of the instructions from the very start of this readme have their +counterparts in red context: + +* `a.redAdd(b)`, `a.redIAdd(b)` +* `a.redSub(b)`, `a.redISub(b)` +* `a.redShl(num)` +* `a.redMul(b)`, `a.redIMul(b)` +* `a.redSqr()`, `a.redISqr()` +* `a.redSqrt()` - square root modulo reduction context's prime +* `a.redInvm()` - modular inverse of the number +* `a.redNeg()` +* `a.redPow(b)` - modular exponentiation + +## LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2015. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + +[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication +[1]: https://en.wikipedia.org/wiki/Mersenne_prime diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/lib/bn.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/lib/bn.js new file mode 100644 index 0000000..3ca1646 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/lib/bn.js @@ -0,0 +1,3420 @@ +(function (module, exports) { + 'use strict'; + + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } + + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buf' + 'fer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + return num !== null && typeof num === 'object' && + num.constructor.name === 'BN' && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var length = this.bitLength(); + var ret; + if (length <= 26) { + ret = this.words[0]; + } else if (length <= 52) { + ret = (this.words[1] * 0x4000000) + this.words[0]; + } else if (length === 53) { + // NOTE: at this stage it is known that the top bit is set + ret = 0x10000000000000 + (this.words[1] * 0x4000000) + this.words[0]; + } else { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid += Math.imul(ah0, bl0); + hi = Math.imul(ah0, bh0); + var w0 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w0 >>> 26); + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid += Math.imul(ah1, bl0); + hi = Math.imul(ah1, bh0); + lo += Math.imul(al0, bl1); + mid += Math.imul(al0, bh1); + mid += Math.imul(ah0, bl1); + hi += Math.imul(ah0, bh1); + var w1 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w1 >>> 26); + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid += Math.imul(ah2, bl0); + hi = Math.imul(ah2, bh0); + lo += Math.imul(al1, bl1); + mid += Math.imul(al1, bh1); + mid += Math.imul(ah1, bl1); + hi += Math.imul(ah1, bh1); + lo += Math.imul(al0, bl2); + mid += Math.imul(al0, bh2); + mid += Math.imul(ah0, bl2); + hi += Math.imul(ah0, bh2); + var w2 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w2 >>> 26); + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid += Math.imul(ah3, bl0); + hi = Math.imul(ah3, bh0); + lo += Math.imul(al2, bl1); + mid += Math.imul(al2, bh1); + mid += Math.imul(ah2, bl1); + hi += Math.imul(ah2, bh1); + lo += Math.imul(al1, bl2); + mid += Math.imul(al1, bh2); + mid += Math.imul(ah1, bl2); + hi += Math.imul(ah1, bh2); + lo += Math.imul(al0, bl3); + mid += Math.imul(al0, bh3); + mid += Math.imul(ah0, bl3); + hi += Math.imul(ah0, bh3); + var w3 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w3 >>> 26); + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid += Math.imul(ah4, bl0); + hi = Math.imul(ah4, bh0); + lo += Math.imul(al3, bl1); + mid += Math.imul(al3, bh1); + mid += Math.imul(ah3, bl1); + hi += Math.imul(ah3, bh1); + lo += Math.imul(al2, bl2); + mid += Math.imul(al2, bh2); + mid += Math.imul(ah2, bl2); + hi += Math.imul(ah2, bh2); + lo += Math.imul(al1, bl3); + mid += Math.imul(al1, bh3); + mid += Math.imul(ah1, bl3); + hi += Math.imul(ah1, bh3); + lo += Math.imul(al0, bl4); + mid += Math.imul(al0, bh4); + mid += Math.imul(ah0, bl4); + hi += Math.imul(ah0, bh4); + var w4 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w4 >>> 26); + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid += Math.imul(ah5, bl0); + hi = Math.imul(ah5, bh0); + lo += Math.imul(al4, bl1); + mid += Math.imul(al4, bh1); + mid += Math.imul(ah4, bl1); + hi += Math.imul(ah4, bh1); + lo += Math.imul(al3, bl2); + mid += Math.imul(al3, bh2); + mid += Math.imul(ah3, bl2); + hi += Math.imul(ah3, bh2); + lo += Math.imul(al2, bl3); + mid += Math.imul(al2, bh3); + mid += Math.imul(ah2, bl3); + hi += Math.imul(ah2, bh3); + lo += Math.imul(al1, bl4); + mid += Math.imul(al1, bh4); + mid += Math.imul(ah1, bl4); + hi += Math.imul(ah1, bh4); + lo += Math.imul(al0, bl5); + mid += Math.imul(al0, bh5); + mid += Math.imul(ah0, bl5); + hi += Math.imul(ah0, bh5); + var w5 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w5 >>> 26); + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid += Math.imul(ah6, bl0); + hi = Math.imul(ah6, bh0); + lo += Math.imul(al5, bl1); + mid += Math.imul(al5, bh1); + mid += Math.imul(ah5, bl1); + hi += Math.imul(ah5, bh1); + lo += Math.imul(al4, bl2); + mid += Math.imul(al4, bh2); + mid += Math.imul(ah4, bl2); + hi += Math.imul(ah4, bh2); + lo += Math.imul(al3, bl3); + mid += Math.imul(al3, bh3); + mid += Math.imul(ah3, bl3); + hi += Math.imul(ah3, bh3); + lo += Math.imul(al2, bl4); + mid += Math.imul(al2, bh4); + mid += Math.imul(ah2, bl4); + hi += Math.imul(ah2, bh4); + lo += Math.imul(al1, bl5); + mid += Math.imul(al1, bh5); + mid += Math.imul(ah1, bl5); + hi += Math.imul(ah1, bh5); + lo += Math.imul(al0, bl6); + mid += Math.imul(al0, bh6); + mid += Math.imul(ah0, bl6); + hi += Math.imul(ah0, bh6); + var w6 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w6 >>> 26); + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid += Math.imul(ah7, bl0); + hi = Math.imul(ah7, bh0); + lo += Math.imul(al6, bl1); + mid += Math.imul(al6, bh1); + mid += Math.imul(ah6, bl1); + hi += Math.imul(ah6, bh1); + lo += Math.imul(al5, bl2); + mid += Math.imul(al5, bh2); + mid += Math.imul(ah5, bl2); + hi += Math.imul(ah5, bh2); + lo += Math.imul(al4, bl3); + mid += Math.imul(al4, bh3); + mid += Math.imul(ah4, bl3); + hi += Math.imul(ah4, bh3); + lo += Math.imul(al3, bl4); + mid += Math.imul(al3, bh4); + mid += Math.imul(ah3, bl4); + hi += Math.imul(ah3, bh4); + lo += Math.imul(al2, bl5); + mid += Math.imul(al2, bh5); + mid += Math.imul(ah2, bl5); + hi += Math.imul(ah2, bh5); + lo += Math.imul(al1, bl6); + mid += Math.imul(al1, bh6); + mid += Math.imul(ah1, bl6); + hi += Math.imul(ah1, bh6); + lo += Math.imul(al0, bl7); + mid += Math.imul(al0, bh7); + mid += Math.imul(ah0, bl7); + hi += Math.imul(ah0, bh7); + var w7 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w7 >>> 26); + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid += Math.imul(ah8, bl0); + hi = Math.imul(ah8, bh0); + lo += Math.imul(al7, bl1); + mid += Math.imul(al7, bh1); + mid += Math.imul(ah7, bl1); + hi += Math.imul(ah7, bh1); + lo += Math.imul(al6, bl2); + mid += Math.imul(al6, bh2); + mid += Math.imul(ah6, bl2); + hi += Math.imul(ah6, bh2); + lo += Math.imul(al5, bl3); + mid += Math.imul(al5, bh3); + mid += Math.imul(ah5, bl3); + hi += Math.imul(ah5, bh3); + lo += Math.imul(al4, bl4); + mid += Math.imul(al4, bh4); + mid += Math.imul(ah4, bl4); + hi += Math.imul(ah4, bh4); + lo += Math.imul(al3, bl5); + mid += Math.imul(al3, bh5); + mid += Math.imul(ah3, bl5); + hi += Math.imul(ah3, bh5); + lo += Math.imul(al2, bl6); + mid += Math.imul(al2, bh6); + mid += Math.imul(ah2, bl6); + hi += Math.imul(ah2, bh6); + lo += Math.imul(al1, bl7); + mid += Math.imul(al1, bh7); + mid += Math.imul(ah1, bl7); + hi += Math.imul(ah1, bh7); + lo += Math.imul(al0, bl8); + mid += Math.imul(al0, bh8); + mid += Math.imul(ah0, bl8); + hi += Math.imul(ah0, bh8); + var w8 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w8 >>> 26); + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid += Math.imul(ah9, bl0); + hi = Math.imul(ah9, bh0); + lo += Math.imul(al8, bl1); + mid += Math.imul(al8, bh1); + mid += Math.imul(ah8, bl1); + hi += Math.imul(ah8, bh1); + lo += Math.imul(al7, bl2); + mid += Math.imul(al7, bh2); + mid += Math.imul(ah7, bl2); + hi += Math.imul(ah7, bh2); + lo += Math.imul(al6, bl3); + mid += Math.imul(al6, bh3); + mid += Math.imul(ah6, bl3); + hi += Math.imul(ah6, bh3); + lo += Math.imul(al5, bl4); + mid += Math.imul(al5, bh4); + mid += Math.imul(ah5, bl4); + hi += Math.imul(ah5, bh4); + lo += Math.imul(al4, bl5); + mid += Math.imul(al4, bh5); + mid += Math.imul(ah4, bl5); + hi += Math.imul(ah4, bh5); + lo += Math.imul(al3, bl6); + mid += Math.imul(al3, bh6); + mid += Math.imul(ah3, bl6); + hi += Math.imul(ah3, bh6); + lo += Math.imul(al2, bl7); + mid += Math.imul(al2, bh7); + mid += Math.imul(ah2, bl7); + hi += Math.imul(ah2, bh7); + lo += Math.imul(al1, bl8); + mid += Math.imul(al1, bh8); + mid += Math.imul(ah1, bl8); + hi += Math.imul(ah1, bh8); + lo += Math.imul(al0, bl9); + mid += Math.imul(al0, bh9); + mid += Math.imul(ah0, bl9); + hi += Math.imul(ah0, bh9); + var w9 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w9 >>> 26); + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid += Math.imul(ah9, bl1); + hi = Math.imul(ah9, bh1); + lo += Math.imul(al8, bl2); + mid += Math.imul(al8, bh2); + mid += Math.imul(ah8, bl2); + hi += Math.imul(ah8, bh2); + lo += Math.imul(al7, bl3); + mid += Math.imul(al7, bh3); + mid += Math.imul(ah7, bl3); + hi += Math.imul(ah7, bh3); + lo += Math.imul(al6, bl4); + mid += Math.imul(al6, bh4); + mid += Math.imul(ah6, bl4); + hi += Math.imul(ah6, bh4); + lo += Math.imul(al5, bl5); + mid += Math.imul(al5, bh5); + mid += Math.imul(ah5, bl5); + hi += Math.imul(ah5, bh5); + lo += Math.imul(al4, bl6); + mid += Math.imul(al4, bh6); + mid += Math.imul(ah4, bl6); + hi += Math.imul(ah4, bh6); + lo += Math.imul(al3, bl7); + mid += Math.imul(al3, bh7); + mid += Math.imul(ah3, bl7); + hi += Math.imul(ah3, bh7); + lo += Math.imul(al2, bl8); + mid += Math.imul(al2, bh8); + mid += Math.imul(ah2, bl8); + hi += Math.imul(ah2, bh8); + lo += Math.imul(al1, bl9); + mid += Math.imul(al1, bh9); + mid += Math.imul(ah1, bl9); + hi += Math.imul(ah1, bh9); + var w10 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w10 >>> 26); + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid += Math.imul(ah9, bl2); + hi = Math.imul(ah9, bh2); + lo += Math.imul(al8, bl3); + mid += Math.imul(al8, bh3); + mid += Math.imul(ah8, bl3); + hi += Math.imul(ah8, bh3); + lo += Math.imul(al7, bl4); + mid += Math.imul(al7, bh4); + mid += Math.imul(ah7, bl4); + hi += Math.imul(ah7, bh4); + lo += Math.imul(al6, bl5); + mid += Math.imul(al6, bh5); + mid += Math.imul(ah6, bl5); + hi += Math.imul(ah6, bh5); + lo += Math.imul(al5, bl6); + mid += Math.imul(al5, bh6); + mid += Math.imul(ah5, bl6); + hi += Math.imul(ah5, bh6); + lo += Math.imul(al4, bl7); + mid += Math.imul(al4, bh7); + mid += Math.imul(ah4, bl7); + hi += Math.imul(ah4, bh7); + lo += Math.imul(al3, bl8); + mid += Math.imul(al3, bh8); + mid += Math.imul(ah3, bl8); + hi += Math.imul(ah3, bh8); + lo += Math.imul(al2, bl9); + mid += Math.imul(al2, bh9); + mid += Math.imul(ah2, bl9); + hi += Math.imul(ah2, bh9); + var w11 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w11 >>> 26); + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid += Math.imul(ah9, bl3); + hi = Math.imul(ah9, bh3); + lo += Math.imul(al8, bl4); + mid += Math.imul(al8, bh4); + mid += Math.imul(ah8, bl4); + hi += Math.imul(ah8, bh4); + lo += Math.imul(al7, bl5); + mid += Math.imul(al7, bh5); + mid += Math.imul(ah7, bl5); + hi += Math.imul(ah7, bh5); + lo += Math.imul(al6, bl6); + mid += Math.imul(al6, bh6); + mid += Math.imul(ah6, bl6); + hi += Math.imul(ah6, bh6); + lo += Math.imul(al5, bl7); + mid += Math.imul(al5, bh7); + mid += Math.imul(ah5, bl7); + hi += Math.imul(ah5, bh7); + lo += Math.imul(al4, bl8); + mid += Math.imul(al4, bh8); + mid += Math.imul(ah4, bl8); + hi += Math.imul(ah4, bh8); + lo += Math.imul(al3, bl9); + mid += Math.imul(al3, bh9); + mid += Math.imul(ah3, bl9); + hi += Math.imul(ah3, bh9); + var w12 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w12 >>> 26); + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid += Math.imul(ah9, bl4); + hi = Math.imul(ah9, bh4); + lo += Math.imul(al8, bl5); + mid += Math.imul(al8, bh5); + mid += Math.imul(ah8, bl5); + hi += Math.imul(ah8, bh5); + lo += Math.imul(al7, bl6); + mid += Math.imul(al7, bh6); + mid += Math.imul(ah7, bl6); + hi += Math.imul(ah7, bh6); + lo += Math.imul(al6, bl7); + mid += Math.imul(al6, bh7); + mid += Math.imul(ah6, bl7); + hi += Math.imul(ah6, bh7); + lo += Math.imul(al5, bl8); + mid += Math.imul(al5, bh8); + mid += Math.imul(ah5, bl8); + hi += Math.imul(ah5, bh8); + lo += Math.imul(al4, bl9); + mid += Math.imul(al4, bh9); + mid += Math.imul(ah4, bl9); + hi += Math.imul(ah4, bh9); + var w13 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w13 >>> 26); + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid += Math.imul(ah9, bl5); + hi = Math.imul(ah9, bh5); + lo += Math.imul(al8, bl6); + mid += Math.imul(al8, bh6); + mid += Math.imul(ah8, bl6); + hi += Math.imul(ah8, bh6); + lo += Math.imul(al7, bl7); + mid += Math.imul(al7, bh7); + mid += Math.imul(ah7, bl7); + hi += Math.imul(ah7, bh7); + lo += Math.imul(al6, bl8); + mid += Math.imul(al6, bh8); + mid += Math.imul(ah6, bl8); + hi += Math.imul(ah6, bh8); + lo += Math.imul(al5, bl9); + mid += Math.imul(al5, bh9); + mid += Math.imul(ah5, bl9); + hi += Math.imul(ah5, bh9); + var w14 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w14 >>> 26); + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid += Math.imul(ah9, bl6); + hi = Math.imul(ah9, bh6); + lo += Math.imul(al8, bl7); + mid += Math.imul(al8, bh7); + mid += Math.imul(ah8, bl7); + hi += Math.imul(ah8, bh7); + lo += Math.imul(al7, bl8); + mid += Math.imul(al7, bh8); + mid += Math.imul(ah7, bl8); + hi += Math.imul(ah7, bh8); + lo += Math.imul(al6, bl9); + mid += Math.imul(al6, bh9); + mid += Math.imul(ah6, bl9); + hi += Math.imul(ah6, bh9); + var w15 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w15 >>> 26); + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid += Math.imul(ah9, bl7); + hi = Math.imul(ah9, bh7); + lo += Math.imul(al8, bl8); + mid += Math.imul(al8, bh8); + mid += Math.imul(ah8, bl8); + hi += Math.imul(ah8, bh8); + lo += Math.imul(al7, bl9); + mid += Math.imul(al7, bh9); + mid += Math.imul(ah7, bl9); + hi += Math.imul(ah7, bh9); + var w16 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w16 >>> 26); + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid += Math.imul(ah9, bl8); + hi = Math.imul(ah9, bh8); + lo += Math.imul(al8, bl9); + mid += Math.imul(al8, bh9); + mid += Math.imul(ah8, bl9); + hi += Math.imul(ah8, bh9); + var w17 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w17 >>> 26); + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid += Math.imul(ah9, bl9); + hi = Math.imul(ah9, bh9); + var w18 = c + lo + ((mid & 0x1fff) << 13); + c = hi + (mid >>> 13) + (w18 >>> 26); + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; +})(typeof module === 'undefined' || module, this); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/package.json new file mode 100644 index 0000000..63ecf80 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/package.json @@ -0,0 +1,42 @@ +{ + "name": "bn.js", + "version": "4.11.1", + "description": "Big number implementation in pure javascript", + "main": "lib/bn.js", + "scripts": { + "lint": "semistandard", + "unit": "mocha --reporter=spec test/*-test.js", + "test": "npm run lint && npm run unit" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/bn.js.git" + }, + "keywords": [ + "BN", + "BigNum", + "Big number", + "Modulo", + "Montgomery" + ], + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/bn.js/issues" + }, + "homepage": "https://github.com/indutny/bn.js", + "devDependencies": { + "istanbul": "^0.3.5", + "mocha": "^2.1.0", + "semistandard": "^7.0.4" + }, + "readme": "# \"bn.js\"\n\n> BigNum in pure javascript\n\n[![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js)\n\n## Install\n`npm install --save bn.js`\n\n## Usage\n\n```js\nconst BN = require('bn.js');\n\nvar a = new BN('dead', 16);\nvar b = new BN('101010', 2);\n\nvar res = a.add(b);\nconsole.log(res.toString(10)); // 57047\n```\n\n**Note**: decimals are not supported in this library.\n\n## Notation\n\n### Prefixes\n\nThere are several prefixes to instructions that affect the way the work. Here\nis the list of them in the order of appearance in the function name:\n\n* `i` - perform operation in-place, storing the result in the host object (on\n which the method was invoked). Might be used to avoid number allocation costs\n* `u` - unsigned, ignore the sign of operands when performing operation, or\n always return positive value. Second case applies to reduction operations\n like `mod()`. In such cases if the result will be negative - modulo will be\n added to the result to make it positive\n\n### Postfixes\n\nThe only available postfix at the moment is:\n\n* `n` - which means that the argument of the function must be a plain JavaScript\n number\n\n### Examples\n\n* `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a`\n* `a.pmod(b)` - reduce `a` modulo `b`, returning positive value\n* `a.iushln(13)` - shift bits of `a` left by 13\n\n## Instructions\n\nPrefixes/postfixes are put in parens at the of the line. `endian` - could be\neither `le` (little-endian) or `be` (big-endian).\n\n### Utilities\n\n* `a.clone()` - clone number\n* `a.toString(base, length)` - convert to base-string and pad with zeroes\n* `a.toNumber()` - convert to Javascript Number (limited to 53 bits)\n* `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`)\n* `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero\n pad to length, throwing if already exceeding\n* `a.toArrayLike(type, endian, length)` - convert to an instance of `type`,\n which must behave like an `Array`\n* `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available)\n* `a.bitLength()` - get number of bits occupied\n* `a.zeroBits()` - return number of less-significant consequent zero bits\n (example: `1010000` has 4 zero bits)\n* `a.byteLength()` - return number of bytes occupied\n* `a.isNeg()` - true if the number is negative\n* `a.isEven()` - no comments\n* `a.isOdd()` - no comments\n* `a.isZero()` - no comments\n* `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b)\n depending on the comparison result (`ucmp`, `cmpn`)\n* `a.lt(b)` - `a` less than `b` (`n`)\n* `a.lte(b)` - `a` less than or equals `b` (`n`)\n* `a.gt(b)` - `a` greater than `b` (`n`)\n* `a.gte(b)` - `a` greater than or equals `b` (`n`)\n* `a.eq(b)` - `a` equals `b` (`n`)\n* `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width\n* `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width\n* `a.isBN(object)` - returns true if the supplied `object` is a BN.js instance\n\n### Arithmetics\n\n* `a.neg()` - negate sign (`i`)\n* `a.abs()` - absolute value (`i`)\n* `a.add(b)` - addition (`i`, `n`, `in`)\n* `a.sub(b)` - subtraction (`i`, `n`, `in`)\n* `a.mul(b)` - multiply (`i`, `n`, `in`)\n* `a.sqr()` - square (`i`)\n* `a.pow(b)` - raise `a` to the power of `b`\n* `a.div(b)` - divide (`divn`, `idivn`)\n* `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`)\n* `a.divRound(b)` - rounded division\n\n### Bit operations\n\n* `a.or(b)` - or (`i`, `u`, `iu`)\n* `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced\n with `andn` in future)\n* `a.xor(b)` - xor (`i`, `u`, `iu`)\n* `a.setn(b)` - set specified bit to `1`\n* `a.shln(b)` - shift left (`i`, `u`, `iu`)\n* `a.shrn(b)` - shift right (`i`, `u`, `iu`)\n* `a.testn(b)` - test if specified bit is set\n* `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`)\n* `a.bincn(b)` - add `1 << b` to the number\n* `a.notn(w)` - not (for the width specified by `w`) (`i`)\n\n### Reduction\n\n* `a.gcd(b)` - GCD\n* `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`)\n* `a.invm(b)` - inverse `a` modulo `b`\n\n## Fast reduction\n\nWhen doing lots of reductions using the same modulo, it might be beneficial to\nuse some tricks: like [Montgomery multiplication][0], or using special algorithm\nfor [Mersenne Prime][1].\n\n### Reduction context\n\nTo enable this tricks one should create a reduction context:\n\n```js\nvar red = BN.red(num);\n```\nwhere `num` is just a BN instance.\n\nOr:\n\n```js\nvar red = BN.red(primeName);\n```\n\nWhere `primeName` is either of these [Mersenne Primes][1]:\n\n* `'k256'`\n* `'p224'`\n* `'p192'`\n* `'p25519'`\n\nOr:\n\n```js\nvar red = BN.mont(num);\n```\n\nTo reduce numbers with [Montgomery trick][1]. `.mont()` is generally faster than\n`.red(num)`, but slower than `BN.red(primeName)`.\n\n### Converting numbers\n\nBefore performing anything in reduction context - numbers should be converted\nto it. Usually, this means that one should:\n\n* Convert inputs to reducted ones\n* Operate on them in reduction context\n* Convert outputs back from the reduction context\n\nHere is how one may convert numbers to `red`:\n\n```js\nvar redA = a.toRed(red);\n```\nWhere `red` is a reduction context created using instructions above\n\nHere is how to convert them back:\n\n```js\nvar a = redA.fromRed();\n```\n\n### Red instructions\n\nMost of the instructions from the very start of this readme have their\ncounterparts in red context:\n\n* `a.redAdd(b)`, `a.redIAdd(b)`\n* `a.redSub(b)`, `a.redISub(b)`\n* `a.redShl(num)`\n* `a.redMul(b)`, `a.redIMul(b)`\n* `a.redSqr()`, `a.redISqr()`\n* `a.redSqrt()` - square root modulo reduction context's prime\n* `a.redInvm()` - modular inverse of the number\n* `a.redNeg()`\n* `a.redPow(b)` - modular exponentiation\n\n## LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2015.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication\n[1]: https://en.wikipedia.org/wiki/Mersenne_prime\n", + "readmeFilename": "README.md", + "_id": "bn.js@4.11.1", + "_shasum": "ff1c52c52fd371e9d91419439bac5cfba2b41798", + "_resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz", + "_from": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/arithmetic-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/arithmetic-test.js new file mode 100644 index 0000000..3f336ac --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/arithmetic-test.js @@ -0,0 +1,635 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; +var fixtures = require('./fixtures'); + +describe('BN.js/Arithmetic', function () { + describe('.add()', function () { + it('should add numbers', function () { + assert.equal(new BN(14).add(new BN(26)).toString(16), '28'); + var k = new BN(0x1234); + var r = k; + + for (var i = 0; i < 257; i++) { + r = r.add(k); + } + + assert.equal(r.toString(16), '125868'); + }); + + it('should handle carry properly (in-place)', function () { + var k = new BN('abcdefabcdefabcdef', 16); + var r = new BN('deadbeef', 16); + + for (var i = 0; i < 257; i++) { + r.iadd(k); + } + + assert.equal(r.toString(16), 'ac79bd9b79be7a277bde'); + }); + + it('should properly do positive + negative', function () { + var a = new BN('abcd', 16); + var b = new BN('-abce', 16); + + assert.equal(a.iadd(b).toString(16), '-1'); + + a = new BN('abcd', 16); + b = new BN('-abce', 16); + + assert.equal(a.add(b).toString(16), '-1'); + assert.equal(b.add(a).toString(16), '-1'); + }); + }); + + describe('.iaddn()', function () { + it('should allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should add negative number', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.iaddn(-200); + + assert.equal(a.toString(), '-300'); + }); + + it('should allow neg + pos with big number', function () { + var a = new BN('-1000000000', 10); + assert.equal(a.negative, 1); + + a.iaddn(200); + + assert.equal(a.toString(), '-999999800'); + }); + + it('should carry limb', function () { + var a = new BN('3ffffff', 16); + + assert.equal(a.iaddn(1).toString(16), '4000000'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).iaddn(0x4000000); + }); + }); + }); + + describe('.sub()', function () { + it('should subtract small numbers', function () { + assert.equal(new BN(26).sub(new BN(14)).toString(16), 'c'); + assert.equal(new BN(14).sub(new BN(26)).toString(16), '-c'); + assert.equal(new BN(26).sub(new BN(26)).toString(16), '0'); + assert.equal(new BN(-26).sub(new BN(26)).toString(16), '-34'); + }); + + var a = new BN( + '31ff3c61db2db84b9823d320907a573f6ad37c437abe458b1802cda041d6384' + + 'a7d8daef41395491e2', + 16); + var b = new BN( + '6f0e4d9f1d6071c183677f601af9305721c91d31b0bbbae8fb790000', + 16); + var r = new BN( + '31ff3c61db2db84b9823d3208989726578fd75276287cd9516533a9acfb9a67' + + '76281f34583ddb91e2', + 16); + + it('should subtract big numbers', function () { + assert.equal(a.sub(b).cmp(r), 0); + }); + + it('should subtract numbers in place', function () { + assert.equal(b.clone().isub(a).neg().cmp(r), 0); + }); + + it('should subtract with carry', function () { + // Carry and copy + var a = new BN('12345', 16); + var b = new BN('1000000000000', 16); + assert.equal(a.isub(b).toString(16), '-fffffffedcbb'); + + a = new BN('12345', 16); + b = new BN('1000000000000', 16); + assert.equal(b.isub(a).toString(16), 'fffffffedcbb'); + }); + }); + + describe('.isubn()', function () { + it('should subtract negative number', function () { + var r = new BN( + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b', 16); + assert.equal(r.isubn(-1).toString(16), + '7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681c'); + }); + + it('should work for positive numbers', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(200); + assert.equal(a.negative, 1); + assert.equal(a.toString(), '-300'); + }); + + it('should not allow a sign change', function () { + var a = new BN(-100); + assert.equal(a.negative, 1); + + a.isubn(-200); + assert.equal(a.negative, 0); + assert.equal(a.toString(), '100'); + }); + + it('should change sign on small numbers at 0', function () { + var a = new BN(0).subn(2); + assert.equal(a.toString(), '-2'); + }); + + it('should change sign on small numbers at 1', function () { + var a = new BN(1).subn(2); + assert.equal(a.toString(), '-1'); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).isubn(0x4000000); + }); + }); + }); + + function testMethod (name, mul) { + describe(name, function () { + it('should multiply numbers of different signs', function () { + var offsets = [ + 1, // smallMulTo + 250, // comb10MulTo + 1000, // bigMulTo + 15000 // jumboMulTo + ]; + + for (var i = 0; i < offsets.length; ++i) { + var x = new BN(1).ishln(offsets[i]); + + assert.equal(mul(x, x).isNeg(), false); + assert.equal(mul(x, x.neg()).isNeg(), true); + assert.equal(mul(x.neg(), x).isNeg(), true); + assert.equal(mul(x.neg(), x.neg()).isNeg(), false); + } + }); + + it('should multiply with carry', function () { + var n = new BN(0x1001); + var r = n; + + for (var i = 0; i < 4; i++) { + r = mul(r, n); + } + + assert.equal(r.toString(16), '100500a00a005001'); + }); + + it('should correctly multiply big numbers', function () { + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal( + mul(n, n).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40'); + assert.equal( + mul(mul(n, n), n).toString(16), + '1b888e01a06e974017a28a5b4da436169761c9730b7aeedf75fc60f687b' + + '46e0cf2cb11667f795d5569482640fe5f628939467a01a612b02350' + + '0d0161e9730279a7561043af6197798e41b7432458463e64fa81158' + + '907322dc330562697d0d600'); + }); + + it('should multiply neg number on 0', function () { + assert.equal( + mul(new BN('-100000000000'), new BN('3').div(new BN('4'))) + .toString(16), + '0' + ); + }); + + it('should regress mul big numbers', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + assert.equal(mul(q, q).toString(16), qs); + }); + }); + } + + testMethod('.mul()', function (x, y) { + return BN.prototype.mul.apply(x, [ y ]); + }); + + testMethod('.mulf()', function (x, y) { + return BN.prototype.mulf.apply(x, [ y ]); + }); + + describe('.imul()', function () { + it('should multiply numbers in-place', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('deadbeefa551edebabba8', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + + a = new BN('abcdef01234567890abcd214a25123f512361e6d236', 16); + b = new BN('deadbeefa551edebabba8121234fd21bac0341324dd', 16); + c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should multiply by 0', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('0', 16); + var c = a.mul(b); + + assert.equal(a.imul(b).toString(16), c.toString(16)); + }); + + it('should regress mul big numbers in-place', function () { + var q = fixtures.dhGroups.p17.q; + var qs = fixtures.dhGroups.p17.qs; + + q = new BN(q, 16); + + assert.equal(q.isqr().toString(16), qs); + }); + }); + + describe('.muln()', function () { + it('should multiply number by small number', function () { + var a = new BN('abcdef01234567890abcd', 16); + var b = new BN('dead', 16); + var c = a.mul(b); + + assert.equal(a.muln(0xdead).toString(16), c.toString(16)); + }); + + it('should throw error with num eq 0x4000000', function () { + assert.throws(function () { + new BN(0).imuln(0x4000000); + }); + }); + }); + + describe('.pow()', function () { + it('should raise number to the power', function () { + var a = new BN('ab', 16); + var b = new BN('13', 10); + var c = a.pow(b); + + assert.equal(c.toString(16), '15963da06977df51909c9ba5b'); + }); + }); + + describe('.div()', function () { + it('should divide small numbers (<=26 bits)', function () { + assert.equal(new BN('256').div(new BN(10)).toString(10), + '25'); + assert.equal(new BN('-256').div(new BN(10)).toString(10), + '-25'); + assert.equal(new BN('256').div(new BN(-10)).toString(10), + '-25'); + assert.equal(new BN('-256').div(new BN(-10)).toString(10), + '25'); + + assert.equal(new BN('10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(256)).toString(10), + '0'); + assert.equal(new BN('10').div(new BN(-256)).toString(10), + '0'); + assert.equal(new BN('-10').div(new BN(-256)).toString(10), + '0'); + }); + + it('should divide large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').div(new BN('611111124969028')) + .toString(10), '1'); + assert.equal(new BN('-1222222225255589').div(new BN('611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('1222222225255589').div(new BN('-611111124969028')) + .toString(10), '-1'); + assert.equal(new BN('-1222222225255589').div(new BN('-611111124969028')) + .toString(10), '1'); + + assert.equal(new BN('611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + assert.equal(new BN('-611111124969028').div(new BN('-1222222225255589')) + .toString(10), '0'); + }); + + it('should divide numbers', function () { + assert.equal(new BN('69527932928').div(new BN('16974594')).toString(16), + 'fff'); + assert.equal(new BN('-69527932928').div(new BN('16974594')).toString(16), + '-fff'); + + var b = new BN( + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729ab9' + + 'b055c3a9458e4ce3289560a38e08ba8175a9446ce14e608245ab3a9' + + '978a8bd8acaa40', + 16); + var n = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16 + ); + assert.equal(b.div(n).toString(16), n.toString(16)); + + assert.equal(new BN('1').div(new BN('-5')).toString(10), '0'); + }); + + it('should not fail on regression after moving to _wordDiv', function () { + // Regression after moving to word div + var p = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f', + 16); + var a = new BN( + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + 16); + var as = a.sqr(); + assert.equal( + as.div(p).toString(16), + '39e58a8055b6fb264b75ec8c646509784204ac15a8c24e05babc9729e58090b9'); + + p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.div(p).toString(16), + 'ffffffff00000002000000000000000000000001000000000000000000000001'); + }); + }); + + describe('.idivn()', function () { + it('should divide numbers in-place', function () { + assert.equal(new BN('10', 16).idivn(3).toString(16), '5'); + assert.equal(new BN('12', 16).idivn(3).toString(16), '6'); + assert.equal(new BN('10000000000000000').idivn(3).toString(10), + '3333333333333333'); + assert.equal( + new BN('100000000000000000000000000000').idivn(3).toString(10), + '33333333333333333333333333333'); + + var t = new BN(3); + assert.equal( + new BN('12345678901234567890123456', 16).idivn(3).toString(16), + new BN('12345678901234567890123456', 16).div(t).toString(16)); + }); + }); + + describe('.divRound()', function () { + it('should divide numbers with rounding', function () { + assert.equal(new BN(9).divRound(new BN(20)).toString(10), + '0'); + assert.equal(new BN(10).divRound(new BN(20)).toString(10), + '1'); + assert.equal(new BN(150).divRound(new BN(20)).toString(10), + '8'); + assert.equal(new BN(149).divRound(new BN(20)).toString(10), + '7'); + assert.equal(new BN(149).divRound(new BN(17)).toString(10), + '9'); + assert.equal(new BN(144).divRound(new BN(17)).toString(10), + '8'); + assert.equal(new BN(-144).divRound(new BN(17)).toString(10), + '-8'); + }); + + it('should return 1 on exact division', function () { + assert.equal(new BN(144).divRound(new BN(144)).toString(10), '1'); + }); + }); + + describe('.mod()', function () { + it('should modulo small numbers (<=26 bits)', function () { + assert.equal(new BN('256').mod(new BN(10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(10)).toString(10), + '-6'); + assert.equal(new BN('256').mod(new BN(-10)).toString(10), + '6'); + assert.equal(new BN('-256').mod(new BN(-10)).toString(10), + '-6'); + + assert.equal(new BN('10').mod(new BN(256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(256)).toString(10), + '-10'); + assert.equal(new BN('10').mod(new BN(-256)).toString(10), + '10'); + assert.equal(new BN('-10').mod(new BN(-256)).toString(10), + '-10'); + }); + + it('should modulo large numbers (>53 bits)', function () { + assert.equal(new BN('1222222225255589').mod(new BN('611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('611111124969028')) + .toString(10), '-611111100286561'); + assert.equal(new BN('1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '611111100286561'); + assert.equal(new BN('-1222222225255589').mod(new BN('-611111124969028')) + .toString(10), '-611111100286561'); + + assert.equal(new BN('611111124969028').mod(new BN('1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('1222222225255589')) + .toString(10), '-611111124969028'); + assert.equal(new BN('611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '611111124969028'); + assert.equal(new BN('-611111124969028').mod(new BN('-1222222225255589')) + .toString(10), '-611111124969028'); + }); + + it('should mod numbers', function () { + assert.equal(new BN('10').mod(new BN(256)).toString(16), + 'a'); + assert.equal(new BN('69527932928').mod(new BN('16974594')).toString(16), + '102f302'); + + // 178 = 10 * 17 + 8 + assert.equal(new BN(178).div(new BN(10)).toNumber(), 17); + assert.equal(new BN(178).mod(new BN(10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(10)).toNumber(), 8); + + // -178 = 10 * (-17) + (-8) + assert.equal(new BN(-178).div(new BN(10)).toNumber(), -17); + assert.equal(new BN(-178).mod(new BN(10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(10)).toNumber(), 2); + + // 178 = -10 * (-17) + 8 + assert.equal(new BN(178).div(new BN(-10)).toNumber(), -17); + assert.equal(new BN(178).mod(new BN(-10)).toNumber(), 8); + assert.equal(new BN(178).umod(new BN(-10)).toNumber(), 8); + + // -178 = -10 * (17) + (-8) + assert.equal(new BN(-178).div(new BN(-10)).toNumber(), 17); + assert.equal(new BN(-178).mod(new BN(-10)).toNumber(), -8); + assert.equal(new BN(-178).umod(new BN(-10)).toNumber(), 2); + + // -4 = 1 * (-3) + -1 + assert.equal(new BN(-4).div(new BN(-3)).toNumber(), 1); + assert.equal(new BN(-4).mod(new BN(-3)).toNumber(), -1); + + // -4 = -1 * (3) + -1 + assert.equal(new BN(-4).mod(new BN(3)).toNumber(), -1); + // -4 = 1 * (-3) + (-1 + 3) + assert.equal(new BN(-4).umod(new BN(-3)).toNumber(), 2); + + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'fffffffe00000003fffffffd0000000200000001fffffffe00000002ffffffff' + + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', + 16); + assert.equal( + a.mod(p).toString(16), + '0'); + }); + + it('should properly carry the sign inside division', function () { + var a = new BN('945304eb96065b2a98b57a48a06ae28d285a71b5', 'hex'); + var b = new BN( + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe', + 'hex'); + + assert.equal(a.mul(b).mod(a).cmpn(0), 0); + }); + }); + + describe('.modn()', function () { + it('should act like .mod() on small numbers', function () { + assert.equal(new BN('10', 16).modn(256).toString(16), '10'); + assert.equal(new BN('100', 16).modn(256).toString(16), '0'); + assert.equal(new BN('1001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(256).toString(16), '1'); + assert.equal(new BN('100000000001', 16).modn(257).toString(16), + new BN('100000000001', 16).mod(new BN(257)).toString(16)); + assert.equal(new BN('123456789012', 16).modn(3).toString(16), + new BN('123456789012', 16).mod(new BN(3)).toString(16)); + }); + }); + + describe('.abs()', function () { + it('should return absolute value', function () { + assert.equal(new BN(0x1001).abs().toString(), '4097'); + assert.equal(new BN(-0x1001).abs().toString(), '4097'); + assert.equal(new BN('ffffffff', 16).abs().toString(), '4294967295'); + }); + }); + + describe('.invm()', function () { + it('should invert relatively-prime numbers', function () { + var p = new BN(257); + var a = new BN(3); + var b = a.invm(p); + assert.equal(a.mul(b).mod(p).toString(16), '1'); + + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + a = new BN('deadbeef', 16); + b = a.invm(p192); + assert.equal(a.mul(b).mod(p192).toString(16), '1'); + + // Even base + var phi = new BN('872d9b030ba368706b68932cf07a0e0c', 16); + var e = new BN(65537); + var d = e.invm(phi); + assert.equal(e.mul(d).mod(phi).toString(16), '1'); + + // Even base (take #2) + a = new BN('5'); + b = new BN('6'); + var r = a.invm(b); + assert.equal(r.mul(a).mod(b).toString(16), '1'); + }); + }); + + describe('.gcd()', function () { + it('should return GCD', function () { + assert.equal(new BN(3).gcd(new BN(2)).toString(10), '1'); + assert.equal(new BN(18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(-12)).toString(10), '6'); + assert.equal(new BN(-18).gcd(new BN(0)).toString(10), '18'); + assert.equal(new BN(0).gcd(new BN(-18)).toString(10), '18'); + assert.equal(new BN(2).gcd(new BN(0)).toString(10), '2'); + assert.equal(new BN(0).gcd(new BN(3)).toString(10), '3'); + assert.equal(new BN(0).gcd(new BN(0)).toString(10), '0'); + }); + }); + + describe('.egcd()', function () { + it('should return EGCD', function () { + assert.equal(new BN(3).egcd(new BN(2)).gcd.toString(10), '1'); + assert.equal(new BN(18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(-18).egcd(new BN(12)).gcd.toString(10), '6'); + assert.equal(new BN(0).egcd(new BN(12)).gcd.toString(10), '12'); + }); + it('should not allow 0 input', function () { + assert.throws(function () { + BN(1).egcd(0); + }); + }); + it('should not allow negative input', function () { + assert.throws(function () { + BN(1).egcd(-1); + }); + }); + }); + + describe('BN.max(a, b)', function () { + it('should return maximum', function () { + assert.equal(BN.max(new BN(3), new BN(2)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(3)).toString(16), '3'); + assert.equal(BN.max(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.max(new BN(2), new BN(-2)).toString(16), '2'); + }); + }); + + describe('BN.min(a, b)', function () { + it('should return minimum', function () { + assert.equal(BN.min(new BN(3), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(3)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(2)).toString(16), '2'); + assert.equal(BN.min(new BN(2), new BN(-2)).toString(16), '-2'); + }); + }); + + describe('BN.ineg', function () { + it('shouldn\'t change sign for zero', function () { + assert.equal(new BN(0).ineg().toString(10), '0'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/binary-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/binary-test.js new file mode 100644 index 0000000..b73242c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/binary-test.js @@ -0,0 +1,228 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Binary', function () { + describe('.shl()', function () { + it('should shl numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').shln(45).toString(16), + '206060200000000000000'); + }); + + it('should ushl numbers', function () { + assert.equal(new BN('69527932928').ushln(13).toString(16), + '2060602000000'); + assert.equal(new BN('69527932928').ushln(45).toString(16), + '206060200000000000000'); + }); + }); + + describe('.shr()', function () { + it('should shr numbers', function () { + // TODO(indutny): add negative numbers when the time will come + assert.equal(new BN('69527932928').shrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').shrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').shrn(256).toString(16), + '0'); + }); + + it('should ushr numbers', function () { + assert.equal(new BN('69527932928').ushrn(13).toString(16), + '818180'); + assert.equal(new BN('69527932928').ushrn(17).toString(16), + '81818'); + assert.equal(new BN('69527932928').ushrn(256).toString(16), + '0'); + }); + }); + + describe('.bincn()', function () { + it('should increment bit', function () { + assert.equal(new BN(0).bincn(1).toString(16), '2'); + assert.equal(new BN(2).bincn(1).toString(16), '4'); + assert.equal(new BN(2).bincn(1).bincn(1).toString(16), + new BN(2).bincn(2).toString(16)); + assert.equal(new BN(0xffffff).bincn(1).toString(16), '1000001'); + assert.equal(new BN(2).bincn(63).toString(16), + '8000000000000002'); + }); + }); + + describe('.imaskn()', function () { + it('should mask bits in-place', function () { + assert.equal(new BN(0).imaskn(1).toString(16), '0'); + assert.equal(new BN(3).imaskn(1).toString(16), '1'); + assert.equal(new BN('123456789', 16).imaskn(4).toString(16), '9'); + assert.equal(new BN('123456789', 16).imaskn(16).toString(16), '6789'); + assert.equal(new BN('123456789', 16).imaskn(28).toString(16), '3456789'); + }); + }); + + describe('.testn()', function () { + it('should support test specific bit', function () { + [ + 'ff', + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' + ].forEach(function (hex) { + var bn = new BN(hex, 16); + var bl = bn.bitLength(); + + for (var i = 0; i < bl; ++i) { + assert.equal(bn.testn(i), true); + } + + // test off the end + assert.equal(bn.testn(bl), false); + }); + + var xbits = '01111001010111001001000100011101' + + '11010011101100011000111001011101' + + '10010100111000000001011000111101' + + '01011111001111100100011110000010' + + '01011010100111010001010011000100' + + '01101001011110100001001111100110' + + '001110010111'; + + var x = new BN( + '23478905234580795234378912401239784125643978256123048348957342' + ); + for (var i = 0; i < x.bitLength(); ++i) { + assert.equal(x.testn(i), (xbits.charAt(i) === '1'), 'Failed @ bit ' + i); + } + }); + + it('should have short-cuts', function () { + var x = new BN('abcd', 16); + assert(!x.testn(128)); + }); + }); + + describe('.and()', function () { + it('should and numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .and(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .and(new BN('abcd', 16)).toString(16), + 'abcd'); + }); + }); + + describe('.iand()', function () { + it('should iand numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .iand(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '0'); + assert.equal(new BN('1000000000000000000000000000000000000001', 2) + .iand(new BN('1', 2)) + .toString(2), '1'); + assert.equal(new BN('1', 2) + .iand(new BN('1000000000000000000000000000000000000001', 2)) + .toString(2), '1'); + }); + }); + + describe('.or()', function () { + it('should or numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .or(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + }); + + it('should or numbers of different limb-length', function () { + assert.equal( + new BN('abcd00000000', 16) + .or(new BN('abcd', 16)).toString(16), + 'abcd0000abcd'); + }); + }); + + describe('.ior()', function () { + it('should ior numbers', function () { + assert.equal(new BN('1010101010101010101010101010101010101010', 2) + .ior(new BN('101010101010101010101010101010101010101', 2)) + .toString(2), '1111111111111111111111111111111111111111'); + assert.equal(new BN('1000000000000000000000000000000000000000', 2) + .ior(new BN('1', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + assert.equal(new BN('1', 2) + .ior(new BN('1000000000000000000000000000000000000000', 2)) + .toString(2), '1000000000000000000000000000000000000001'); + }); + }); + + describe('.xor()', function () { + it('should xor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .xor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + }); + }); + + describe('.ixor()', function () { + it('should ixor numbers', function () { + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1100110011001100110011001100110', 2)) + .toString(2), '10101010101010101010101010101010'); + assert.equal(new BN('11001100110011001100110011001100', 2) + .ixor(new BN('1', 2)) + .toString(2), '11001100110011001100110011001101'); + assert.equal(new BN('1', 2) + .ixor(new BN('11001100110011001100110011001100', 2)) + .toString(2), '11001100110011001100110011001101'); + }); + + it('should and numbers of different limb-length', function () { + assert.equal( + new BN('abcd0000ffff', 16) + .xor(new BN('abcd', 16)).toString(16), + 'abcd00005432'); + }); + }); + + describe('.setn()', function () { + it('should allow single bits to be set', function () { + assert.equal(new BN(0).setn(2, true).toString(2), '100'); + assert.equal(new BN(0).setn(27, true).toString(2), + '1000000000000000000000000000'); + assert.equal(new BN(0).setn(63, true).toString(16), + new BN(1).iushln(63).toString(16)); + assert.equal(new BN('1000000000000000000000000001', 2).setn(27, false) + .toString(2), '1'); + assert.equal(new BN('101', 2).setn(2, false).toString(2), '1'); + }); + }); + + describe('.notn()', function () { + it('should allow bitwise negation', function () { + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(9).toString(2), + '111000'); + assert.equal(new BN('000111000', 2).notn(9).toString(2), + '111000111'); + assert.equal(new BN('111000111', 2).notn(32).toString(2), + '11111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(32).toString(2), + '11111111111111111111111111000111'); + assert.equal(new BN('111000111', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111000111000'); + assert.equal(new BN('000111000', 2).notn(68).toString(2), + '11111111111111111111111111111111' + + '111111111111111111111111111111000111'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/constructor-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/constructor-test.js new file mode 100644 index 0000000..bad412b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/constructor-test.js @@ -0,0 +1,149 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Constructor', function () { + describe('with Smi input', function () { + it('should accept one limb number', function () { + assert.equal(new BN(12345).toString(16), '3039'); + }); + + it('should accept two-limb number', function () { + assert.equal(new BN(0x4123456).toString(16), '4123456'); + }); + + it('should accept 52 bits of precision', function () { + var num = Math.pow(2, 52); + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should accept max safe integer', function () { + var num = Math.pow(2, 53) - 1; + assert.equal(new BN(num, 10).toString(10), num.toString(10)); + }); + + it('should not accept an unsafe integer', function () { + var num = Math.pow(2, 53); + + assert.throws(function () { + BN(num, 10); + }); + }); + + it('should accept two-limb LE number', function () { + assert.equal(new BN(0x4123456, null, 'le').toString(16), '56341204'); + }); + }); + + describe('with String input', function () { + it('should accept base-16', function () { + assert.equal(new BN('1A6B765D8CDF', 16).toString(16), '1a6b765d8cdf'); + assert.equal(new BN('1A6B765D8CDF', 16).toString(), '29048849665247'); + }); + + it('should accept base-hex', function () { + assert.equal(new BN('FF', 'hex').toString(), '255'); + }); + + it('should accept base-16 with spaces', function () { + var num = 'a89c e5af8724 c0a23e0e 0ff77500'; + assert.equal(new BN(num, 16).toString(16), num.replace(/ /g, '')); + }); + + it('should accept long base-16', function () { + var num = '123456789abcdef123456789abcdef123456789abcdef'; + assert.equal(new BN(num, 16).toString(16), num); + }); + + it('should accept positive base-10', function () { + assert.equal(new BN('10654321').toString(), '10654321'); + assert.equal(new BN('29048849665247').toString(16), '1a6b765d8cdf'); + }); + + it('should accept negative base-10', function () { + assert.equal(new BN('-29048849665247').toString(16), '-1a6b765d8cdf'); + }); + + it('should accept long base-10', function () { + var num = '10000000000000000'; + assert.equal(new BN(num).toString(10), num); + }); + + it('should accept base-2', function () { + var base2 = '11111111111111111111111111111111111111111111111111111'; + assert.equal(new BN(base2, 2).toString(2), base2); + }); + + it('should accept base-36', function () { + var base36 = 'zzZzzzZzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'; + assert.equal(new BN(base36, 36).toString(36), base36.toLowerCase()); + }); + + it('should not overflow limbs during base-10', function () { + var num = '65820182292848241686198767302293' + + '20890292528855852623664389292032'; + assert(new BN(num).words[0] < 0x4000000); + }); + + it('should accept base-16 LE integer', function () { + assert.equal(new BN('1A6B765D8CDF', 16, 'le').toString(16), + 'df8c5d766b1a'); + }); + }); + + describe('with Array input', function () { + it('should not fail on empty array', function () { + assert.equal(new BN([]).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN([ 1, 2, 3 ]).toString(16), '10203'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toString(16), '1020304'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ]).toString(16), '102030405'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toString(16), + '102030405060708'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray().join(','), '1,2,3,4'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray().join(','), + '1,2,3,4,5,6,7,8'); + }); + + it('should import little endian', function () { + assert.equal(new BN([ 1, 2, 3 ], 10, 'le').toString(16), '30201'); + assert.equal(new BN([ 1, 2, 3, 4 ], 10, 'le').toString(16), '4030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 10, 'le').toString(16), + '504030201'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ], 'le').toString(16), + '807060504030201'); + assert.equal(new BN([ 1, 2, 3, 4 ]).toArray('le').join(','), '4,3,2,1'); + assert.equal(new BN([ 1, 2, 3, 4, 5, 6, 7, 8 ]).toArray('le').join(','), + '8,7,6,5,4,3,2,1'); + }); + + it('should import big endian with implicit base', function () { + assert.equal(new BN([ 1, 2, 3, 4, 5 ], 'le').toString(16), '504030201'); + }); + }); + + // the Array code is able to handle Buffer + describe('with Buffer input', function () { + it('should not fail on empty Buffer', function () { + assert.equal(new BN(new Buffer(0)).toString(16), '0'); + }); + + it('should import/export big endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex')).toString(16), '10203'); + }); + + it('should import little endian', function () { + assert.equal(new BN(new Buffer('010203', 'hex'), 'le').toString(16), '30201'); + }); + }); + + describe('with BN input', function () { + it('should clone BN', function () { + var num = new BN(12345); + assert.equal(new BN(num).toString(10), '12345'); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/fixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/fixtures.js new file mode 100644 index 0000000..39fd661 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/fixtures.js @@ -0,0 +1,264 @@ +exports.dhGroups = { + p16: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199' + + 'ffffffffffffffff', + priv: '6d5923e6449122cbbcc1b96093e0b7e4fd3e469f58daddae' + + '53b49b20664f4132675df9ce98ae0cfdcac0f4181ccb643b' + + '625f98104dcf6f7d8e81961e2cab4b5014895260cb977c7d' + + '2f981f8532fb5da60b3676dfe57f293f05d525866053ac7e' + + '65abfd19241146e92e64f309a97ef3b529af4d6189fa416c' + + '9e1a816c3bdf88e5edf48fbd8233ef9038bb46faa95122c0' + + '5a426be72039639cd2d53d37254b3d258960dcb33c255ede' + + '20e9d7b4b123c8b4f4b986f53cdd510d042166f7dd7dca98' + + '7c39ab36381ba30a5fdd027eb6128d2ef8e5802a2194d422' + + 'b05fe6e1cb4817789b923d8636c1ec4b7601c90da3ddc178' + + '52f59217ae070d87f2e75cbfb6ff92430ad26a71c8373452' + + 'ae1cc5c93350e2d7b87e0acfeba401aaf518580937bf0b6c' + + '341f8c49165a47e49ce50853989d07171c00f43dcddddf72' + + '94fb9c3f4e1124e98ef656b797ef48974ddcd43a21fa06d0' + + '565ae8ce494747ce9e0ea0166e76eb45279e5c6471db7df8' + + 'cc88764be29666de9c545e72da36da2f7a352fb17bdeb982' + + 'a6dc0193ec4bf00b2e533efd6cd4d46e6fb237b775615576' + + 'dd6c7c7bbc087a25e6909d1ebc6e5b38e5c8472c0fc429c6' + + 'f17da1838cbcd9bbef57c5b5522fd6053e62ba21fe97c826' + + 'd3889d0cc17e5fa00b54d8d9f0f46fb523698af965950f4b' + + '941369e180f0aece3870d9335f2301db251595d173902cad' + + '394eaa6ffef8be6c', + pub: 'd53703b7340bc89bfc47176d351e5cf86d5a18d9662eca3c' + + '9759c83b6ccda8859649a5866524d77f79e501db923416ca' + + '2636243836d3e6df752defc0fb19cc386e3ae48ad647753f' + + 'bf415e2612f8a9fd01efe7aca249589590c7e6a0332630bb' + + '29c5b3501265d720213790556f0f1d114a9e2071be3620bd' + + '4ee1e8bb96689ac9e226f0a4203025f0267adc273a43582b' + + '00b70b490343529eaec4dcff140773cd6654658517f51193' + + '13f21f0a8e04fe7d7b21ffeca85ff8f87c42bb8d9cb13a72' + + 'c00e9c6e9dfcedda0777af951cc8ccab90d35e915e707d8e' + + '4c2aca219547dd78e9a1a0730accdc9ad0b854e51edd1e91' + + '4756760bab156ca6e3cb9c625cf0870def34e9ac2e552800' + + 'd6ce506d43dbbc75acfa0c8d8fb12daa3c783fb726f187d5' + + '58131779239c912d389d0511e0f3a81969d12aeee670e48f' + + 'ba41f7ed9f10705543689c2506b976a8ffabed45e33795b0' + + '1df4f6b993a33d1deab1316a67419afa31fbb6fdd252ee8c' + + '7c7d1d016c44e3fcf6b41898d7f206aa33760b505e4eff2e' + + 'c624bc7fe636b1d59e45d6f904fc391419f13d1f0cdb5b6c' + + '2378b09434159917dde709f8a6b5dc30994d056e3f964371' + + '11587ac7af0a442b8367a7bd940f752ddabf31cf01171e24' + + 'd78df136e9681cd974ce4f858a5fb6efd3234a91857bb52d' + + '9e7b414a8bc66db4b5a73bbeccfb6eb764b4f0cbf0375136' + + 'b024b04e698d54a5' + }, + p17: { + prime: 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd1' + + '29024e088a67cc74020bbea63b139b22514a08798e3404dd' + + 'ef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245' + + 'e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed' + + 'ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3d' + + 'c2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f' + + '83655d23dca3ad961c62f356208552bb9ed529077096966d' + + '670c354e4abc9804f1746c08ca18217c32905e462e36ce3b' + + 'e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9' + + 'de2bcbf6955817183995497cea956ae515d2261898fa0510' + + '15728e5a8aaac42dad33170d04507a33a85521abdf1cba64' + + 'ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7' + + 'abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6b' + + 'f12ffa06d98a0864d87602733ec86a64521f2b18177b200c' + + 'bbe117577a615d6c770988c0bad946e208e24fa074e5ab31' + + '43db5bfce0fd108e4b82d120a92108011a723c12a787e6d7' + + '88719a10bdba5b2699c327186af4e23c1a946834b6150bda' + + '2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6' + + '287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed' + + '1f612970cee2d7afb81bdd762170481cd0069127d5b05aa9' + + '93b4ea988d8fddc186ffb7dc90a6c08f4df435c934028492' + + '36c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bd' + + 'f8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831' + + '179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1b' + + 'db7f1447e6cc254b332051512bd7af426fb8f401378cd2bf' + + '5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6' + + 'd55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f3' + + '23a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aa' + + 'cc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be328' + + '06a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55c' + + 'da56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee' + + '12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff', + priv: '6017f2bc23e1caff5b0a8b4e1fc72422b5204415787801dc' + + '025762b8dbb98ab57603aaaa27c4e6bdf742b4a1726b9375' + + 'a8ca3cf07771779589831d8bd18ddeb79c43e7e77d433950' + + 'e652e49df35b11fa09644874d71d62fdaffb580816c2c88c' + + '2c4a2eefd4a660360316741b05a15a2e37f236692ad3c463' + + 'fff559938fc6b77176e84e1bb47fb41af691c5eb7bb81bd8' + + 'c918f52625a1128f754b08f5a1403b84667231c4dfe07ed4' + + '326234c113931ce606037e960f35a2dfdec38a5f057884d3' + + '0af8fab3be39c1eeb390205fd65982191fc21d5aa30ddf51' + + 'a8e1c58c0c19fc4b4a7380ea9e836aaf671c90c29bc4bcc7' + + '813811aa436a7a9005de9b507957c56a9caa1351b6efc620' + + '7225a18f6e97f830fb6a8c4f03b82f4611e67ab9497b9271' + + 'd6ac252793cc3e5538990dbd894d2dbc2d152801937d9f74' + + 'da4b741b50b4d40e4c75e2ac163f7b397fd555648b249f97' + + 'ffe58ffb6d096aa84534c4c5729cff137759bd34e80db4ab' + + '47e2b9c52064e7f0bf677f72ac9e5d0c6606943683f9d12f' + + '180cf065a5cb8ec3179a874f358847a907f8471d15f1e728' + + '7023249d6d13c82da52628654438f47b8b5cdf4761fbf6ad' + + '9219eceac657dbd06cf2ab776ad4c968f81c3d039367f0a4' + + 'd77c7ec4435c27b6c147071665100063b5666e06eb2fb2cc' + + '3159ba34bc98ca346342195f6f1fb053ddc3bc1873564d40' + + '1c6738cdf764d6e1ff25ca5926f80102ea6593c17170966b' + + 'b5d7352dd7fb821230237ea3ebed1f920feaadbd21be295a' + + '69f2083deae9c5cdf5f4830eb04b7c1f80cc61c17232d79f' + + '7ecc2cc462a7965f804001c89982734e5abba2d31df1b012' + + '152c6b226dff34510b54be8c2cd68d795def66c57a3abfb6' + + '896f1d139e633417f8c694764974d268f46ece3a8d6616ea' + + 'a592144be48ee1e0a1595d3e5edfede5b27cec6c48ceb2ff' + + 'b42cb44275851b0ebf87dfc9aa2d0cb0805e9454b051dfe8' + + 'a29fadd82491a4b4c23f2d06ba45483ab59976da1433c9ce' + + '500164b957a04cf62dd67595319b512fc4b998424d1164dd' + + 'bbe5d1a0f7257cbb04ec9b5ed92079a1502d98725023ecb2', + pub: '3bf836229c7dd874fe37c1790d201e82ed8e192ed61571ca' + + '7285264974eb2a0171f3747b2fc23969a916cbd21e14f7e2' + + 'f0d72dcd2247affba926f9e7bb99944cb5609aed85e71b89' + + 'e89d2651550cb5bd8281bd3144066af78f194032aa777739' + + 'cccb7862a1af401f99f7e5c693f25ddce2dedd9686633820' + + 'd28d0f5ed0c6b5a094f5fe6170b8e2cbc9dff118398baee6' + + 'e895a6301cb6e881b3cae749a5bdf5c56fc897ff68bc73f2' + + '4811bb108b882872bade1f147d886a415cda2b93dd90190c' + + 'be5c2dd53fe78add5960e97f58ff2506afe437f4cf4c912a' + + '397c1a2139ac6207d3ab76e6b7ffd23bb6866dd7f87a9ae5' + + '578789084ff2d06ea0d30156d7a10496e8ebe094f5703539' + + '730f5fdbebc066de417be82c99c7da59953071f49da7878d' + + 'a588775ff2a7f0084de390f009f372af75cdeba292b08ea8' + + '4bd13a87e1ca678f9ad148145f7cef3620d69a891be46fbb' + + 'cad858e2401ec0fd72abdea2f643e6d0197b7646fbb83220' + + '0f4cf7a7f6a7559f9fb0d0f1680822af9dbd8dec4cd1b5e1' + + '7bc799e902d9fe746ddf41da3b7020350d3600347398999a' + + 'baf75d53e03ad2ee17de8a2032f1008c6c2e6618b62f225b' + + 'a2f350179445debe68500fcbb6cae970a9920e321b468b74' + + '5fb524fb88abbcacdca121d737c44d30724227a99745c209' + + 'b970d1ff93bbc9f28b01b4e714d6c9cbd9ea032d4e964d8e' + + '8fff01db095160c20b7646d9fcd314c4bc11bcc232aeccc0' + + 'fbedccbc786951025597522eef283e3f56b44561a0765783' + + '420128638c257e54b972a76e4261892d81222b3e2039c61a' + + 'ab8408fcaac3d634f848ab3ee65ea1bd13c6cd75d2e78060' + + 'e13cf67fbef8de66d2049e26c0541c679fff3e6afc290efe' + + '875c213df9678e4a7ec484bc87dae5f0a1c26d7583e38941' + + 'b7c68b004d4df8b004b666f9448aac1cc3ea21461f41ea5d' + + 'd0f7a9e6161cfe0f58bcfd304bdc11d78c2e9d542e86c0b5' + + '6985cc83f693f686eaac17411a8247bf62f5ccc7782349b5' + + 'cc1f20e312fa2acc0197154d1bfee507e8db77e8f2732f2d' + + '641440ccf248e8643b2bd1e1f9e8239356ab91098fcb431d', + q: 'a899c59999bf877d96442d284359783bdc64b5f878b688fe' + + '51407f0526e616553ad0aaaac4d5bed3046f10a1faaf42bb' + + '2342dc4b7908eea0c46e4c4576897675c2bfdc4467870d3d' + + 'cd90adaed4359237a4bc6924bfb99aa6bf5f5ede15b574ea' + + 'e977eac096f3c67d09bda574c6306c6123fa89d2f086b8dc' + + 'ff92bc570c18d83fe6c810ccfd22ce4c749ef5e6ead3fffe' + + 'c63d95e0e3fde1df9db6a35fa1d107058f37e41957769199' + + 'd945dd7a373622c65f0af3fd9eb1ddc5c764bbfaf7a3dc37' + + '2548e683b970dac4aa4b9869080d2376c9adecebb84e172c' + + '09aeeb25fb8df23e60033260c4f8aac6b8b98ab894b1fb84' + + 'ebb83c0fb2081c3f3eee07f44e24d8fabf76f19ed167b0d7' + + 'ff971565aa4efa3625fce5a43ceeaa3eebb3ce88a00f597f' + + '048c69292b38dba2103ecdd5ec4ccfe3b2d87fa6202f334b' + + 'c1cab83b608dfc875b650b69f2c7e23c0b2b4adf149a6100' + + 'db1b6dbad4679ecb1ea95eafaba3bd00db11c2134f5a8686' + + '358b8b2ab49a1b2e85e1e45caeac5cd4dc0b3b5fffba8871' + + '1c6baf399edd48dad5e5c313702737a6dbdcede80ca358e5' + + '1d1c4fe42e8948a084403f61baed38aa9a1a5ce2918e9f33' + + '100050a430b47bc592995606440272a4994677577a6aaa1b' + + 'a101045dbec5a4e9566dab5445d1af3ed19519f07ac4e2a8' + + 'bd0a84b01978f203a9125a0be020f71fab56c2c9e344d4f4' + + '12d53d3cd8eb74ca5122002e931e3cb0bd4b7492436be17a' + + 'd7ebe27148671f59432c36d8c56eb762655711cfc8471f70' + + '83a8b7283bcb3b1b1d47d37c23d030288cfcef05fbdb4e16' + + '652ee03ee7b77056a808cd700bc3d9ef826eca9a59be959c' + + '947c865d6b372a1ca2d503d7df6d7611b12111665438475a' + + '1c64145849b3da8c2d343410df892d958db232617f9896f1' + + 'de95b8b5a47132be80dd65298c7f2047858409bf762dbc05' + + 'a62ca392ac40cfb8201a0607a2cae07d99a307625f2b2d04' + + 'fe83fbd3ab53602263410f143b73d5b46fc761882e78c782' + + 'd2c36e716a770a7aefaf7f76cea872db7bffefdbc4c2f9e0' + + '39c19adac915e7a63dcb8c8c78c113f29a3e0bc10e100ce0', + qs: '6f0a2fb763eaeb8eb324d564f03d4a55fdcd709e5f1b65e9' + + '5702b0141182f9f945d71bc3e64a7dfdae7482a7dd5a4e58' + + 'bc38f78de2013f2c468a621f08536969d2c8d011bb3bc259' + + '2124692c91140a5472cad224acdacdeae5751dadfdf068b8' + + '77bfa7374694c6a7be159fc3d24ff9eeeecaf62580427ad8' + + '622d48c51a1c4b1701d768c79d8c819776e096d2694107a2' + + 'f3ec0c32224795b59d32894834039dacb369280afb221bc0' + + '90570a93cf409889b818bb30cccee98b2aa26dbba0f28499' + + '08e1a3cd43fa1f1fb71049e5c77c3724d74dc351d9989057' + + '37bbda3805bd6b1293da8774410fb66e3194e18cdb304dd9' + + 'a0b59b583dcbc9fc045ac9d56aea5cfc9f8a0b95da1e11b7' + + '574d1f976e45fe12294997fac66ca0b83fc056183549e850' + + 'a11413cc4abbe39a211e8c8cbf82f2a23266b3c10ab9e286' + + '07a1b6088909cddff856e1eb6b2cde8bdac53fa939827736' + + 'ca1b892f6c95899613442bd02dbdb747f02487718e2d3f22' + + 'f73734d29767ed8d0e346d0c4098b6fdcb4df7d0c4d29603' + + '5bffe80d6c65ae0a1b814150d349096baaf950f2caf298d2' + + 'b292a1d48cf82b10734fe8cedfa16914076dfe3e9b51337b' + + 'ed28ea1e6824bb717b641ca0e526e175d3e5ed7892aebab0' + + 'f207562cc938a821e2956107c09b6ce4049adddcd0b7505d' + + '49ae6c69a20122461102d465d93dc03db026be54c303613a' + + 'b8e5ce3fd4f65d0b6162ff740a0bf5469ffd442d8c509cd2' + + '3b40dab90f6776ca17fc0678774bd6eee1fa85ababa52ec1' + + 'a15031eb677c6c488661dddd8b83d6031fe294489ded5f08' + + '8ad1689a14baeae7e688afa3033899c81f58de39b392ca94' + + 'af6f15a46f19fa95c06f9493c8b96a9be25e78b9ea35013b' + + 'caa76de6303939299d07426a88a334278fc3d0d9fa71373e' + + 'be51d3c1076ab93a11d3d0d703366ff8cde4c11261d488e5' + + '60a2bdf3bfe2476032294800d6a4a39d306e65c6d7d8d66e' + + '5ec63eee94531e83a9bddc458a2b508285c0ee10b7bd94da' + + '2815a0c5bd5b2e15cbe66355e42f5af8955cdfc0b3a4996d' + + '288db1f4b32b15643b18193e378cb7491f3c3951cdd044b1' + + 'a519571bffac2da986f5f1d506c66530a55f70751e24fa8e' + + 'd83ac2347f4069fb561a5565e78c6f0207da24e889a93a96' + + '65f717d9fe8a2938a09ab5f81be7ccecf466c0397fc15a57' + + '469939793f302739765773c256a3ca55d0548afd117a7cae' + + '98ca7e0d749a130c7b743d376848e255f8fdbe4cb4480b63' + + 'cd2c015d1020cf095d175f3ca9dcdfbaf1b2a6e6468eee4c' + + 'c750f2132a77f376bd9782b9d0ff4da98621b898e251a263' + + '4301ba2214a8c430b2f7a79dbbfd6d7ff6e9b0c137b025ff' + + '587c0bf912f0b19d4fff96b1ecd2ca990c89b386055c60f2' + + '3b94214bd55096f17a7b2c0fa12b333235101cd6f28a128c' + + '782e8a72671adadebbd073ded30bd7f09fb693565dcf0bf3' + + '090c21d13e5b0989dd8956f18f17f4f69449a13549c9d80a' + + '77e5e61b5aeeee9528634100e7bc390672f0ded1ca53555b' + + 'abddbcf700b9da6192255bddf50a76b709fbed251dce4c7e' + + '1ca36b85d1e97c1bc9d38c887a5adf140f9eeef674c31422' + + 'e65f63cae719f8c1324e42fa5fd8500899ef5aa3f9856aa7' + + 'ce10c85600a040343204f36bfeab8cfa6e9deb8a2edd2a8e' + + '018d00c7c9fa3a251ad0f57183c37e6377797653f382ec7a' + + '2b0145e16d3c856bc3634b46d90d7198aff12aff88a30e34' + + 'e2bfaf62705f3382576a9d3eeb0829fca2387b5b654af46e' + + '5cf6316fb57d59e5ea6c369061ac64d99671b0e516529dd5' + + 'd9c48ea0503e55fee090d36c5ea8b5954f6fcc0060794e1c' + + 'b7bc24aa1e5c0142fd4ce6e8fd5aa92a7bf84317ea9e1642' + + 'b6995bac6705adf93cbce72433ed0871139970d640f67b78' + + 'e63a7a6d849db2567df69ac7d79f8c62664ac221df228289' + + 'd0a4f9ebd9acb4f87d49da64e51a619fd3f3baccbd9feb12' + + '5abe0cc2c8d17ed1d8546da2b6c641f4d3020a5f9b9f26ac' + + '16546c2d61385505612275ea344c2bbf1ce890023738f715' + + '5e9eba6a071678c8ebd009c328c3eb643679de86e69a9fa5' + + '67a9e146030ff03d546310a0a568c5ba0070e0da22f2cef8' + + '54714b04d399bbc8fd261f9e8efcd0e83bdbc3f5cfb2d024' + + '3e398478cc598e000124eb8858f9df8f52946c2a1ca5c400' + } +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/pummel/dh-group-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/pummel/dh-group-test.js new file mode 100644 index 0000000..37a259f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/pummel/dh-group-test.js @@ -0,0 +1,23 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../../').BN; +var fixtures = require('../fixtures'); + +describe('BN.js/Slow DH test', function () { + var groups = fixtures.dhGroups; + Object.keys(groups).forEach(function (name) { + it('should match public key for ' + name + ' group', function () { + var group = groups[name]; + + this.timeout(3600 * 1000); + + var base = new BN(2); + var mont = BN.red(new BN(group.prime, 16)); + var priv = new BN(group.priv, 16); + var multed = base.toRed(mont).redPow(priv).fromRed(); + var actual = new Buffer(multed.toArray()); + assert.equal(actual.toString('hex'), group.pub); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/red-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/red-test.js new file mode 100644 index 0000000..5f78b83 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/red-test.js @@ -0,0 +1,249 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Reduction context', function () { + function testMethod (name, fn) { + describe(name + ' method', function () { + it('should support add, iadd, sub, isub operations', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(123).toRed(m); + var b = new BN(231).toRed(m); + + assert.equal(a.redAdd(b).fromRed().toString(10), '97'); + assert.equal(a.redSub(b).fromRed().toString(10), '149'); + assert.equal(b.redSub(a).fromRed().toString(10), '108'); + + assert.equal(a.clone().redIAdd(b).fromRed().toString(10), '97'); + assert.equal(a.clone().redISub(b).fromRed().toString(10), '149'); + assert.equal(b.clone().redISub(a).fromRed().toString(10), '108'); + }); + + it('should support pow and mul operations', function () { + var p192 = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p192); + var a = new BN(123); + var b = new BN(231); + var c = a.toRed(m).redMul(b.toRed(m)).fromRed(); + assert(c.cmp(a.mul(b).mod(p192)) === 0); + + assert.equal(a.toRed(m).redPow(new BN(3)).fromRed() + .cmp(a.sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(4)).fromRed() + .cmp(a.sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(8)).fromRed() + .cmp(a.sqr().sqr().sqr()), 0); + assert.equal(a.toRed(m).redPow(new BN(9)).fromRed() + .cmp(a.sqr().sqr().sqr().mul(a)), 0); + assert.equal(a.toRed(m).redPow(new BN(17)).fromRed() + .cmp(a.sqr().sqr().sqr().sqr().mul(a)), 0); + assert.equal( + a.toRed(m).redPow(new BN('deadbeefabbadead', 16)).fromRed() + .toString(16), + '3aa0e7e304e320b68ef61592bcb00341866d6fa66e11a4d6'); + }); + + it('should sqrtm numbers', function () { + var p = new BN(263); + var m = fn(p); + var q = new BN(11).toRed(m); + + var qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + m = fn(p); + + q = new BN(13).toRed(m); + qr = q.redSqrt(true, p); + assert.equal(qr.redSqr().cmp(q), 0); + + qr = q.redSqrt(false, p); + assert.equal(qr.redSqr().cmp(q), 0); + + // Tonelli-shanks + p = new BN(13); + m = fn(p); + q = new BN(10).toRed(m); + assert.equal(q.redSqrt().fromRed().toString(10), '7'); + }); + + it('should invm numbers', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(3).toRed(m); + var b = a.redInvm(); + assert.equal(a.redMul(b).fromRed().toString(16), '1'); + }); + + it('should invm numbers (regression)', function () { + var p = new BN( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + 16); + var a = new BN( + 'e1d969b8192fbac73ea5b7921896d6a2263d4d4077bb8e5055361d1f7f8163f3', + 16); + + var m = fn(p); + a = a.toRed(m); + + assert.equal(a.redInvm().fromRed().negative, 0); + }); + + it('should imul numbers', function () { + var p = new BN( + 'fffffffffffffffffffffffffffffffeffffffffffffffff', + 16); + var m = fn(p); + + var a = new BN('deadbeefabbadead', 16); + var b = new BN('abbadeadbeefdead', 16); + var c = a.mul(b).mod(p); + + assert.equal(a.toRed(m).redIMul(b.toRed(m)).fromRed().toString(16), + c.toString(16)); + }); + + it('should pow(base, 0) == 1', function () { + var base = new BN(256).toRed(BN.red('k256')); + var exponent = new BN(0); + var result = base.redPow(exponent); + assert.equal(result.toString(), '1'); + }); + + it('should shl numbers', function () { + var base = new BN(256).toRed(BN.red('k256')); + var result = base.redShl(1); + assert.equal(result.toString(), '512'); + }); + + it('should reduce when converting to red', function () { + var p = new BN(257); + var m = fn(p); + var a = new BN(5).toRed(m); + + assert.doesNotThrow(function () { + var b = a.redISub(new BN(512).toRed(m)); + b.redISub(new BN(512).toRed(m)); + }); + }); + + it('redNeg and zero value', function () { + var a = new BN(0).toRed(BN.red('k256')).redNeg(); + assert.equal(a.isZero(), true); + }); + }); + } + + testMethod('Plain', BN.red); + testMethod('Montgomery', BN.mont); + + describe('Pseudo-Mersenne Primes', function () { + it('should reduce numbers mod k256', function () { + var p = BN._prime('k256'); + + assert.equal(p.ireduce(new BN(0xdead)).toString(16), 'dead'); + assert.equal(p.ireduce(new BN('deadbeef', 16)).toString(16), 'deadbeef'); + + var num = new BN('fedcba9876543210fedcba9876543210dead' + + 'fedcba9876543210fedcba9876543210dead', + 16); + var exp = num.mod(p.p).toString(16); + assert.equal(p.ireduce(num).toString(16), exp); + + var regr = new BN('f7e46df64c1815962bf7bc9c56128798' + + '3f4fcef9cb1979573163b477eab93959' + + '335dfb29ef07a4d835d22aa3b6797760' + + '70a8b8f59ba73d56d01a79af9', + 16); + exp = regr.mod(p.p).toString(16); + + assert.equal(p.ireduce(regr).toString(16), exp); + }); + + it('should not fail to invm number mod k256', function () { + var regr2 = new BN( + '6c150c4aa9a8cf1934485d40674d4a7cd494675537bda36d49405c5d2c6f496f', 16); + regr2 = regr2.toRed(BN.red('k256')); + assert.equal(regr2.redInvm().redMul(regr2).fromRed().cmpn(1), 0); + }); + + it('should correctly square the number', function () { + var p = BN._prime('k256').p; + var red = BN.red('k256'); + + var n = new BN('9cd8cb48c3281596139f147c1364a3ed' + + 'e88d3f310fdb0eb98c924e599ca1b3c9', + 16); + var expected = n.sqr().mod(p); + var actual = n.toRed(red).redSqr().fromRed(); + + assert.equal(actual.toString(16), expected.toString(16)); + }); + + it('redISqr should return right result', function () { + var n = new BN('30f28939', 16); + var actual = n.toRed(BN.red('k256')).redISqr().fromRed(); + assert.equal(actual.toString(16), '95bd93d19520eb1'); + }); + }); + + it('should avoid 4.1.0 regresion', function () { + function bits2int (obits, q) { + var bits = new BN(obits); + var shift = (obits.length << 3) - q.bitLength(); + if (shift > 0) { + bits.ishrn(shift); + } + return bits; + } + var t = new Buffer('aff1651e4cd6036d57aa8b2a05ccf1a9d5a40166340ecbbdc55' + + 'be10b568aa0aa3d05ce9a2fcec9df8ed018e29683c6051cb83e' + + '46ce31ba4edb045356a8d0d80b', 'hex'); + var g = new BN('5c7ff6b06f8f143fe8288433493e4769c4d988ace5be25a0e24809670' + + '716c613d7b0cee6932f8faa7c44d2cb24523da53fbe4f6ec3595892d1' + + 'aa58c4328a06c46a15662e7eaa703a1decf8bbb2d05dbe2eb956c142a' + + '338661d10461c0d135472085057f3494309ffa73c611f78b32adbb574' + + '0c361c9f35be90997db2014e2ef5aa61782f52abeb8bd6432c4dd097b' + + 'c5423b285dafb60dc364e8161f4a2a35aca3a10b1c4d203cc76a470a3' + + '3afdcbdd92959859abd8b56e1725252d78eac66e71ba9ae3f1dd24871' + + '99874393cd4d832186800654760e1e34c09e4d155179f9ec0dc4473f9' + + '96bdce6eed1cabed8b6f116f7ad9cf505df0f998e34ab27514b0ffe7', + 16); + var p = new BN('9db6fb5951b66bb6fe1e140f1d2ce5502374161fd6538df1648218642' + + 'f0b5c48c8f7a41aadfa187324b87674fa1822b00f1ecf8136943d7c55' + + '757264e5a1a44ffe012e9936e00c1d3e9310b01c7d179805d3058b2a9' + + 'f4bb6f9716bfe6117c6b5b3cc4d9be341104ad4a80ad6c94e005f4b99' + + '3e14f091eb51743bf33050c38de235567e1b34c3d6a5c0ceaa1a0f368' + + '213c3d19843d0b4b09dcb9fc72d39c8de41f1bf14d4bb4563ca283716' + + '21cad3324b6a2d392145bebfac748805236f5ca2fe92b871cd8f9c36d' + + '3292b5509ca8caa77a2adfc7bfd77dda6f71125a7456fea153e433256' + + 'a2261c6a06ed3693797e7995fad5aabbcfbe3eda2741e375404ae25b', + 16); + var q = new BN('f2c3119374ce76c9356990b465374a17f23f9ed35089bd969f61c6dde' + + '9998c1f', 16); + var k = bits2int(t, q); + var expectedR = '89ec4bb1400eccff8e7d9aa515cd1de7803f2daff09693ee7fd1353e' + + '90a68307'; + var r = g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); + assert.equal(r.toString(16), expectedR); + }); + + it('K256.split for 512 bits number should return equal numbers', function () { + var red = BN.red('k256'); + var input = new BN(1).iushln(512).subn(1); + assert.equal(input.bitLength(), 512); + var output = new BN(0); + red.prime.split(input, output); + assert.equal(input.cmp(output), 0); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/utils-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/utils-test.js new file mode 100644 index 0000000..f51ce4b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/test/utils-test.js @@ -0,0 +1,345 @@ +/* global describe, it */ + +var assert = require('assert'); +var BN = require('../').BN; + +describe('BN.js/Utils', function () { + describe('.toString()', function () { + describe('binary padding', function () { + it('should have a length of 256', function () { + var a = new BN(0); + + assert.equal(a.toString(2, 256).length, 256); + }); + }); + describe('hex padding', function () { + it('should have length of 8 from leading 15', function () { + var a = new BN('ffb9602', 16); + + assert.equal(a.toString('hex', 2).length, 8); + }); + + it('should have length of 8 from leading zero', function () { + var a = new BN('fb9604', 16); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 8 from leading zeros', function () { + var a = new BN(0); + + assert.equal(a.toString('hex', 8).length, 8); + }); + + it('should have length of 64 from leading 15', function () { + var a = new BN( + 'ffb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 2).length, 64); + }); + + it('should have length of 64 from leading zero', function () { + var a = new BN( + 'fb96ff654e61130ba8422f0debca77a0ea74ae5ea8bca9b54ab64aabf01003', + 16); + + assert.equal(a.toString('hex', 64).length, 64); + }); + }); + }); + + describe('.isNeg()', function () { + it('should return true for negative numbers', function () { + assert.equal(new BN(-1).isNeg(), true); + assert.equal(new BN(1).isNeg(), false); + assert.equal(new BN(0).isNeg(), false); + assert.equal(new BN('-0', 10).isNeg(), false); + }); + }); + + describe('.isOdd()', function () { + it('should return true for odd numbers', function () { + assert.equal(new BN(0).isOdd(), false); + assert.equal(new BN(1).isOdd(), true); + assert.equal(new BN(2).isOdd(), false); + assert.equal(new BN('-0', 10).isOdd(), false); + assert.equal(new BN('-1', 10).isOdd(), true); + assert.equal(new BN('-2', 10).isOdd(), false); + }); + }); + + describe('.isEven()', function () { + it('should return true for even numbers', function () { + assert.equal(new BN(0).isEven(), true); + assert.equal(new BN(1).isEven(), false); + assert.equal(new BN(2).isEven(), true); + assert.equal(new BN('-0', 10).isEven(), true); + assert.equal(new BN('-1', 10).isEven(), false); + assert.equal(new BN('-2', 10).isEven(), true); + }); + }); + + describe('.isZero()', function () { + it('should return true for zero', function () { + assert.equal(new BN(0).isZero(), true); + assert.equal(new BN(1).isZero(), false); + assert.equal(new BN(0xffffffff).isZero(), false); + }); + }); + + describe('.bitLength()', function () { + it('should return proper bitLength', function () { + assert.equal(new BN(0).bitLength(), 0); + assert.equal(new BN(0x1).bitLength(), 1); + assert.equal(new BN(0x2).bitLength(), 2); + assert.equal(new BN(0x3).bitLength(), 2); + assert.equal(new BN(0x4).bitLength(), 3); + assert.equal(new BN(0x8).bitLength(), 4); + assert.equal(new BN(0x10).bitLength(), 5); + assert.equal(new BN(0x100).bitLength(), 9); + assert.equal(new BN(0x123456).bitLength(), 21); + assert.equal(new BN('123456789', 16).bitLength(), 33); + assert.equal(new BN('8023456789', 16).bitLength(), 40); + }); + }); + + describe('.byteLength()', function () { + it('should return proper byteLength', function () { + assert.equal(new BN(0).byteLength(), 0); + assert.equal(new BN(0x1).byteLength(), 1); + assert.equal(new BN(0x2).byteLength(), 1); + assert.equal(new BN(0x3).byteLength(), 1); + assert.equal(new BN(0x4).byteLength(), 1); + assert.equal(new BN(0x8).byteLength(), 1); + assert.equal(new BN(0x10).byteLength(), 1); + assert.equal(new BN(0x100).byteLength(), 2); + assert.equal(new BN(0x123456).byteLength(), 3); + assert.equal(new BN('123456789', 16).byteLength(), 5); + assert.equal(new BN('8023456789', 16).byteLength(), 5); + }); + }); + + describe('.toArray()', function () { + it('should return [ 0 ] for `0`', function () { + var n = new BN(0); + assert.deepEqual(n.toArray('be'), [ 0 ]); + assert.deepEqual(n.toArray('le'), [ 0 ]); + }); + + it('should zero pad to desired lengths', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toArray('be', 5), [ 0x00, 0x00, 0x12, 0x34, 0x56 ]); + assert.deepEqual(n.toArray('le', 5), [ 0x56, 0x34, 0x12, 0x00, 0x00 ]); + }); + + it('should throw when naturally larger than desired length', function () { + var n = new BN(0x123456); + assert.throws(function () { + n.toArray('be', 2); + }); + }); + }); + + describe('.toBuffer', function () { + it('should return proper Buffer', function () { + var n = new BN(0x123456); + assert.deepEqual(n.toBuffer('be', 5).toString('hex'), '0000123456'); + assert.deepEqual(n.toBuffer('le', 5).toString('hex'), '5634120000'); + }); + }); + + describe('.toNumber()', function () { + it('should return proper Number if below the limit', function () { + assert.deepEqual(new BN(0x123456).toNumber(), 0x123456); + assert.deepEqual(new BN(0x3ffffff).toNumber(), 0x3ffffff); + assert.deepEqual(new BN(0x4000000).toNumber(), 0x4000000); + assert.deepEqual(new BN(0x10000000000000).toNumber(), 0x10000000000000); + assert.deepEqual(new BN(0x10040004004000).toNumber(), 0x10040004004000); + assert.deepEqual(new BN(-0x123456).toNumber(), -0x123456); + assert.deepEqual(new BN(-0x3ffffff).toNumber(), -0x3ffffff); + assert.deepEqual(new BN(-0x4000000).toNumber(), -0x4000000); + assert.deepEqual(new BN(-0x10000000000000).toNumber(), -0x10000000000000); + assert.deepEqual(new BN(-0x10040004004000).toNumber(), -0x10040004004000); + }); + + it('should throw when number exceeds 53 bits', function () { + var n = new BN(1).iushln(54); + assert.throws(function () { + n.toNumber(); + }); + }); + }); + + describe('.zeroBits()', function () { + it('should return proper zeroBits', function () { + assert.equal(new BN(0).zeroBits(), 0); + assert.equal(new BN(0x1).zeroBits(), 0); + assert.equal(new BN(0x2).zeroBits(), 1); + assert.equal(new BN(0x3).zeroBits(), 0); + assert.equal(new BN(0x4).zeroBits(), 2); + assert.equal(new BN(0x8).zeroBits(), 3); + assert.equal(new BN(0x10).zeroBits(), 4); + assert.equal(new BN(0x100).zeroBits(), 8); + assert.equal(new BN(0x1000000).zeroBits(), 24); + assert.equal(new BN(0x123456).zeroBits(), 1); + }); + }); + + describe('.toJSON', function () { + it('should return hex string', function () { + assert.equal(new BN(0x123).toJSON(), '123'); + }); + }); + + describe('.cmpn', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmpn(42), 0); + assert.equal(new BN(42).cmpn(43), -1); + assert.equal(new BN(42).cmpn(41), 1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffe), 0); + assert.equal(new BN(0x3fffffe).cmpn(0x3ffffff), -1); + assert.equal(new BN(0x3fffffe).cmpn(0x3fffffd), 1); + assert.throws(function () { + new BN(0x3fffffe).cmpn(0x4000000); + }); + assert.equal(new BN(42).cmpn(-42), 1); + assert.equal(new BN(-42).cmpn(42), -1); + assert.equal(new BN(-42).cmpn(-42), 0); + assert.equal(1 / new BN(-42).cmpn(-42), Infinity); + }); + }); + + describe('.cmp', function () { + it('should return -1, 0, 1 correctly', function () { + assert.equal(new BN(42).cmp(new BN(42)), 0); + assert.equal(new BN(42).cmp(new BN(43)), -1); + assert.equal(new BN(42).cmp(new BN(41)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffe)), 0); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3ffffff)), -1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x3fffffd)), 1); + assert.equal(new BN(0x3fffffe).cmp(new BN(0x4000000)), -1); + assert.equal(new BN(42).cmp(new BN(-42)), 1); + assert.equal(new BN(-42).cmp(new BN(42)), -1); + assert.equal(new BN(-42).cmp(new BN(-42)), 0); + assert.equal(1 / new BN(-42).cmp(new BN(-42)), Infinity); + }); + }); + + describe('comparison shorthands', function () { + it('.gtn greater than', function () { + assert.equal(new BN(3).gtn(2), true); + assert.equal(new BN(3).gtn(3), false); + assert.equal(new BN(3).gtn(4), false); + }); + it('.gt greater than', function () { + assert.equal(new BN(3).gt(new BN(2)), true); + assert.equal(new BN(3).gt(new BN(3)), false); + assert.equal(new BN(3).gt(new BN(4)), false); + }); + it('.gten greater than or equal', function () { + assert.equal(new BN(3).gten(3), true); + assert.equal(new BN(3).gten(2), true); + assert.equal(new BN(3).gten(4), false); + }); + it('.gte greater than or equal', function () { + assert.equal(new BN(3).gte(new BN(3)), true); + assert.equal(new BN(3).gte(new BN(2)), true); + assert.equal(new BN(3).gte(new BN(4)), false); + }); + it('.ltn less than', function () { + assert.equal(new BN(2).ltn(3), true); + assert.equal(new BN(2).ltn(2), false); + assert.equal(new BN(2).ltn(1), false); + }); + it('.lt less than', function () { + assert.equal(new BN(2).lt(new BN(3)), true); + assert.equal(new BN(2).lt(new BN(2)), false); + assert.equal(new BN(2).lt(new BN(1)), false); + }); + it('.lten less than or equal', function () { + assert.equal(new BN(3).lten(3), true); + assert.equal(new BN(3).lten(2), false); + assert.equal(new BN(3).lten(4), true); + }); + it('.lte less than or equal', function () { + assert.equal(new BN(3).lte(new BN(3)), true); + assert.equal(new BN(3).lte(new BN(2)), false); + assert.equal(new BN(3).lte(new BN(4)), true); + }); + it('.eqn equal', function () { + assert.equal(new BN(3).eqn(3), true); + assert.equal(new BN(3).eqn(2), false); + assert.equal(new BN(3).eqn(4), false); + }); + it('.eq equal', function () { + assert.equal(new BN(3).eq(new BN(3)), true); + assert.equal(new BN(3).eq(new BN(2)), false); + assert.equal(new BN(3).eq(new BN(4)), false); + }); + }); + + describe('.fromTwos', function () { + it('should convert from two\'s complement to negative number', function () { + assert.equal(new BN('00000000', 16).fromTwos(32).toNumber(), 0); + assert.equal(new BN('00000001', 16).fromTwos(32).toNumber(), 1); + assert.equal(new BN('7fffffff', 16).fromTwos(32).toNumber(), 2147483647); + assert.equal(new BN('80000000', 16).fromTwos(32).toNumber(), -2147483648); + assert.equal(new BN('f0000000', 16).fromTwos(32).toNumber(), -268435456); + assert.equal(new BN('f1234567', 16).fromTwos(32).toNumber(), -249346713); + assert.equal(new BN('ffffffff', 16).fromTwos(32).toNumber(), -1); + assert.equal(new BN('fffffffe', 16).fromTwos(32).toNumber(), -2); + assert.equal(new BN('fffffffffffffffffffffffffffffffe', 16) + .fromTwos(128).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'fffffffffffffffffffffffffffffffe', 16).fromTwos(256).toNumber(), -2); + assert.equal(new BN('ffffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toNumber(), -1); + assert.equal(new BN('7fffffffffffffffffffffffffffffff' + + 'ffffffffffffffffffffffffffffffff', 16).fromTwos(256).toString(10), + new BN('5789604461865809771178549250434395392663499' + + '2332820282019728792003956564819967', 10).toString(10)); + assert.equal(new BN('80000000000000000000000000000000' + + '00000000000000000000000000000000', 16).fromTwos(256).toString(10), + new BN('-578960446186580977117854925043439539266349' + + '92332820282019728792003956564819968', 10).toString(10)); + }); + }); + + describe('.toTwos', function () { + it('should convert from negative number to two\'s complement', function () { + assert.equal(new BN(0).toTwos(32).toString(16), '0'); + assert.equal(new BN(1).toTwos(32).toString(16), '1'); + assert.equal(new BN(2147483647).toTwos(32).toString(16), '7fffffff'); + assert.equal(new BN('-2147483648', 10).toTwos(32).toString(16), '80000000'); + assert.equal(new BN('-268435456', 10).toTwos(32).toString(16), 'f0000000'); + assert.equal(new BN('-249346713', 10).toTwos(32).toString(16), 'f1234567'); + assert.equal(new BN('-1', 10).toTwos(32).toString(16), 'ffffffff'); + assert.equal(new BN('-2', 10).toTwos(32).toString(16), 'fffffffe'); + assert.equal(new BN('-2', 10).toTwos(128).toString(16), + 'fffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-2', 10).toTwos(256).toString(16), + 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe'); + assert.equal(new BN('-1', 10).toTwos(256).toString(16), + 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('5789604461865809771178549250434395392663' + + '4992332820282019728792003956564819967', 10).toTwos(256).toString(16), + '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); + assert.equal(new BN('-578960446186580977117854925043439539266' + + '34992332820282019728792003956564819968', 10).toTwos(256).toString(16), + '8000000000000000000000000000000000000000000000000000000000000000'); + }); + }); + + describe('.isBN', function () { + it('should return true for BN', function () { + assert.equal(BN.isBN(new BN()), true); + }); + + it('should return false for everything else', function () { + assert.equal(BN.isBN(1), false); + assert.equal(BN.isBN([]), false); + assert.equal(BN.isBN({}), false); + }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/util/genCombMulTo.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/util/genCombMulTo.js new file mode 100644 index 0000000..8b456c7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/util/genCombMulTo.js @@ -0,0 +1,65 @@ +'use strict'; + +// NOTE: This could be potentionally used to generate loop-less multiplications +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('var w' + k + ' = c;'); + src.push('c = 0;'); + for (var j = minJ; j <= maxJ; j++) { + i = k - j; + + src.push('lo = Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid = Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;'); + src.push('hi = Math.imul(ah' + i + ', bh' + j + ');'); + + src.push('w' + k + ' = (w' + k + ' + lo) | 0;'); + src.push('w' + k + ' = (w' + k + ' + ((mid & 0x1fff) << 13)) | 0;'); + src.push('c = (c + hi) | 0;'); + src.push('c = (c + (mid >>> 13)) | 0;'); + src.push('c = (c + (w' + k + ' >>> 26)) | 0;'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/util/genCombMulTo10.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/util/genCombMulTo10.js new file mode 100644 index 0000000..4214ffd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/bn.js/util/genCombMulTo10.js @@ -0,0 +1,64 @@ +'use strict'; + +function genCombMulTo (alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = self.words;', + 'var b = num.words;', + 'var o = out.words;', + 'var c = 0;', + 'var lo;', + 'var mid;', + 'var hi;' + ]; + for (var i = 0; i < alen; i++) { + src.push('var a' + i + ' = a[' + i + '] | 0;'); + src.push('var al' + i + ' = a' + i + ' & 0x1fff;'); + src.push('var ah' + i + ' = a' + i + ' >>> 13;'); + } + for (i = 0; i < blen; i++) { + src.push('var b' + i + ' = b[' + i + '] | 0;'); + src.push('var bl' + i + ' = b' + i + ' & 0x1fff;'); + src.push('var bh' + i + ' = b' + i + ' >>> 13;'); + } + src.push(''); + src.push('out.negative = self.negative ^ num.negative;'); + src.push('out.length = ' + len + ';'); + + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + src.push('\/* k = ' + k + ' *\/'); + src.push('lo = Math.imul(al' + (k - minJ) + ', bl' + minJ + ');'); + src.push('mid = Math.imul(al' + (k - minJ) + ', bh' + minJ + ');'); + src.push('mid += Math.imul(ah' + (k - minJ) + ', bl' + minJ + ');'); + src.push('hi = Math.imul(ah' + (k - minJ) + ', bh' + minJ + ');'); + + for (var j = minJ + 1; j <= maxJ; j++) { + i = k - j; + + src.push('lo += Math.imul(al' + i + ', bl' + j + ');'); + src.push('mid += Math.imul(al' + i + ', bh' + j + ');'); + src.push('mid += Math.imul(ah' + i + ', bl' + j + ');'); + src.push('hi += Math.imul(ah' + i + ', bh' + j + ');'); + } + + src.push('var w' + k + ' = c + lo + ((mid & 0x1fff) << 13);'); + src.push('c = hi + (mid >>> 13) + (w' + k + ' >>> 26);'); + src.push('w' + k + ' &= 0x3ffffff;'); + } + // Store in separate step for better memory access + for (k = 0; k < len; k++) { + src.push('o[' + k + '] = w' + k + ';'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} + +console.log(genCombMulTo(10, 10)); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/.travis.yml new file mode 100644 index 0000000..2022962 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.11" \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/LICENSE new file mode 100644 index 0000000..f6d285c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 Calvin Metcalf & contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/index.js new file mode 100644 index 0000000..2b301cd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/index.js @@ -0,0 +1,40 @@ +var bn = require('bn.js'); +var randomBytes = require('randombytes'); +module.exports = crt; +function blind(priv) { + var r = getr(priv); + var blinder = r.toRed(bn.mont(priv.modulus)) + .redPow(new bn(priv.publicExponent)).fromRed(); + return { + blinder: blinder, + unblinder:r.invm(priv.modulus) + }; +} +function crt(msg, priv) { + var blinds = blind(priv); + var len = priv.modulus.byteLength(); + var mod = bn.mont(priv.modulus); + var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus); + var c1 = blinded.toRed(bn.mont(priv.prime1)); + var c2 = blinded.toRed(bn.mont(priv.prime2)); + var qinv = priv.coefficient; + var p = priv.prime1; + var q = priv.prime2; + var m1 = c1.redPow(priv.exponent1); + var m2 = c2.redPow(priv.exponent2); + m1 = m1.fromRed(); + m2 = m2.fromRed(); + var h = m1.isub(m2).imul(qinv).umod(p); + h.imul(q); + m2.iadd(h); + return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); +} +crt.getr = getr; +function getr(priv) { + var len = priv.modulus.byteLength(); + var r = new bn(randomBytes(len)); + while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) { + r = new bn(randomBytes(len)); + } + return r; +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/package.json new file mode 100644 index 0000000..eeabacd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/package.json @@ -0,0 +1,34 @@ +{ + "name": "browserify-rsa", + "version": "4.0.1", + "description": "RSA for browserify", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "author": "", + "license": "MIT", + "dependencies": { + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/crypto-browserify/browserify-rsa.git" + }, + "devDependencies": { + "parse-asn1": "^5.0.0", + "tap-spec": "^2.1.2", + "tape": "^3.0.3" + }, + "readme": "browserify-rsa\n====\n[![Build Status](https://travis-ci.org/crypto-browserify/browserify-rsa.svg)](https://travis-ci.org/crypto-browserify/browserify-rsa)\n\nRSA private decryption/signing using chinese remainder and blinding.\n\nAPI\n====\n\nGive it a message as a buffer and a private key (as decoded by https://www.npmjs.com/package/parse-asn1) and it returns encrypted data as a buffer.\n", + "readmeFilename": "readme.md", + "bugs": { + "url": "https://github.com/crypto-browserify/browserify-rsa/issues" + }, + "homepage": "https://github.com/crypto-browserify/browserify-rsa#readme", + "_id": "browserify-rsa@4.0.1", + "_shasum": "21e0abfaf6f2029cf2fafb133567a701d4135524", + "_resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "_from": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/readme.md new file mode 100644 index 0000000..370fd95 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/readme.md @@ -0,0 +1,10 @@ +browserify-rsa +==== +[![Build Status](https://travis-ci.org/crypto-browserify/browserify-rsa.svg)](https://travis-ci.org/crypto-browserify/browserify-rsa) + +RSA private decryption/signing using chinese remainder and blinding. + +API +==== + +Give it a message as a buffer and a private key (as decoded by https://www.npmjs.com/package/parse-asn1) and it returns encrypted data as a buffer. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/test.js new file mode 100644 index 0000000..3d79a6d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/browserify-rsa/test.js @@ -0,0 +1,53 @@ +var keys = [ + new Buffer('2d2d2d2d2d424547494e2050524956415445204b45592d2d2d2d2d0a4d494943647749424144414e42676b71686b6947397730424151454641415343416d457767674a6441674541416f4742414b756c55545a3842317163635a38630a44585247535930386757384b764c6c63787878474334675a484e543343425546386e3552344b453330615a79595a2f727473515a7530356a755a4a78614a30710a6d62653735646c5135642b586339424d586551672f4d70545a773554414e374f4964475959704642652b31504c5a367745666a6b59724d714d55636671324c710a68544c64416276424a6e755263595a4c716d42654f51384654724b7241674d4241414543675945416e6b485262455055332f57495353517250333669794362320a532f53425a774b6b7a6d764372427844576850654473777039632f324a593736724e57664c7a793869586755473857557a76486a653631516833676d42634b650a62556154476c34567938486131594241446f3552665272646d3046453474766776752f546b7146717042425a7765753534323835686b357a6c47376e2f4437590a646e4e58557075354d6c4e623578336757306b43515144554c2f2f637763585578592f6576614a50346a53652b5a7745515a6f2b7a58524c695055756c426f560a6177323843564d757864677771416f315831494b65665065556166375251753867434b61526e704775457558416b45417a785a54664d6d766d435544496577340a35476b36624b3236355851576468636769713235346c7042474f596d446a397943453779412b7a6d415351774d73585464514f6931684f434579725875534a350a632b2b4544514a4146683357726e7a6f455042797559584d6d45543874534652574d51357670674e716833686148523562346755433268786169756e43424e4c0a315270565939416f55694479774763472f5350683933436e4b42336e69774a42414b503741747369665a6756587469697a4234614d5468546a565961535a727a0a44304b6739447548796c706b4443686d467537375447724e55516741567559746668622f6252626c56612f4630684a3465514854334a554351425654363874620a4f6752556b30615039744333303231564e383258362b6b6c6f7753514e386f425058382b546644575355696c702f2b6a3234486b792b5a3239446f3779522f520a7175746e4c39324376426c564c56343d0a2d2d2d2d2d454e442050524956415445204b45592d2d2d2d2d0a', 'hex'), + new Buffer('2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a4d4949435641494241414a2f4f77737762466f2f757943386c7447662f794131412b6756354947646e4167506255534933477a624843412b782b544c472f744c0a76625277337231736d7070592f6a6b6b70695657314572534d754e307569787035676237385a39724831587057623557576770335761592f3945484d6a4d644f0a6b512f394c565a7652766c2f4d2f4669366f77502b712b616d4a493142456a454359666268474c33726d6c5664713471586334305177494441514142416e38490a565a3042506f414f68794633334b464d4878793872323866735667784a5559674d334e715167647634664661774359586a684a7a3964755535594a47464a474a0a57554765486c6b7959466c70693466336d377459374a61776d51555742304d4e536f4b48493363674458342f7466424e386e692b634f3065536f5235637a42590a4573414842553437703161774e46414877642b5a457576394834526d4d6e37703237397251547470416b4148334e7173322f7672524632635a554e34664958660a347848735142427955617947713861334a305547615346577636387a54554b466865727239755a6f744e70374e4a346a425869415277307138646f63585547310a416b4148676d4f4b486f4f5274416d696b71706d46454a5a4f7473584d614c43496d3445737a506f356369596f4c4d42635669743039416469516c74375a4a4c0a445930327376553162306167435a39376b446b6d48446b58416b414361384d394a454c7544732f502f76494759446b4d566174494666573662574630326546470a746157774d71436353457357766277307871597433346a5552704e62436a6d4379515677596641772f2b544c68503964416b414677526a64776a77333771706a0a646467316d4e697533376237737746786d6b694d4f585a5278614e4e736662353641313452704e337a6f6233516447557962476f644d494b5446626d552f6c750a436a71417861664a416b41473279663652576277464957664d7974375759436830566147424363677935373441696e566965456f335a5a7946664336332b786d0a33756f614e7934694c6f4a763447436a7155427a335a666356614f2f444457470a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a', 'hex'), + new Buffer('2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a4d4949456a77494241414b422f6779376d6a615767506546645659445a5752434139424e69763370506230657332372b464b593068737a4c614f7734374578430a744157704473483438545841667948425977424c67756179666b344c4749757078622b43474d62526f337845703043626659314a62793236543976476a5243310a666f484444554a4738347561526279487161663469367a74346756522b786c4145496a6b614641414b38634f6f58415431435671474c4c6c6a554363684c38500a6a61486a2f7972695a2f53377264776c49334c6e41427877776d4c726d522f7637315774706d4f2f614e47384e2b31706f2b5177616768546b79513539452f5a0a7641754f6b4657486f6b32712f523650594161326a645a397a696d3046714f502b6e6b5161454452624246426d4271547635664647666b32577341664b662f520a47302f5646642b5a654d353235315465547658483639356e6c53476175566c3941674d42414145436766344c725748592f6c35346f7554685a577676627275670a70667a36734a583267396c3779586d576c455773504543566f2f375355627059467074364f5a7939397a53672b494b624771574b6664686f4b725477495674430a4c30595a304e6c6d646e414e53497a30726f785147375a786b4c352b764853772f506d443978345577662b437a38684154436d4e42763171633630646b7975570a34434c71653732716154695657526f4f316961675167684e634c6f6f36765379363545784c614344545068613779753276773468465a705769456a57346478660a7246644c696978353242433836596c416c784d452f724c6738494a5676696c62796f39615764586d784f6155544c527636506b4644312f6756647738563951720a534c4e39466c4b326b6b6a695830647a6f6962765a7733744d6e74337979644178305838372b734d5256616843316270336b56507a3448793045575834514a2f0a504d33317647697549546b324e43643531445874314c746e324f503546614a536d4361456a6830586b5534716f7559796a585774384275364254436c327675610a466730556a6939432b496b504c6d61554d624d494f7761546b386357714c74685378734c6537304a354f6b477267664b554d2f772b4248483150742f506a7a6a0a432b2b6c306b6946614f5644566141563947704c504c43426f4b2f50433952622f72784d4d6f43434e774a2f4e5a756564496e793277334c4d69693737682f540a7a53766572674e47686a5936526e7661386c4c584a36646c726b6350417970733367577778716a344e5230542b474d3062445550564c62374d303758563753580a7637564a476d35324a625247774d3173732b72385854544e656d65476b2b5752784737546774734d715947584c66423851786b2f66352f4d63633030546c38750a7758464e7366784a786d7436416273547233673336774a2f49684f6e69627a3941642b6e63686c426e4e3351655733434b48717a61523138766f717674566d320a6b4a66484b31357072482f7353476d786d6945476772434a545a78744462614e434f372f56426a6e4b756455554968434177734c747571302f7a7562397641640a384731736366497076357161534e7a6d4b6f5838624f77417276725336775037794b726354737557496c484438724a5649374945446e516f5470354738664b310a68774a2f4d4968384d35763072356455594576366f494a5747636c65364148314a6d73503557496166677137325a32323838704863434648774e59384467394a0a3736517377564c6e556850546c6d6d33454f4f50474574616d32694144357230416679746c62346c624e6f51736a32737a65584f4e4458422b366f7565616a680a564e454c55723848635350356c677a525a6a4a57366146497a6a394c44526d516e55414f6a475358564f517445774a2f4d43515a374e2f763464494b654452410a3864385545785a332b674748756d7a697a7447524a30745172795a483250616b50354937562b316c377145556e4a3263336d462b65317634314570394c4376680a627a72504b773964786831386734622b37624d707357506e7372614b6836697078633761614f615a5630447867657a347a635a753050316f6c4f30634e334b4d0a6e784a305064733352386241684e43446453324a5a61527035513d3d0a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a', 'hex') +]; +var parseKey = require('parse-asn1'); +var privs = keys.map(parseKey); +var crt = require('./'); +var crypto = require('crypto'); +var test = require('tape'); +var constants = require('constants'); +var bn = require('bn.js'); +function testIt(priv, run) { + test('r is coprime with n ' + (run + 1), function (t) { + var len = 30; + t.plan(len); + var i = 0; + while(i++ < len) { + var r = crt.getr(priv); + t.equals(r.gcd(priv.modulus).toString(), '1', 'are coprime run ' + i); + } + }); +} +privs.forEach(testIt); + +function testMessage(key, run) { + var len = 40; + var i = 0; + while (len--) { + test('round trip key ' + (run + 1) + ' run ' + (++i), function (t) { + t.plan(1); + var priv = parseKey(key); + var len = priv.modulus.byteLength(); + var r = new bn(crypto.randomBytes(len)); + while (r.cmp(priv.modulus) >= 0) { + r = new bn(crypto.randomBytes(len)); + } + var buf = new Buffer(r.toArray()); + if (buf.byteLength < priv.modulus.byteLength()) { + var tmp = new Buffer(priv.modulus.byteLength() - buf.byteLength); + tmp.fill(0); + buf = Buffer.concat([tmp, buf]); + } + var nodeEncrypt = crypto.privateDecrypt({ + padding: constants.RSA_NO_PADDING, + key: key + }, buf).toString('hex'); + var myEncrypt = crt(buf, priv).toString('hex'); + t.equals(myEncrypt, nodeEncrypt, 'equal encrypts'); + }); + } +} +keys.forEach(testMessage); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/.npmignore new file mode 100644 index 0000000..4ebc8ae --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/.npmignore @@ -0,0 +1 @@ +coverage diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/.travis.yml new file mode 100644 index 0000000..ea321cc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/.travis.yml @@ -0,0 +1,9 @@ +sudo: false +language: node_js +node_js: + - "0.12" + - "iojs" +env: + - TEST_SUITE=standard + - TEST_SUITE=unit +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/README.md new file mode 100644 index 0000000..89ed074 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/README.md @@ -0,0 +1,8 @@ +#parse-asn1 + +[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/parse-asn1.png)](http://travis-ci.org/crypto-browserify/parse-asn1) +[![NPM](http://img.shields.io/npm/v/parse-asn1.svg)](https://www.npmjs.org/package/parse-asn1) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +utility library for parsing asn1 files for use with browserify-sign. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/aesid.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/aesid.json new file mode 100644 index 0000000..24f653b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/aesid.json @@ -0,0 +1,13 @@ +{"2.16.840.1.101.3.4.1.1": "aes-128-ecb", +"2.16.840.1.101.3.4.1.2": "aes-128-cbc", +"2.16.840.1.101.3.4.1.3": "aes-128-ofb", +"2.16.840.1.101.3.4.1.4": "aes-128-cfb", +"2.16.840.1.101.3.4.1.21": "aes-192-ecb", +"2.16.840.1.101.3.4.1.22": "aes-192-cbc", +"2.16.840.1.101.3.4.1.23": "aes-192-ofb", +"2.16.840.1.101.3.4.1.24": "aes-192-cfb", +"2.16.840.1.101.3.4.1.41": "aes-256-ecb", +"2.16.840.1.101.3.4.1.42": "aes-256-cbc", +"2.16.840.1.101.3.4.1.43": "aes-256-ofb", +"2.16.840.1.101.3.4.1.44": "aes-256-cfb" +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/asn1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/asn1.js new file mode 100644 index 0000000..cb2fcfc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/asn1.js @@ -0,0 +1,117 @@ +// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js +// Fedor, you are amazing. + +var asn1 = require('asn1.js') + +var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('modulus').int(), + this.key('publicExponent').int(), + this.key('privateExponent').int(), + this.key('prime1').int(), + this.key('prime2').int(), + this.key('exponent1').int(), + this.key('exponent2').int(), + this.key('coefficient').int() + ) +}) +exports.RSAPrivateKey = RSAPrivateKey + +var RSAPublicKey = asn1.define('RSAPublicKey', function () { + this.seq().obj( + this.key('modulus').int(), + this.key('publicExponent').int() + ) +}) +exports.RSAPublicKey = RSAPublicKey + +var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ) +}) +exports.PublicKey = PublicKey + +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('none').null_().optional(), + this.key('curve').objid().optional(), + this.key('params').seq().obj( + this.key('p').int(), + this.key('q').int(), + this.key('g').int() + ).optional() + ) +}) + +var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ) +}) +exports.PrivateKey = PrivateKeyInfo +var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters').int() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ) +}) + +exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo + +var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('p').int(), + this.key('q').int(), + this.key('g').int(), + this.key('pub_key').int(), + this.key('priv_key').int() + ) +}) +exports.DSAPrivateKey = DSAPrivateKey + +exports.DSAparam = asn1.define('DSAparam', function () { + this.int() +}) +var ECPrivateKey = asn1.define('ECPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ) +}) +exports.ECPrivateKey = ECPrivateKey +var ECParameters = asn1.define('ECParameters', function () { + this.choice({ + namedCurve: this.objid() + }) +}) + +exports.signature = asn1.define('signature', function () { + this.seq().obj( + this.key('r').int(), + this.key('s').int() + ) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/fixProc.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/fixProc.js new file mode 100644 index 0000000..5c4085e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/fixProc.js @@ -0,0 +1,30 @@ +// adapted from https://github.com/apatil/pemstrip +var findProc = /Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\r?\n\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n/m +var startRegex = /^-----BEGIN (.*) KEY-----\r?\n/m +var fullRegex = /^-----BEGIN (.*) KEY-----\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n-----END \1 KEY-----$/m +var evp = require('evp_bytestokey') +var ciphers = require('browserify-aes') +module.exports = function (okey, password) { + var key = okey.toString() + var match = key.match(findProc) + var decrypted + if (!match) { + var match2 = key.match(fullRegex) + decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64') + } else { + var suite = 'aes' + match[1] + var iv = new Buffer(match[2], 'hex') + var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64') + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key + var out = [] + var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) + out.push(cipher.update(cipherText)) + out.push(cipher.final()) + decrypted = Buffer.concat(out) + } + var tag = key.match(startRegex)[1] + ' KEY' + return { + tag: tag, + data: decrypted + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/index.js new file mode 100644 index 0000000..5cc7967 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/index.js @@ -0,0 +1,101 @@ +var asn1 = require('./asn1') +var aesid = require('./aesid.json') +var fixProc = require('./fixProc') +var ciphers = require('browserify-aes') +var compat = require('pbkdf2') +module.exports = parseKeys + +function parseKeys (buffer) { + var password + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase + buffer = buffer.key + } + if (typeof buffer === 'string') { + buffer = new Buffer(buffer) + } + + var stripped = fixProc(buffer, password) + + var type = stripped.tag + var data = stripped.data + var subtype, ndata + switch (type) { + case 'PUBLIC KEY': + ndata = asn1.PublicKey.decode(data, 'der') + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') + case '1.2.840.10045.2.1': + ndata.subjectPrivateKey = ndata.subjectPublicKey + return { + type: 'ec', + data: ndata + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') + return { + type: 'dsa', + data: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der') + data = decrypt(data, password) + // falls through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der') + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') + case '1.2.840.10045.2.1': + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') + return { + type: 'dsa', + params: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der') + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der') + case 'DSA PRIVATE KEY': + return { + type: 'dsa', + params: asn1.DSAPrivateKey.decode(data, 'der') + } + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der') + return { + curve: data.parameters.value, + privateKey: data.privateKey + } + default: throw new Error('unknown key type ' + type) + } +} +parseKeys.signature = asn1.signature +function decrypt (data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt + var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10) + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')] + var iv = data.algorithm.decrypt.cipher.iv + var cipherText = data.subjectPrivateKey + var keylen = parseInt(algo.split('-')[1], 10) / 8 + var key = compat.pbkdf2Sync(password, salt, iters, keylen) + var cipher = ciphers.createDecipheriv(algo, key, iv) + var out = [] + out.push(cipher.update(cipherText)) + out.push(cipher.final()) + return Buffer.concat(out) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/.npmignore new file mode 100644 index 0000000..0d7d7ee --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/.npmignore @@ -0,0 +1,3 @@ +node_modules/ +npm-debug.log +test.js diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/README.md new file mode 100644 index 0000000..0c571b8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/README.md @@ -0,0 +1,100 @@ +# ASN1.js + +ASN.1 DER Encoder/Decoder and DSL. + +## Example + +Define model: + +```javascript +var asn = require('asn1.js'); + +var Human = asn.define('Human', function() { + this.seq().obj( + this.key('firstName').octstr(), + this.key('lastName').octstr(), + this.key('age').int(), + this.key('gender').enum({ 0: 'male', 1: 'female' }), + this.key('bio').seqof(Bio) + ); +}); + +var Bio = asn.define('Bio', function() { + this.seq().obj( + this.key('time').gentime(), + this.key('description').octstr() + ); +}); +``` + +Encode data: + +```javascript +var output = Human.encode({ + firstName: 'Thomas', + lastName: 'Anderson', + age: 28, + gender: 'male', + bio: [ + { + time: +new Date('31 March 1999'), + description: 'freedom of mind' + } + ] +}, 'der'); +``` + +Decode data: + +```javascript +var human = Human.decode(output, 'der'); +console.log(human); +/* +{ firstName: , + lastName: , + age: 28, + gender: 'male', + bio: + [ { time: 922820400000, + description: } ] } +*/ +``` + +### Partial decode + +Its possible to parse data without stopping on first error. In order to do it, +you should call: + +```javascript +var human = Human.decode(output, 'der', { partial: true }); +console.log(human); +/* +{ result: { ... }, + errors: [ ... ] } +*/ +``` + +#### LICENSE + +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2013. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1.js new file mode 100644 index 0000000..02bbdc1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1.js @@ -0,0 +1,9 @@ +var asn1 = exports; + +asn1.bignum = require('bn.js'); + +asn1.define = require('./asn1/api').define; +asn1.base = require('./asn1/base'); +asn1.constants = require('./asn1/constants'); +asn1.decoders = require('./asn1/decoders'); +asn1.encoders = require('./asn1/encoders'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/api.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/api.js new file mode 100644 index 0000000..0e8a201 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/api.js @@ -0,0 +1,59 @@ +var asn1 = require('../asn1'); +var inherits = require('inherits'); + +var api = exports; + +api.define = function define(name, body) { + return new Entity(name, body); +}; + +function Entity(name, body) { + this.name = name; + this.body = body; + + this.decoders = {}; + this.encoders = {}; +}; + +Entity.prototype._createNamed = function createNamed(base) { + var named; + try { + named = require('vm').runInThisContext( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; + } + inherits(named, base); + named.prototype._initNamed = function initnamed(entity) { + base.call(this, entity); + }; + + return new named(this); +}; + +Entity.prototype._getDecoder = function _getDecoder(enc) { + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(asn1.decoders[enc]); + return this.decoders[enc]; +}; + +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; + +Entity.prototype._getEncoder = function _getEncoder(enc) { + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(asn1.encoders[enc]); + return this.encoders[enc]; +}; + +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/buffer.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/buffer.js new file mode 100644 index 0000000..bc826e8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/buffer.js @@ -0,0 +1,116 @@ +var inherits = require('inherits'); +var Reporter = require('../base').Reporter; +var Buffer = require('buffer').Buffer; + +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } + + this.base = base; + this.offset = 0; + this.length = base.length; +} +inherits(DecoderBuffer, Reporter); +exports.DecoderBuffer = DecoderBuffer; + +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; +}; + +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; + + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); + + return res; +}; + +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; + +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); +} + +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + + var res = new DecoderBuffer(this.base); + + // Share reporter state + res._reporterState = this._reporterState; + + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; +} + +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } +} +exports.EncoderBuffer = EncoderBuffer; + +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; + + if (this.length === 0) + return out; + + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; + } + + return out; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/index.js new file mode 100644 index 0000000..935abde --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/index.js @@ -0,0 +1,6 @@ +var base = exports; + +base.Reporter = require('./reporter').Reporter; +base.DecoderBuffer = require('./buffer').DecoderBuffer; +base.EncoderBuffer = require('./buffer').EncoderBuffer; +base.Node = require('./node'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/node.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/node.js new file mode 100644 index 0000000..0c196e8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/node.js @@ -0,0 +1,621 @@ +var Reporter = require('../base').Reporter; +var EncoderBuffer = require('../base').EncoderBuffer; +var DecoderBuffer = require('../base').DecoderBuffer; +var assert = require('minimalistic-assert'); + +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +]; + +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); + +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + var state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + var state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(newKey) { + var state = this._baseState; + + assert(state.key === null); + state.key = newKey; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +Node.prototype.contains = function contains(item) { + var state = this._baseState; + + assert(state.use === null); + state.contains = item; + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input)); + + var result = state['default']; + var present = true; + + var prevKey; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + var tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input); + else + this._decodeChoice(input); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + + if (input.isError(present)) + return present; + } + } + + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input); + else + result = this._decodeChoice(input); + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input); + }); + } + + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj)._decode(data); + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input) { + var state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0]); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1]); + else if (tag === 'objid') + return this._decodeObjid(input, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag); + else if (tag === 'null_') + return this._decodeNull(input); + else if (tag === 'bool') + return this._decodeBool(input); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0]); + else if (state.use !== null) + return this._getUse(state.use, input._reporterState.obj)._decode(input); + else + return input.error('unknown tag: ' + tag); + + return null; +}; + +Node.prototype._getUse = function _getUse(entity, obj) { + + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; + + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; + + if (this._skipDefault(result, reporter, parent)) + return; + + return result; +}; + +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + var result = null; + var present = true; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; + } + + // For error reporting + var prevKey; + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be ommited only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else + throw new Error('Unsupported tag: ' + tag); +}; + +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; + +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/reporter.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/reporter.js new file mode 100644 index 0000000..e0a8e89 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/base/reporter.js @@ -0,0 +1,102 @@ +var inherits = require('inherits'); + +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.Reporter = Reporter; + +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; + +Reporter.prototype.save = function save() { + var state = this._reporterState; + + return { obj: state.obj, pathLen: state.path.length }; +}; + +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; + + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; + +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; + +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; + + state.path = state.path.slice(0, index - 1); + if (state.obj !== null) + state.obj[key] = value; +}; + +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + + var prev = state.obj; + state.obj = {}; + return prev; +}; + +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; + + var now = state.obj; + state.obj = prev; + return now; +}; + +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } + + if (!state.options.partial) + throw err; + + if (!inherited) + state.errors.push(err); + + return err; +}; + +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; + + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; + +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + Error.captureStackTrace(this, ReporterError); + + return this; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/der.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/der.js new file mode 100644 index 0000000..907dd39 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/der.js @@ -0,0 +1,42 @@ +var constants = require('../constants'); + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/index.js new file mode 100644 index 0000000..c44e325 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/constants/index.js @@ -0,0 +1,19 @@ +var constants = exports; + +// Helper +constants._reverse = function reverse(map) { + var res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + var value = map[key]; + res[value] = key; + }); + + return res; +}; + +constants.der = require('./der'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/der.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/der.js new file mode 100644 index 0000000..92d892d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/der.js @@ -0,0 +1,321 @@ +var inherits = require('inherits'); + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; + + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + var state = buffer.save(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + var res = decoder.decode(buffer, 'der'); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); + + var str = ''; + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); + + if (values) + res = values[res.toString(10)] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + var num = len & 0x7f; + if (num >= 4) + return buf.error('length octect is too long'); + + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/index.js new file mode 100644 index 0000000..e2583aa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/index.js @@ -0,0 +1,4 @@ +var decoders = exports; + +decoders.der = require('./der'); +decoders.pem = require('./pem'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/pem.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/pem.js new file mode 100644 index 0000000..a7d5225 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/decoders/pem.js @@ -0,0 +1,50 @@ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var DERDecoder = require('./der'); + +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; + +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); + + var label = options.label.toUpperCase(); + + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); + + var base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9\+\/=]+/gi, ''); + + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/der.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/der.js new file mode 100644 index 0000000..fb0b39f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/der.js @@ -0,0 +1,294 @@ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = new Buffer(numArray); + } + + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(new Buffer(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; + + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/index.js new file mode 100644 index 0000000..6a5d29e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/index.js @@ -0,0 +1,4 @@ +var encoders = exports; + +encoders.der = require('./der'); +encoders.pem = require('./pem'); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/pem.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/pem.js new file mode 100644 index 0000000..40298b8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/lib/asn1/encoders/pem.js @@ -0,0 +1,23 @@ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var DEREncoder = require('./der'); + +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; + +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); + + var p = buf.toString('base64'); + var out = [ '-----BEGIN ' + options.label + '-----' ]; + for (var i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/index.js new file mode 100644 index 0000000..70b4ea5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/index.js @@ -0,0 +1,11 @@ +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/package.json new file mode 100644 index 0000000..bd3bd47 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/package.json @@ -0,0 +1,25 @@ +{ + "name": "minimalistic-assert", + "version": "1.0.0", + "description": "minimalistic-assert ===", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/calvinmetcalf/minimalistic-assert.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/calvinmetcalf/minimalistic-assert/issues" + }, + "homepage": "https://github.com/calvinmetcalf/minimalistic-assert", + "readme": "minimalistic-assert\n===\n\nvery minimalistic assert module.\n", + "readmeFilename": "readme.md", + "_id": "minimalistic-assert@1.0.0", + "_shasum": "702be2dda6b37f4836bcb3f5db56641b64a1d3d3", + "_resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz", + "_from": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/readme.md new file mode 100644 index 0000000..2ca0d25 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/node_modules/minimalistic-assert/readme.md @@ -0,0 +1,4 @@ +minimalistic-assert +=== + +very minimalistic assert module. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/package.json new file mode 100644 index 0000000..31bec4b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/package.json @@ -0,0 +1,39 @@ +{ + "name": "asn1.js", + "version": "4.5.2", + "description": "ASN.1 encoder and decoder", + "main": "lib/asn1.js", + "scripts": { + "test": "mocha --reporter spec test/*-test.js rfc/2560/test/*-test.js rfc/5280/test/*-test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/asn1.js.git" + }, + "keywords": [ + "asn.1", + "der" + ], + "author": { + "name": "Fedor Indutny" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/asn1.js/issues" + }, + "homepage": "https://github.com/indutny/asn1.js", + "devDependencies": { + "mocha": "^2.3.4" + }, + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + }, + "readme": "# ASN1.js\n\nASN.1 DER Encoder/Decoder and DSL.\n\n## Example\n\nDefine model:\n\n```javascript\nvar asn = require('asn1.js');\n\nvar Human = asn.define('Human', function() {\n this.seq().obj(\n this.key('firstName').octstr(),\n this.key('lastName').octstr(),\n this.key('age').int(),\n this.key('gender').enum({ 0: 'male', 1: 'female' }),\n this.key('bio').seqof(Bio)\n );\n});\n\nvar Bio = asn.define('Bio', function() {\n this.seq().obj(\n this.key('time').gentime(),\n this.key('description').octstr()\n );\n});\n```\n\nEncode data:\n\n```javascript\nvar output = Human.encode({\n firstName: 'Thomas',\n lastName: 'Anderson',\n age: 28,\n gender: 'male',\n bio: [\n {\n time: +new Date('31 March 1999'),\n description: 'freedom of mind'\n }\n ]\n}, 'der');\n```\n\nDecode data:\n\n```javascript\nvar human = Human.decode(output, 'der');\nconsole.log(human);\n/*\n{ firstName: ,\n lastName: ,\n age: 28,\n gender: 'male',\n bio:\n [ { time: 922820400000,\n description: } ] }\n*/\n```\n\n### Partial decode\n\nIts possible to parse data without stopping on first error. In order to do it,\nyou should call:\n\n```javascript\nvar human = Human.decode(output, 'der', { partial: true });\nconsole.log(human);\n/*\n{ result: { ... },\n errors: [ ... ] }\n*/\n```\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2013.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "asn1.js@4.5.2", + "_shasum": "17492bdfd4bb5f1d7e56ab6b085297fee9e640e9", + "_resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.5.2.tgz", + "_from": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.5.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/index.js new file mode 100644 index 0000000..fc40c1c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/index.js @@ -0,0 +1,149 @@ +try { + var asn1 = require('asn1.js'); + var rfc5280 = require('asn1.js-rfc5280'); +} catch (e) { + var asn1 = require('../' + '..'); + var rfc5280 = require('../' + '5280'); +} + +var OCSPRequest = asn1.define('OCSPRequest', function() { + this.seq().obj( + this.key('tbsRequest').use(TBSRequest), + this.key('optionalSignature').optional().explicit(0).use(Signature) + ); +}); +exports.OCSPRequest = OCSPRequest; + +var TBSRequest = asn1.define('TBSRequest', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).use(rfc5280.Version), + this.key('requestorName').optional().explicit(1).use(rfc5280.GeneralName), + this.key('requestList').seqof(Request), + this.key('requestExtensions').optional().explicit(2).use(rfc5280.Extensions) + ); +}); +exports.TBSRequest = TBSRequest; + +var Signature = asn1.define('Signature', function() { + this.seq().obj( + this.key('signatureAlgorithm').use(rfc5280.AlgorithmIdentifier), + this.key('signature').bitstr(), + this.key('certs').optional().explicit(0).seqof(rfc5280.Certificate) + ); +}); +exports.Signature = Signature; + +var Request = asn1.define('Request', function() { + this.seq().obj( + this.key('reqCert').use(CertID), + this.key('singleRequestExtensions').optional().explicit(0).use( + rfc5280.Extensions) + ); +}); +exports.Request = Request; + +var OCSPResponse = asn1.define('OCSPResponse', function() { + this.seq().obj( + this.key('responseStatus').use(ResponseStatus), + this.key('responseBytes').optional().explicit(0).seq().obj( + this.key('responseType').objid({ + '1 3 6 1 5 5 7 48 1 1': 'id-pkix-ocsp-basic' + }), + this.key('response').octstr() + ) + ); +}); +exports.OCSPResponse = OCSPResponse; + +var ResponseStatus = asn1.define('ResponseStatus', function() { + this.enum({ + 0: 'successful', + 1: 'malformed_request', + 2: 'internal_error', + 3: 'try_later', + 5: 'sig_required', + 6: 'unauthorized' + }); +}); +exports.ResponseStatus = ResponseStatus; + +var BasicOCSPResponse = asn1.define('BasicOCSPResponse', function() { + this.seq().obj( + this.key('tbsResponseData').use(ResponseData), + this.key('signatureAlgorithm').use(rfc5280.AlgorithmIdentifier), + this.key('signature').bitstr(), + this.key('certs').optional().explicit(0).seqof(rfc5280.Certificate) + ); +}); +exports.BasicOCSPResponse = BasicOCSPResponse; + +var ResponseData = asn1.define('ResponseData', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).use(rfc5280.Version), + this.key('responderID').use(ResponderID), + this.key('producedAt').gentime(), + this.key('responses').seqof(SingleResponse), + this.key('responseExtensions').optional().explicit(0) + .use(rfc5280.Extensions) + ); +}); +exports.ResponseData = ResponseData; + +var ResponderID = asn1.define('ResponderId', function() { + this.choice({ + byName: this.explicit(1).use(rfc5280.Name), + byKey: this.explicit(2).use(KeyHash) + }); +}); +exports.ResponderID = ResponderID; + +var KeyHash = asn1.define('KeyHash', function() { + this.octstr(); +}); +exports.KeyHash = KeyHash; + +var SingleResponse = asn1.define('SingleResponse', function() { + this.seq().obj( + this.key('certId').use(CertID), + this.key('certStatus').use(CertStatus), + this.key('thisUpdate').gentime(), + this.key('nextUpdate').optional().explicit(0).gentime(), + this.key('singleExtensions').optional().explicit(1).use(rfc5280.Extensions) + ); +}); +exports.SingleResponse = SingleResponse; + +var CertStatus = asn1.define('CertStatus', function() { + this.choice({ + good: this.implicit(0).null_(), + revoked: this.implicit(1).use(RevokedInfo), + unknown: this.implicit(2).null_() + }); +}); +exports.CertStatus = CertStatus; + +var RevokedInfo = asn1.define('RevokedInfo', function() { + this.seq().obj( + this.key('revocationTime').gentime(), + this.key('revocationReason').optional().explicit(0).use(rfc5280.CRLReason) + ); +}); +exports.RevokedInfo = RevokedInfo; + +var CertID = asn1.define('CertID', function() { + this.seq().obj( + this.key('hashAlgorithm').use(rfc5280.AlgorithmIdentifier), + this.key('issuerNameHash').octstr(), + this.key('issuerKeyHash').octstr(), + this.key('serialNumber').use(rfc5280.CertificateSerialNumber) + ); +}); +exports.CertID = CertID; + +var Nonce = asn1.define('Nonce', function() { + this.octstr(); +}); +exports.Nonce = Nonce; + +exports['id-pkix-ocsp'] = [ 1, 3, 6, 1, 5, 5, 7, 48, 1 ]; +exports['id-pkix-ocsp-nonce'] = [ 1, 3, 6, 1, 5, 5, 7, 48, 1, 2 ]; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/package.json new file mode 100644 index 0000000..68ce12f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/package.json @@ -0,0 +1,27 @@ +{ + "name": "asn1.js-rfc2560", + "version": "4.0.0", + "description": "RFC2560 structures for asn1.js", + "main": "index.js", + "repository": { + "type": "git", + "url": "git@github.com:indutny/asn1.js" + }, + "keywords": [ + "asn1", + "rfc2560", + "der" + ], + "author": "Fedor Indutny", + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/asn1.js/issues" + }, + "homepage": "https://github.com/indutny/asn1.js", + "dependencies": { + "asn1.js-rfc5280": "^4.4.0" + }, + "peerDependencies": { + "asn1.js": "^4.4.0" + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/test/basic-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/test/basic-test.js new file mode 100644 index 0000000..b8a6005 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/2560/test/basic-test.js @@ -0,0 +1,50 @@ +var assert = require('assert'); +var rfc2560 = require('..'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js RFC2560', function() { + it('should decode OCSP response', function() { + var data = new Buffer( + '308201d40a0100a08201cd308201c906092b0601050507300101048201ba308201b630' + + '819fa216041499e4405f6b145e3e05d9ddd36354fc62b8f700ac180f32303133313133' + + '303037343531305a30743072304a300906052b0e03021a050004140226ee2f5fa28108' + + '34dacc3380e680ace827f604041499e4405f6b145e3e05d9ddd36354fc62b8f700ac02' + + '1100bb4f9a31232b1ba52a0b77af481800588000180f32303133313133303037343531' + + '305aa011180f32303133313230343037343531305a300d06092a864886f70d01010505' + + '00038201010027813333c9b46845dfe3d0cb6b19c03929cdfc9181c1ce823929bb911a' + + 'd9de05721790fcccbab43f9fbdec1217ab8023156d07bbcc3555f25e9e472fbbb5e019' + + '2835efcdc71b3dbc5e5c4c5939fc7a610fc6521d4ed7d2b685a812fa1a3a129ea87873' + + '972be3be54618ba4a4d96090d7f9aaa5f70d4f07cf5cf3611d8a7b3adafe0b319459ed' + + '40d456773d5f45f04c773711d86cc41d274f771a31c10d30cd6f846b587524bfab2445' + + '4bbb4535cff46f6b341e50f26a242dd78e246c8dea0e2fabcac9582e000c138766f536' + + 'd7f7bab81247c294454e62b710b07126de4e09685818f694df5783eb66f384ce5977f1' + + '2721ff38c709f3ec580d22ff40818dd17f', + 'hex'); + + var res = rfc2560.OCSPResponse.decode(data, 'der'); + assert.equal(res.responseStatus, 'successful'); + assert.equal(res.responseBytes.responseType, 'id-pkix-ocsp-basic'); + + var basic = rfc2560.BasicOCSPResponse.decode( + res.responseBytes.response, + 'der' + ); + assert.equal(basic.tbsResponseData.version, 'v1'); + assert.equal(basic.tbsResponseData.producedAt, 1385797510000); + }); + + it('should encode/decode OCSP response', function() { + var encoded = rfc2560.OCSPResponse.encode({ + responseStatus: 'malformed_request', + responseBytes: { + responseType: 'id-pkix-ocsp-basic', + response: 'random-string' + } + }, 'der'); + var decoded = rfc2560.OCSPResponse.decode(encoded, 'der'); + assert.equal(decoded.responseStatus, 'malformed_request'); + assert.equal(decoded.responseBytes.responseType, 'id-pkix-ocsp-basic'); + assert.equal(decoded.responseBytes.response.toString(), 'random-string'); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/index.js new file mode 100644 index 0000000..edbc019 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/index.js @@ -0,0 +1,878 @@ +try { + var asn1 = require('asn1.js'); +} catch (e) { + var asn1 = require('../..'); +} + +/** + * RFC5280 X509 and Extension Definitions + */ + +var rfc5280 = exports; + +// OIDs +var x509OIDs = { + '2 5 29 9': 'subjectDirectoryAttributes', + '2 5 29 14': 'subjectKeyIdentifier', + '2 5 29 15': 'keyUsage', + '2 5 29 17': 'subjectAlternativeName', + '2 5 29 18': 'issuerAlternativeName', + '2 5 29 19': 'basicConstraints', + '2 5 29 20': 'cRLNumber', + '2 5 29 21': 'reasonCode', + '2 5 29 24': 'invalidityDate', + '2 5 29 27': 'deltaCRLIndicator', + '2 5 29 28': 'issuingDistributionPoint', + '2 5 29 29': 'certificateIssuer', + '2 5 29 30': 'nameConstraints', + '2 5 29 31': 'cRLDistributionPoints', + '2 5 29 32': 'certificatePolicies', + '2 5 29 33': 'policyMappings', + '2 5 29 35': 'authorityKeyIdentifier', + '2 5 29 36': 'policyConstraints', + '2 5 29 37': 'extendedKeyUsage', + '2 5 29 46': 'freshestCRL', + '2 5 29 54': 'inhibitAnyPolicy', + '1 3 6 1 5 5 7 1 1': 'authorityInformationAccess', + '1 3 6 1 5 5 7 11': 'subjectInformationAccess' +}; + +// CertificateList ::= SEQUENCE { +// tbsCertList TBSCertList, +// signatureAlgorithm AlgorithmIdentifier, +// signature BIT STRING } +var CertificateList = asn1.define('CertificateList', function() { + this.seq().obj( + this.key('tbsCertList').use(TBSCertList), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signature').bitstr() + ); +}); +rfc5280.CerficateList = CertificateList; + +// AlgorithmIdentifier ::= SEQUENCE { +// algorithm OBJECT IDENTIFIER, +// parameters ANY DEFINED BY algorithm OPTIONAL } +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function() { + this.seq().obj( + this.key('algorithm').objid(), + this.key('parameters').optional().any() + ); +}); +rfc5280.AlgorithmIdentifier = AlgorithmIdentifier; + +// Certificate ::= SEQUENCE { +// tbsCertificate TBSCertificate, +// signatureAlgorithm AlgorithmIdentifier, +// signature BIT STRING } +var Certificate = asn1.define('Certificate', function() { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signature').bitstr() + ); +}); +rfc5280.Certificate = Certificate; + +// TBSCertificate ::= SEQUENCE { +// version [0] Version DEFAULT v1, +// serialNumber CertificateSerialNumber, +// signature AlgorithmIdentifier, +// issuer Name, +// validity Validity, +// subject Name, +// subjectPublicKeyInfo SubjectPublicKeyInfo, +// issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, +// subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, +// extensions [3] Extensions OPTIONAL +var TBSCertificate = asn1.define('TBSCertificate', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).use(Version), + this.key('serialNumber').int(), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').optional().explicit(1).bitstr(), + this.key('subjectUniqueID').optional().explicit(2).bitstr(), + this.key('extensions').optional().explicit(3).seqof(Extension) + ); +}); +rfc5280.TBSCertificate = TBSCertificate; + +// Version ::= INTEGER { v1(0), v2(1), v3(2) } +var Version = asn1.define('Version', function() { + this.int({ + 0: 'v1', + 1: 'v2', + 2: 'v3' + }); +}); +rfc5280.Version = Version; + +// Validity ::= SEQUENCE { +// notBefore Time, +// notAfter Time } +var Validity = asn1.define('Validity', function() { + this.seq().obj( + this.key('notBefore').use(Time), + this.key('notAfter').use(Time) + ); +}); +rfc5280.Validity = Validity; + +// Time ::= CHOICE { +// utcTime UTCTime, +// generalTime GeneralizedTime } +var Time = asn1.define('Time', function() { + this.choice({ + utcTime: this.utctime(), + genTime: this.gentime() + }); +}); +rfc5280.Time = Time; + +// SubjectPublicKeyInfo ::= SEQUENCE { +// algorithm AlgorithmIdentifier, +// subjectPublicKey BIT STRING } +var SubjectPublicKeyInfo = asn1.define('SubjectPublicKeyInfo', function() { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ); +}); +rfc5280.SubjectPublicKeyInfo = SubjectPublicKeyInfo; + +// TBSCertList ::= SEQUENCE { +// version Version OPTIONAL, +// signature AlgorithmIdentifier, +// issuer Name, +// thisUpdate Time, +// nextUpdate Time OPTIONAL, +// revokedCertificates SEQUENCE OF SEQUENCE { +// userCertificate CertificateSerialNumber, +// revocationDate Time, +// crlEntryExtensions Extensions OPTIONAL +// } OPTIONAL, +// crlExtensions [0] Extensions OPTIONAL } +var TBSCertList = asn1.define('TBSCertList', function() { + this.seq().obj( + this.key('version').optional().int(), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('thisUpdate').use(Time), + this.key('nextUpdate').use(Time), + this.key('revokedCertificates').optional().seq().obj( + this.seq().obj( + this.key('userCertificate').int(), + this.key('revocationDate').use(Time), + this.key('crlEntryExtensions').optional().seqof(Extension) + ) + ), + this.key('crlExtensions').implicit(0).optional().seqof(Extension) + ); +}); +rfc5280.TBSCertList = TBSCertList; + +// Extension ::= SEQUENCE { +// extnID OBJECT IDENTIFIER, +// critical BOOLEAN DEFAULT FALSE, +// extnValue OCTET STRING } +var Extension = asn1.define('Extension', function() { + this.seq().obj( + this.key('extnID').objid(x509OIDs), + this.key('critical').bool().def(false), + this.key('extnValue').octstr().contains(function(obj) { + var out = x509Extensions[obj.extnID]; + // Cope with unknown extensions + return out ? out : asn1.define('OctString', function() { this.any() }) + }) + ); +}); +rfc5280.Extension = Extension; + +// Name ::= CHOICE { -- only one possibility for now -- +// rdnSequence RDNSequence } +var Name = asn1.define('Name', function() { + this.choice({ + rdnSequence: this.use(RDNSequence) + }); +}); +rfc5280.Name = Name; + +// GeneralName ::= CHOICE { +// otherName [0] AnotherName, +// rfc822Name [1] IA5String, +// dNSName [2] IA5String, +// x400Address [3] ORAddress, +// directoryName [4] Name, +// ediPartyName [5] EDIPartyName, +// uniformResourceIdentifier [6] IA5String, +// iPAddress [7] OCTET STRING, +// registeredID [8] OBJECT IDENTIFIER } +var GeneralName = asn1.define('GeneralName', function() { + this.choice({ + otherName: this.implicit(0).use(AnotherName), + rfc822Name: this.implicit(1).ia5str(), + dNSName: this.implicit(2).ia5str(), + directoryName: this.explicit(4).use(Name), + ediPartyName: this.implicit(5).use(EDIPartyName), + uniformResourceIdentifier: this.implicit(6).ia5str(), + iPAddress: this.implicit(7).octstr(), + registeredID: this.implicit(8).objid() + }); +}); +rfc5280.GeneralName = GeneralName; + +// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName +var GeneralNames = asn1.define('GeneralNames', function() { + this.seqof(GeneralName); +}); +rfc5280.GeneralNames = GeneralNames; + +// AnotherName ::= SEQUENCE { +// type-id OBJECT IDENTIFIER, +// value [0] EXPLICIT ANY DEFINED BY type-id } +var AnotherName = asn1.define('AnotherName', function() { + this.seq().obj( + this.key('type-id').objid(), + this.key('value').explicit(0).any() + ); +}); +rfc5280.AnotherName = AnotherName; + +// EDIPartyName ::= SEQUENCE { +// nameAssigner [0] DirectoryString OPTIONAL, +// partyName [1] DirectoryString } +var EDIPartyName = asn1.define('EDIPartyName', function() { + this.seq().obj( + this.key('nameAssigner').implicit(0).optional().use(DirectoryString), + this.key('partyName').implicit(1).use(DirectoryString) + ); +}); +rfc5280.EDIPartyName = EDIPartyName; + +// RDNSequence ::= SEQUENCE OF RelativeDistinguishedName +var RDNSequence = asn1.define('RDNSequence', function() { + this.seqof(RelativeDistinguishedName); +}); +rfc5280.RDNSequence = RDNSequence; + +// RelativeDistinguishedName ::= +// SET SIZE (1..MAX) OF AttributeTypeAndValue +var RelativeDistinguishedName = asn1.define('RelativeDistinguishedName', + function() { + this.setof(AttributeTypeAndValue); +}); +rfc5280.RelativeDistinguishedName = RelativeDistinguishedName; + +// AttributeTypeAndValue ::= SEQUENCE { +// type AttributeType, +// value AttributeValue } +var AttributeTypeAndValue = asn1.define('AttributeTypeAndValue', function() { + this.seq().obj( + this.key('type').use(AttributeType), + this.key('value').use(AttributeValue) + ); +}); +rfc5280.AttributeTypeAndValue = AttributeTypeAndValue; + +// Attribute ::= SEQUENCE { +// type AttributeType, +// values SET OF AttributeValue } +var Attribute = asn1.define('Attribute', function() { + this.seq().obj( + this.key('type').use(AttributeType), + this.key('values').setof(AttributeValue) + ); +}); +rfc5280.Attribute = Attribute; + +// AttributeType ::= OBJECT IDENTIFIER +var AttributeType = asn1.define('AttributeType', function() { + this.objid(); +}); +rfc5280.AttributeType = AttributeType; + +// AttributeValue ::= ANY -- DEFINED BY AttributeType +var AttributeValue = asn1.define('AttributeValue', function() { + this.any(); +}); +rfc5280.AttributeValue = AttributeValue; + +// DirectoryString ::= CHOICE { +// teletexString TeletexString (SIZE (1..MAX)), +// printableString PrintableString (SIZE (1..MAX)), +// universalString UniversalString (SIZE (1..MAX)), +// utf8String UTF8String (SIZE (1..MAX)), +// bmpString BMPString (SIZE (1..MAX)) } +var DirectoryString = asn1.define('DirectoryString', function() { + this.choice({ + teletexString: this.t61str(), + printableString: this.printstr(), + universalString: this.unistr(), + utf8String: this.utf8str(), + bmpString: this.bmpstr() + }); +}); +rfc5280.DirectoryString = DirectoryString; + +// AuthorityKeyIdentifier ::= SEQUENCE { +// keyIdentifier [0] KeyIdentifier OPTIONAL, +// authorityCertIssuer [1] GeneralNames OPTIONAL, +// authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL } +var AuthorityKeyIdentifier = asn1.define('AuthorityKeyIdentifier', function() { + this.seq().obj( + this.key('keyIdentifier').optional().use(KeyIdentifier), + this.key('authorityCertIssuer').optional().use(GeneralNames), + this.key('authorityCertSerialNumber').optional() + .use(CertificateSerialNumber) + ); +}); +rfc5280.AuthorityKeyIdentifier = AuthorityKeyIdentifier; + +// KeyIdentifier ::= OCTET STRING +var KeyIdentifier = asn1.define('KeyIdentifier', function() { + this.octstr(); +}); +rfc5280.KeyIdentifier = KeyIdentifier; + +// CertificateSerialNumber ::= INTEGER +var CertificateSerialNumber = asn1.define('CertificateSerialNumber', + function() { + this.int(); +}); +rfc5280.CertificateSerialNumber = CertificateSerialNumber; + +// ORAddress ::= SEQUENCE { +// built-in-standard-attributes BuiltInStandardAttributes, +// built-in-domain-defined-attributes BuiltInDomainDefinedAttributes +// OPTIONAL, +// extension-attributes ExtensionAttributes OPTIONAL } +var ORAddress = asn1.define('ORAddress', function() { + this.seq().obj( + this.key('builtInStandardAttributes').use(BuiltInStandardAttributes), + this.key('builtInDomainDefinedAttributes').optional() + .use(BuiltInDomainDefinedAttributes), + this.key('extensionAttributes').optional().use(ExtensionAttributes) + ); +}); +rfc5280.ORAddress = ORAddress; + +// BuiltInStandardAttributes ::= SEQUENCE { +// country-name CountryName OPTIONAL, +// administration-domain-name AdministrationDomainName OPTIONAL, +// network-address [0] IMPLICIT NetworkAddress OPTIONAL, +// terminal-identifier [1] IMPLICIT TerminalIdentifier OPTIONAL, +// private-domain-name [2] PrivateDomainName OPTIONAL, +// organization-name [3] IMPLICIT OrganizationName OPTIONAL, +// numeric-user-identifier [4] IMPLICIT NumericUserIdentifier OPTIONAL, +// personal-name [5] IMPLICIT PersonalName OPTIONAL, +// organizational-unit-names [6] IMPLICIT OrganizationalUnitNames OPTIONAL } +var BuiltInStandardAttributes = asn1.define('BuiltInStandardAttributes', + function() { + this.seq().obj( + this.key('countryName').optional().use(CountryName), + this.key('administrationDomainName').optional() + .use(AdministrationDomainName), + this.key('networkAddress').optional().use(NetworkAddress), + this.key('terminalIdentifier').optional().use(TerminalIdentifier), + this.key('privateDomainName').optional().use(PrivateDomainName), + this.key('organizationName').optional().use(OrganizationName), + this.key('numericUserIdentifier').optional().use(NumericUserIdentifier), + this.key('personalName').optional().use(PersonalName), + this.key('organizationalUnitNames').optional().use(OrganizationalUnitNames) + ); +}); +rfc5280.BuiltInStandardAttributes = BuiltInStandardAttributes; + +// CountryName ::= CHOICE { +// x121-dcc-code NumericString, +// iso-3166-alpha2-code PrintableString } +var CountryName = asn1.define('CountryName', function() { + this.choice({ + x121DccCode: this.numstr(), + iso3166Alpha2Code: this.printstr() + }); +}); +rfc5280.CountryName = CountryName; + + +// AdministrationDomainName ::= CHOICE { +// numeric NumericString, +// printable PrintableString } +var AdministrationDomainName = asn1.define('AdministrationDomainName', + function() { + this.choice({ + numeric: this.numstr(), + printable: this.printstr() + }); +}); +rfc5280.AdministrationDomainName = AdministrationDomainName; + +// NetworkAddress ::= X121Address +var NetworkAddress = asn1.define('NetworkAddress', function() { + this.use(X121Address); +}); +rfc5280.NetworkAddress = NetworkAddress; + +// X121Address ::= NumericString +var X121Address = asn1.define('X121Address', function() { + this.numstr(); +}); +rfc5280.X121Address = X121Address; + +// TerminalIdentifier ::= PrintableString +var TerminalIdentifier = asn1.define('TerminalIdentifier', function() { + this.printstr(); +}); +rfc5280.TerminalIdentifier = TerminalIdentifier; + +// PrivateDomainName ::= CHOICE { +// numeric NumericString, +// printable PrintableString } +var PrivateDomainName = asn1.define('PrivateDomainName', function() { + this.choice({ + numeric: this.numstr(), + printable: this.printstr() + }); +}); +rfc5280.PrivateDomainName = PrivateDomainName; + +// OrganizationName ::= PrintableString +var OrganizationName = asn1.define('OrganizationName', function() { + this.printstr(); +}); +rfc5280.OrganizationName = OrganizationName; + +// NumericUserIdentifier ::= NumericString +var NumericUserIdentifier = asn1.define('NumericUserIdentifier', function() { + this.numstr(); +}); +rfc5280.NumericUserIdentifier = NumericUserIdentifier; + +// PersonalName ::= SET { +// surname [0] IMPLICIT PrintableString, +// given-name [1] IMPLICIT PrintableString OPTIONAL, +// initials [2] IMPLICIT PrintableString OPTIONAL, +// generation-qualifier [3] IMPLICIT PrintableString OPTIONAL } +var PersonalName = asn1.define('PersonalName', function() { + this.set().obj( + this.key('surname').implicit().printstr(), + this.key('givenName').implicit().printstr(), + this.key('initials').implicit().printstr(), + this.key('generationQualifier').implicit().printstr() + ); +}); +rfc5280.PersonalName = PersonalName; + +// OrganizationalUnitNames ::= SEQUENCE SIZE (1..ub-organizational-units) +// OF OrganizationalUnitName +var OrganizationalUnitNames = asn1.define('OrganizationalUnitNames', + function() { + this.seqof(OrganizationalUnitName); +}); +rfc5280.OrganizationalUnitNames = OrganizationalUnitNames; + +// OrganizationalUnitName ::= PrintableString (SIZE +// (1..ub-organizational-unit-name-length)) +var OrganizationalUnitName = asn1.define('OrganizationalUnitName', function() { + this.printstr(); +}); +rfc5280.OrganizationalUnitName = OrganizationalUnitName; + +// uiltInDomainDefinedAttributes ::= SEQUENCE SIZE +// (1..ub-domain-defined-attributes) +// OF BuiltInDomainDefinedAttribute +var BuiltInDomainDefinedAttributes = asn1.define( + 'BuiltInDomainDefinedAttributes', function() { + this.seqof(BuiltInDomainDefinedAttribute); +}); +rfc5280.BuiltInDomainDefinedAttributes = BuiltInDomainDefinedAttributes; + +// BuiltInDomainDefinedAttribute ::= SEQUENCE { +// type PrintableString (SIZE (1..ub-domain-defined-attribute-type-length)), +// value PrintableString (SIZE (1..ub-domain-defined-attribute-value-length)) +//} +var BuiltInDomainDefinedAttribute = asn1.define('BuiltInDomainDefinedAttribute', + function() { + this.seq().obj( + this.key('type').printstr(), + this.key('value').printstr() + ); +}); +rfc5280.BuiltInDomainDefinedAttribute = BuiltInDomainDefinedAttribute; + + +// ExtensionAttributes ::= SET SIZE (1..ub-extension-attributes) OF +// ExtensionAttribute +var ExtensionAttributes = asn1.define('ExtensionAttributes', function() { + this.seqof(ExtensionAttribute); +}); +rfc5280.ExtensionAttributes = ExtensionAttributes; + +// ExtensionAttribute ::= SEQUENCE { +// extension-attribute-type [0] IMPLICIT INTEGER, +// extension-attribute-value [1] ANY DEFINED BY extension-attribute-type } +var ExtensionAttribute = asn1.define('ExtensionAttribute', function() { + this.seq().obj( + this.key('extensionAttributeType').implicit().int(), + this.key('extensionAttributeValue').any().implicit().int() + ); +}); +rfc5280.ExtensionAttribute = ExtensionAttribute; + +// SubjectKeyIdentifier ::= KeyIdentifier +var SubjectKeyIdentifier = asn1.define('SubjectKeyIdentifier', function() { + this.use(KeyIdentifier); +}); +rfc5280.SubjectKeyIdentifier = SubjectKeyIdentifier; + +// KeyUsage ::= BIT STRING { +// digitalSignature (0), +// nonRepudiation (1), -- recent editions of X.509 have +// -- renamed this bit to contentCommitment +// keyEncipherment (2), +// dataEncipherment (3), +// keyAgreement (4), +// keyCertSign (5), +// cRLSign (6), +// encipherOnly (7), +// decipherOnly (8) } +var KeyUsage = asn1.define('KeyUsage', function() { + this.bitstr(); +}); +rfc5280.KeyUsage = KeyUsage; + +// CertificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation +var CertificatePolicies = asn1.define('CertificatePolicies', function() { + this.seqof(PolicyInformation); +}); +rfc5280.CertificatePolicies = CertificatePolicies; + +// PolicyInformation ::= SEQUENCE { +// policyIdentifier CertPolicyId, +// policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo +// OPTIONAL } +var PolicyInformation = asn1.define('PolicyInformation', function() { + this.seq().obj( + this.key('policyIdentifier').use(CertPolicyId), + this.key('policyQualifiers').optional().use(PolicyQualifiers) + ); +}); +rfc5280.PolicyInformation = PolicyInformation; + +// CertPolicyId ::= OBJECT IDENTIFIER +var CertPolicyId = asn1.define('CertPolicyId', function() { + this.objid(); +}); +rfc5280.CertPolicyId = CertPolicyId; + +var PolicyQualifiers = asn1.define('PolicyQualifiers', function() { + this.seqof(PolicyQualifierInfo); +}); +rfc5280.PolicyQualifiers = PolicyQualifiers; + +// PolicyQualifierInfo ::= SEQUENCE { +// policyQualifierId PolicyQualifierId, +// qualifier ANY DEFINED BY policyQualifierId } +var PolicyQualifierInfo = asn1.define('PolicyQualifierInfo', function() { + this.seq().obj( + this.key('policyQualifierId').use(PolicyQualifierId), + this.key('qualifier').any().use(PolicyQualifierId) + ); +}); +rfc5280.PolicyQualifierInfo = PolicyQualifierInfo; + +// PolicyQualifierId ::= OBJECT IDENTIFIER +var PolicyQualifierId = asn1.define('PolicyQualifierId', function() { + this.objid(); +}); +rfc5280.PolicyQualifierId = PolicyQualifierId; + +// PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF SEQUENCE { +// issuerDomainPolicy CertPolicyId, +// subjectDomainPolicy CertPolicyId } +var PolicyMappings = asn1.define('PolicyMappings', function() { + this.seqof(PolicyMapping); +}); +rfc5280.PolicyMappings = PolicyMappings; + +var PolicyMapping = asn1.define('PolicyMapping', function() { + this.seq().obj( + this.key('issuerDomainPolicy').use(CertPolicyId), + this.key('subjectDomainPolicy').use(CertPolicyId) + ); +}); +rfc5280.PolicyMapping = PolicyMapping; + +// SubjectAltName ::= GeneralNames +var SubjectAlternativeName = asn1.define('SubjectAlternativeName', function() { + this.use(GeneralNames); +}); +rfc5280.SubjectAlternativeName = SubjectAlternativeName; + +// IssuerAltName ::= GeneralNames +var IssuerAlternativeName = asn1.define('IssuerAlternativeName', function() { + this.use(GeneralNames); +}); +rfc5280.IssuerAlternativeName = IssuerAlternativeName; + +// SubjectDirectoryAttributes ::= SEQUENCE SIZE (1..MAX) OF Attribute +var SubjectDirectoryAttributes = asn1.define('SubjectDirectoryAttributes', + function() { + this.seqof(Attribute); +}); +rfc5280.SubjectDirectoryAttributes = SubjectDirectoryAttributes; + +// BasicConstraints ::= SEQUENCE { +// cA BOOLEAN DEFAULT FALSE, +// pathLenConstraint INTEGER (0..MAX) OPTIONAL } +var BasicConstraints = asn1.define('BasicConstraints', function() { + this.seq().obj( + this.key('cA').bool().def(false), + this.key('pathLenConstraint').optional().int() + ); +}); +rfc5280.BasicConstraints = BasicConstraints; + +// NameConstraints ::= SEQUENCE { +// permittedSubtrees [0] GeneralSubtrees OPTIONAL, +// excludedSubtrees [1] GeneralSubtrees OPTIONAL } +var NameConstraints = asn1.define('NameConstraints', function() { + this.seq().obj( + this.key('permittedSubtrees').implicit(0).optional().use(GeneralSubtrees), + this.key('excludedSubtrees').implicit(1).optional().use(GeneralSubtrees) + ); +}); +rfc5280.NameConstraints = NameConstraints; + +// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree +var GeneralSubtrees = asn1.define('GeneralSubtrees', function() { + this.seqof(GeneralSubtree); +}); +rfc5280.GeneralSubtrees = GeneralSubtrees; + +// GeneralSubtree ::= SEQUENCE { +// base GeneralName, +// minimum [0] BaseDistance DEFAULT 0, +// maximum [1] BaseDistance OPTIONAL } +var GeneralSubtree = asn1.define('GeneralSubtree', function() { + this.seq().obj( + this.key('base').use(GeneralName), + this.key('minimum').default(0).use(BaseDistance), + this.key('maximum').optional().use(BaseDistance) + ); +}); +rfc5280.GeneralSubtree = GeneralSubtree; + +// BaseDistance ::= INTEGER +var BaseDistance = asn1.define('BaseDistance', function() { + this.int(); +}); +rfc5280.BaseDistance = BaseDistance; + +// PolicyConstraints ::= SEQUENCE { +// requireExplicitPolicy [0] SkipCerts OPTIONAL, +// inhibitPolicyMapping [1] SkipCerts OPTIONAL } +var PolicyConstraints = asn1.define('PolicyConstraints', function() { + this.seq().obj( + this.key('requireExplicitPolicy').implicit(0).optional().use(SkipCerts), + this.key('inhibitPolicyMapping').implicit(1).optional().use(SkipCerts) + ); +}); +rfc5280.PolicyConstraints = PolicyConstraints; + +// SkipCerts ::= INTEGER +var SkipCerts = asn1.define('SkipCerts', function() { + this.int(); +}); +rfc5280.SkipCerts = SkipCerts; + +// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId +var ExtendedKeyUsage = asn1.define('ExtendedKeyUsage', function() { + this.seqof(KeyPurposeId); +}); +rfc5280.ExtendedKeyUsage = ExtendedKeyUsage; + +// KeyPurposeId ::= OBJECT IDENTIFIER +var KeyPurposeId = asn1.define('KeyPurposeId', function() { + this.objid(); +}); +rfc5280.KeyPurposeId = KeyPurposeId; + +// RLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint +var CRLDistributionPoints = asn1.define('CRLDistributionPoints', function() { + this.seqof(DistributionPoint); +}); +rfc5280.CRLDistributionPoints = CRLDistributionPoints; + +// DistributionPoint ::= SEQUENCE { +// distributionPoint [0] DistributionPointName OPTIONAL, +// reasons [1] ReasonFlags OPTIONAL, +// cRLIssuer [2] GeneralNames OPTIONAL } +var DistributionPoint = asn1.define('DistributionPoint', function() { + this.seq().obj( + this.key('distributionPoint').optional().use(DistributionPointName), + this.key('reasons').optional().use(ReasonFlags), + this.key('cRLIssuer').optional().use(GeneralNames) + ); +}); +rfc5280.DistributionPoint = DistributionPoint; + +// DistributionPointName ::= CHOICE { +// fullName [0] GeneralNames, +// nameRelativeToCRLIssuer [1] RelativeDistinguishedName } +var DistributionPointName = asn1.define('DistributionPointName', function() { + this.choice({ + fullName: this.implicit(0).use(GeneralNames), + nameRelativeToCRLIssuer: this.implicit(1).use(RelativeDistinguishedName) + }); +}); +rfc5280.DistributionPointName = DistributionPointName; + +// ReasonFlags ::= BIT STRING { +// unused (0), +// keyCompromise (1), +// cACompromise (2), +// affiliationChanged (3), +// superseded (4), +// cessationOfOperation (5), +// certificateHold (6), +// privilegeWithdrawn (7), +// aACompromise (8) } +var ReasonFlags = asn1.define('ReasonFlags', function() { + this.bitstr(); +}); +rfc5280.ReasonFlags = ReasonFlags; + +// InhibitAnyPolicy ::= SkipCerts +var InhibitAnyPolicy = asn1.define('InhibitAnyPolicy', function() { + this.use(SkipCerts); +}); +rfc5280.InhibitAnyPolicy = InhibitAnyPolicy; + +// FreshestCRL ::= CRLDistributionPoints +var FreshestCRL = asn1.define('FreshestCRL', function() { + this.use(CRLDistributionPoints); +}); +rfc5280.FreshestCRL = FreshestCRL; + +// AuthorityInfoAccessSyntax ::= +// SEQUENCE SIZE (1..MAX) OF AccessDescription +var AuthorityInfoAccessSyntax = asn1.define('AuthorityInfoAccessSyntax', + function() { + this.seqof(AccessDescription); +}); +rfc5280.AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax; + +// AccessDescription ::= SEQUENCE { +// accessMethod OBJECT IDENTIFIER, +// accessLocation GeneralName } +var AccessDescription = asn1.define('AccessDescription', function() { + this.seq().obj( + this.key('accessMethod').objid(), + this.key('accessLocation').use(GeneralName) + ); +}); +rfc5280.AccessDescription = AccessDescription; + +// SubjectInfoAccessSyntax ::= +// SEQUENCE SIZE (1..MAX) OF AccessDescription +var SubjectInformationAccess = asn1.define('SubjectInformationAccess', + function() { + this.seqof(AccessDescription); +}); +rfc5280.SubjectInformationAccess = SubjectInformationAccess; + +/** + * CRL Extensions + */ + +// CRLNumber ::= INTEGER +var CRLNumber = asn1.define('CRLNumber', function() { + this.int(); +}); +rfc5280.CRLNumber = CRLNumber; + +var DeltaCRLIndicator = asn1.define('DeltaCRLIndicator', function() { + this.use(CRLNumber); +}); +rfc5280.DeltaCRLIndicator = DeltaCRLIndicator; + +// IssuingDistributionPoint ::= SEQUENCE { +// distributionPoint [0] DistributionPointName OPTIONAL, +// onlyContainsUserCerts [1] BOOLEAN DEFAULT FALSE, +// onlyContainsCACerts [2] BOOLEAN DEFAULT FALSE, +// onlySomeReasons [3] ReasonFlags OPTIONAL, +// indirectCRL [4] BOOLEAN DEFAULT FALSE, +// onlyContainsAttributeCerts [5] BOOLEAN DEFAULT FALSE } +var IssuingDistributionPoint = asn1.define('IssuingDistributionPoint', + function() { + this.seq().obj( + this.key('distributionPoint').use(DistributionPointName), + this.key('onlyContainsUserCerts').def(false).bool(), + this.key('onlyContainsCACerts').def(false).bool(), + this.key('onlySomeReasons').use(ReasonFlags), + this.key('indirectCRL').def(false).bool(), + this.key('onlyContainsAttributeCerts').def(false).bool() + ); +}); +rfc5280.IssuingDistributionPoint = IssuingDistributionPoint; + +// CRLReason ::= ENUMERATED { +// unspecified (0), +// keyCompromise (1), +// cACompromise (2), +// affiliationChanged (3), +// superseded (4), +// cessationOfOperation (5), +// certificateHold (6), +// -- value 7 is not used +// removeFromCRL (8), +// privilegeWithdrawn (9), +// aACompromise (10) } +var ReasonCode = asn1.define('ReasonCode', function() { + this.enum(); +}); +rfc5280.ReasonCode = ReasonCode; + +// InvalidityDate ::= GeneralizedTime +var InvalidityDate = asn1.define('InvalidityDate', function() { + this.gentime(); +}); +rfc5280.InvalidityDate = InvalidityDate; + +// CertificateIssuer ::= GeneralNames +var CertificateIssuer = asn1.define('CertificateIssuer', function() { + this.use(GeneralNames); +}); +rfc5280.CertificateIssuer = CertificateIssuer; + +// OID label to extension model mapping +var x509Extensions = { + subjectDirectoryAttributes: SubjectDirectoryAttributes, + subjectKeyIdentifier: SubjectKeyIdentifier, + keyUsage: KeyUsage, + subjectAlternativeName: SubjectAlternativeName, + issuerAlternativeName: IssuerAlternativeName, + basicConstraints: BasicConstraints, + cRLNumber: CRLNumber, + reasonCode: ReasonCode, + invalidityDate: InvalidityDate, + deltaCRLIndicator: DeltaCRLIndicator, + issuingDistributionPoint: IssuingDistributionPoint, + certificateIssuer: CertificateIssuer, + nameConstraints: NameConstraints, + cRLDistributionPoints: CRLDistributionPoints, + certificatePolicies: CertificatePolicies, + policyMappings: PolicyMappings, + authorityKeyIdentifier: AuthorityKeyIdentifier, + policyConstraints: PolicyConstraints, + extendedKeyUsage: ExtendedKeyUsage, + freshestCRL: FreshestCRL, + inhibitAnyPolicy: InhibitAnyPolicy, + authorityInformationAccess: AuthorityInfoAccessSyntax, + subjectInformationAccess: SubjectInformationAccess +}; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/package.json new file mode 100644 index 0000000..42cdca2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/package.json @@ -0,0 +1,24 @@ +{ + "name": "asn1.js-rfc5280", + "version": "1.0.0", + "description": "RFC5280 extension structures for asn1.js", + "main": "index.js", + "repository": { + "type": "git", + "url": "git@github.com:indutny/asn1.js" + }, + "keywords": [ + "asn1", + "rfc5280", + "der" + ], + "author": "Felix Hanley", + "license": "MIT", + "bugs": { + "url": "https://github.com/indutny/asn1.js/issues" + }, + "homepage": "https://github.com/indutny/asn1.js", + "dependencies": { + "asn1.js": "^4.5.0" + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/basic-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/basic-test.js new file mode 100644 index 0000000..3ce8ed9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/basic-test.js @@ -0,0 +1,105 @@ +var assert = require('assert'); +var fs = require('fs'); +var asn1 = require('../../../'); +var rfc5280 = require('..'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js RFC5280', function() { + + it('should decode Certificate', function() { + var data = fs.readFileSync(__dirname + '/fixtures/cert1.crt'); + var res = rfc5280.Certificate.decode(data, 'der'); + + var tbs = res.tbsCertificate; + assert.equal(tbs.version, 'v3'); + assert.deepEqual(tbs.serialNumber, + new asn1.bignum('462e4256bb1194dc', 16)); + assert.equal(tbs.signature.algorithm.join('.'), + '1.2.840.113549.1.1.5'); + assert.equal(tbs.signature.parameters.toString('hex'), '0500'); + }); + + it('should decode ECC Certificate', function() { + // Symantec Class 3 ECC 256 bit Extended Validation CA from + // https://knowledge.symantec.com/support/ssl-certificates-support/index?page=content&actp=CROSSLINK&id=AR1908 + var data = fs.readFileSync(__dirname + '/fixtures/cert2.crt'); + var res = rfc5280.Certificate.decode(data, 'der'); + + var tbs = res.tbsCertificate; + assert.equal(tbs.version, 'v3'); + assert.deepEqual(tbs.serialNumber, + new asn1.bignum('4d955d20af85c49f6925fbab7c665f89', 16)); + assert.equal(tbs.signature.algorithm.join('.'), + '1.2.840.10045.4.3.3'); // RFC5754 + var spki = rfc5280.SubjectPublicKeyInfo.encode(tbs.subjectPublicKeyInfo, + 'der'); +// spki check to the output of +// openssl x509 -in ecc_cert.pem -pubkey -noout | +// openssl pkey -pubin -outform der | openssl base64 + assert.equal(spki.toString('base64'), + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE3QQ9svKQk5fG6bu8kdtR8KO' + + 'G7fvG04WTMgVJ4ASDYZZR/1chrgvaDucEoX/bKhy9ypg1xXFzQM3oaqtUhE' + + 'Mm4g==' + ); + }); + + it('should decode AuthorityInfoAccess', function() { + var data = new Buffer('305a302b06082b06010505073002861f687474703a2f2f70' + + '6b692e676f6f676c652e636f6d2f47494147322e63727430' + + '2b06082b06010505073001861f687474703a2f2f636c6965' + + '6e7473312e676f6f676c652e636f6d2f6f637370', + 'hex'); + + var info = rfc5280.AuthorityInfoAccessSyntax.decode(data, 'der'); + + assert(info[0].accessMethod); + }); + + it('should decode directoryName in GeneralName', function() { + var data = new Buffer('a411300f310d300b06022a03160568656c6c6f', 'hex'); + + var name = rfc5280.GeneralName.decode(data, 'der'); + assert.equal(name.type, 'directoryName'); + }); + + it('should decode Certificate Extensions', function() { + var data; + var cert; + + var extensions = {} + data = fs.readFileSync(__dirname + '/fixtures/cert3.crt'); + cert = rfc5280.Certificate.decode(data, 'der'); + cert.tbsCertificate.extensions.forEach(function(e) { + extensions[e.extnID] = e + }); + assert.equal(extensions.basicConstraints.extnValue.cA, false); + assert.equal(extensions.extendedKeyUsage.extnValue.length, 2); + + extensions = {} + data = fs.readFileSync(__dirname + '/fixtures/cert4.crt'); + cert = rfc5280.Certificate.decode(data, 'der'); + cert.tbsCertificate.extensions.forEach(function(e) { + extensions[e.extnID] = e + }); + assert.equal(extensions.basicConstraints.extnValue.cA, true); + assert.equal(extensions.authorityInformationAccess.extnValue[0] + .accessLocation.value, 'http://ocsp.godaddy.com/') + + extensions = {} + data = fs.readFileSync(__dirname + '/fixtures/cert5.crt'); + cert = rfc5280.Certificate.decode(data, 'der'); + cert.tbsCertificate.extensions.forEach(function(e) { + extensions[e.extnID] = e + }); + assert.equal(extensions.basicConstraints.extnValue.cA, true); + + extensions = {} + data = fs.readFileSync(__dirname + '/fixtures/cert6.crt'); + cert = rfc5280.Certificate.decode(data, 'der'); + cert.tbsCertificate.extensions.forEach(function(e) { + extensions[e.extnID] = e + }); + assert.equal(extensions.basicConstraints.extnValue.cA, true); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert1.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert1.crt new file mode 100644 index 0000000..35447cf Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert1.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert2.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert2.crt new file mode 100644 index 0000000..bf9eff1 Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert2.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert3.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert3.crt new file mode 100644 index 0000000..218a8a0 Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert3.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert4.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert4.crt new file mode 100644 index 0000000..885c45a Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert4.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert5.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert5.crt new file mode 100644 index 0000000..0ba053c Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert5.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert6.crt b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert6.crt new file mode 100644 index 0000000..3cd289b Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/rfc/5280/test/fixtures/cert6.crt differ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/der-decode-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/der-decode-test.js new file mode 100644 index 0000000..0f1ad86 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/der-decode-test.js @@ -0,0 +1,149 @@ +var assert = require('assert'); +var asn1 = require('..'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js DER decoder', function() { + it('should propagate implicit tag', function() { + var B = asn1.define('B', function() { + this.seq().obj( + this.key('b').octstr() + ); + }); + + var A = asn1.define('Bug', function() { + this.seq().obj( + this.key('a').implicit(0).use(B) + ); + }); + + var out = A.decode(new Buffer('300720050403313233', 'hex'), 'der'); + assert.equal(out.a.b.toString(), '123'); + }); + + it('should decode optional tag to undefined key', function() { + var A = asn1.define('A', function() { + this.seq().obj( + this.key('key').bool(), + this.optional().key('opt').bool() + ); + }); + var out = A.decode(new Buffer('30030101ff', 'hex'), 'der'); + assert.deepEqual(out, { 'key': true }); + }); + + it('should decode optional tag to default value', function() { + var A = asn1.define('A', function() { + this.seq().obj( + this.key('key').bool(), + this.optional().key('opt').octstr().def('default') + ); + }); + var out = A.decode(new Buffer('30030101ff', 'hex'), 'der'); + assert.deepEqual(out, { 'key': true, 'opt': 'default' }); + }); + + function test(name, model, inputHex, expected) { + it(name, function() { + var M = asn1.define('Model', model); + var decoded = M.decode(new Buffer(inputHex,'hex'), 'der'); + assert.deepEqual(decoded, expected); + }); + } + + test('should decode choice', function() { + this.choice({ + apple: this.bool(), + }); + }, '0101ff', { 'type': 'apple', 'value': true }); + + it('should decode optional and use', function() { + var B = asn1.define('B', function() { + this.int(); + }); + + var A = asn1.define('A', function() { + this.optional().use(B); + }); + + var out = A.decode(new Buffer('020101', 'hex'), 'der'); + assert.equal(out.toString(10), '1'); + }); + + test('should decode indefinite length', function() { + this.seq().obj( + this.key('key').bool() + ); + }, '30800101ff0000', { 'key': true }); + + test('should decode bmpstr', function() { + this.bmpstr(); + }, '1e26004300650072007400690066006900630061' + + '0074006500540065006d0070006c006100740065', 'CertificateTemplate'); + + test('should decode bmpstr with cyrillic chars', function() { + this.bmpstr(); + }, '1e0c041f04400438043204350442', 'Привет'); + + test('should properly decode objid with dots', function() { + this.objid({ + '1.2.398.3.10.1.1.1.2.2': 'yes' + }); + }, '060a2a830e030a0101010202', 'yes'); + + it('should decode encapsulated models', function() { + var B = asn1.define('B', function() { + this.seq().obj( + this.key('nested').int() + ); + }); + var A = asn1.define('A', function() { + this.octstr().contains(B); + }); + + var out = A.decode(new Buffer('04053003020105', 'hex'), 'der'); + assert.equal(out.nested.toString(10), '5'); + }); + + test('should decode IA5 string', function() { + this.ia5str(); + }, '160C646F6720616E6420626F6E65', 'dog and bone'); + + test('should decode printable string', function() { + this.printstr(); + }, '1310427261686D7320616E64204C69737A74', 'Brahms and Liszt'); + + test('should decode T61 string', function() { + this.t61str(); + }, '140C4F6C69766572205477697374', 'Oliver Twist'); + + test('should decode ISO646 string', function() { + this.iso646str(); + }, '1A0B7365707469632074616E6B', 'septic tank'); + + it('should decode optional seqof', function() { + var B = asn1.define('B', function() { + this.seq().obj( + this.key('num').int() + ); + }); + var A = asn1.define('A', function() { + this.seq().obj( + this.key('test1').seqof(B), + this.key('test2').optional().seqof(B) + ); + }); + + var out = A.decode(new Buffer( + '3018300A30030201013003020102300A30030201033003020104', 'hex'), 'der'); + assert.equal(out.test1[0].num.toString(10), 1); + assert.equal(out.test1[1].num.toString(10), 2); + assert.equal(out.test2[0].num.toString(10), 3); + assert.equal(out.test2[1].num.toString(10), 4); + + out = A.decode(new Buffer('300C300A30030201013003020102', 'hex'), 'der'); + assert.equal(out.test1[0].num.toString(10), 1); + assert.equal(out.test1[1].num.toString(10), 2); + assert.equal(out.test2, undefined); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/der-encode-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/der-encode-test.js new file mode 100644 index 0000000..af37293 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/der-encode-test.js @@ -0,0 +1,133 @@ +var assert = require('assert'); +var asn1 = require('..'); +var BN = require('bn.js'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js DER encoder', function() { + /* + * Explicit value shold be wrapped with A0 | EXPLICIT tag + * this adds two more bytes to resulting buffer. + * */ + it('should code explicit tag as 0xA2', function() { + var E = asn1.define('E', function() { + this.explicit(2).octstr() + }); + + var encoded = E.encode('X', 'der'); + + // + assert.equal(encoded.toString('hex'), 'a203040158'); + assert.equal(encoded.length, 5); + }) + + function test(name, model_definition, model_value, der_expected) { + it(name, function() { + var Model, der_actual; + Model = asn1.define('Model', model_definition); + der_actual = Model.encode(model_value, 'der'); + assert.deepEqual(der_actual, new Buffer(der_expected,'hex')); + }); + } + + test('should encode choice', function() { + this.choice({ + apple: this.bool(), + }); + }, { type: 'apple', value: true }, '0101ff'); + + test('should encode implicit seqof', function() { + var Int = asn1.define('Int', function() { + this.int(); + }); + this.implicit(0).seqof(Int); + }, [ 1 ], 'A003020101' ); + + test('should encode explicit seqof', function() { + var Int = asn1.define('Int', function() { + this.int(); + }); + this.explicit(0).seqof(Int); + }, [ 1 ], 'A0053003020101' ); + + test('should encode BN(128) properly', function() { + this.int(); + }, new BN(128), '02020080'); + + test('should encode int 128 properly', function() { + this.int(); + }, 128, '02020080'); + + test('should encode 0x8011 properly', function() { + this.int(); + }, 0x8011, '0203008011'); + + test('should omit default value in DER', function() { + this.seq().obj( + this.key('required').def(false).bool(), + this.key('value').int() + ); + }, {required: false, value: 1}, '3003020101'); + + it('should encode optional and use', function() { + var B = asn1.define('B', function() { + this.int(); + }); + + var A = asn1.define('A', function() { + this.optional().use(B); + }); + + var out = A.encode(1, 'der'); + assert.equal(out.toString('hex'), '020101'); + }); + + test('should properly encode objid with dots', function() { + this.objid({ + '1.2.398.3.10.1.1.1.2.2': 'yes' + }); + }, 'yes', '060a2a830e030a0101010202'); + + test('should properly encode objid as array of strings', function() { + this.objid(); + }, '1.2.398.3.10.1.1.1.2.2'.split('.'), '060a2a830e030a0101010202'); + + test('should properly encode bmpstr', function() { + this.bmpstr(); + }, 'CertificateTemplate', '1e26004300650072007400690066006900630061' + + '0074006500540065006d0070006c006100740065'); + + test('should properly encode bmpstr with cyrillic chars', function() { + this.bmpstr(); + }, 'Привет', '1e0c041f04400438043204350442'); + + it('should encode encapsulated models', function() { + var B = asn1.define('B', function() { + this.seq().obj( + this.key('nested').int() + ); + }); + var A = asn1.define('A', function() { + this.octstr().contains(B); + }); + + var out = A.encode({ nested: 5 }, 'der') + assert.equal(out.toString('hex'), '04053003020105'); + }); + + test('should properly encode IA5 string', function() { + this.ia5str(); + }, 'dog and bone', '160C646F6720616E6420626F6E65'); + + test('should properly encode printable string', function() { + this.printstr(); + }, 'Brahms and Liszt', '1310427261686D7320616E64204C69737A74'); + + test('should properly encode T61 string', function() { + this.t61str(); + }, 'Oliver Twist', '140C4F6C69766572205477697374'); + + test('should properly encode ISO646 string', function() { + this.iso646str(); + }, 'septic tank', '1A0B7365707469632074616E6B'); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/error-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/error-test.js new file mode 100644 index 0000000..9892905 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/error-test.js @@ -0,0 +1,222 @@ +var assert = require('assert'); +var asn1 = require('..'); +var bn = asn1.bignum; +var fixtures = require('./fixtures'); +var jsonEqual = fixtures.jsonEqual; + +var Buffer = require('buffer').Buffer; + +describe('asn1.js error', function() { + describe('encoder', function() { + function test(name, model, input, expected) { + it('should support ' + name, function() { + var M = asn1.define('TestModel', model); + + var error; + assert.throws(function() { + try { + var encoded = M.encode(input, 'der'); + } catch (e) { + error = e; + throw e; + } + }); + + assert(expected.test(error.stack), + 'Failed to match, expected: ' + expected + ' got: ' + + JSON.stringify(error.stack)); + }); + } + + describe('primitives', function() { + test('int', function() { + this.int(); + }, 'hello', /no values map/i); + + test('enum', function() { + this.enum({ 0: 'hello', 1: 'world' }); + }, 'gosh', /contain: "gosh"/); + + test('objid', function() { + this.objid(); + }, 1, /objid\(\) should be either array or string, got: 1/); + + test('numstr', function() { + this.numstr(); + }, 'hello', /only digits and space/); + + test('printstr', function() { + this.printstr(); + }, 'hello!', /only latin upper and lower case letters/); + }); + + describe('composite', function() { + test('shallow', function() { + this.seq().obj( + this.key('key').int() + ); + }, { key: 'hello' } , /map at: \["key"\]/i); + + test('deep and empty', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ) + ) + ); + }, { } , /input is not object at: \["a"\]\["b"\]/i); + + test('deep', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ) + ) + ); + }, { a: { b: { c: 'hello' } } } , /map at: \["a"\]\["b"\]\["c"\]/i); + + test('use', function() { + var S = asn1.define('S', function() { + this.seq().obj( + this.key('x').int() + ); + }); + + this.seq().obj( + this.key('a').seq().obj( + this.key('b').use(S) + ) + ); + }, { a: { b: { x: 'hello' } } } , /map at: \["a"\]\["b"\]\["x"\]/i); + }); + }); + + describe('decoder', function() { + function test(name, model, input, expected) { + it('should support ' + name, function() { + var M = asn1.define('TestModel', model); + + var error; + assert.throws(function() { + try { + var decoded = M.decode(new Buffer(input, 'hex'), 'der'); + } catch (e) { + error = e; + throw e; + } + }); + var partial = M.decode(new Buffer(input, 'hex'), 'der', { + partial: true + }); + + assert(expected.test(error.stack), + 'Failed to match, expected: ' + expected + ' got: ' + + JSON.stringify(error.stack)); + + assert.equal(partial.errors.length, 1); + assert(expected.test(partial.errors[0].stack), + 'Failed to match, expected: ' + expected + ' got: ' + + JSON.stringify(partial.errors[0].stack)); + }); + } + + describe('primitive', function() { + test('int', function() { + this.int(); + }, '2201', /body of: "int"/); + + test('int', function() { + this.int(); + }, '', /tag of "int"/); + + test('bmpstr invalid length', function() { + this.bmpstr(); + }, '1e0b041f04400438043204350442', /bmpstr length mismatch/); + + test('numstr unsupported characters', function() { + this.numstr(); + }, '12024141', /numstr unsupported characters/); + + test('printstr unsupported characters', function() { + this.printstr(); + }, '13024121', /printstr unsupported characters/); + }); + + describe('composite', function() { + test('shallow', function() { + this.seq().obj( + this.key('a').seq().obj() + ); + }, '30', /length of "seq"/); + + test('deep and empty', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ) + ) + ); + }, '300430023000', /tag of "int" at: \["a"\]\["b"\]\["c"\]/); + + test('deep and incomplete', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ) + ) + ); + }, '30053003300122', /length of "int" at: \["a"\]\["b"\]\["c"\]/); + }); + }); + + describe('partial decoder', function() { + function test(name, model, input, expectedObj, expectedErrs) { + it('should support ' + name, function() { + var M = asn1.define('TestModel', model); + + var decoded = M.decode(new Buffer(input, 'hex'), 'der', { + partial: true + }); + + jsonEqual(decoded.result, expectedObj); + + assert.equal(decoded.errors.length, expectedErrs.length); + expectedErrs.forEach(function(expected, i) { + assert(expected.test(decoded.errors[i].stack), + 'Failed to match, expected: ' + expected + ' got: ' + + JSON.stringify(decoded.errors[i].stack)); + }); + }); + } + + test('last key not present', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ), + this.key('d').int() + ) + ); + }, '30073005300022012e', { a: { b: {}, d: new bn(46) } }, [ + /"int" at: \["a"\]\["b"\]\["c"\]/ + ]); + + test('first key not present', function() { + this.seq().obj( + this.key('a').seq().obj( + this.key('b').seq().obj( + this.key('c').int() + ), + this.key('d').int() + ) + ); + }, '30073005300322012e', { a: { b: { c: new bn(46) } } }, [ + /"int" at: \["a"\]\["d"\]/ + ]); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/fixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/fixtures.js new file mode 100644 index 0000000..9ee4db6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/fixtures.js @@ -0,0 +1,7 @@ +var assert = require('assert'); + +function jsonEqual(a, b) { + assert.deepEqual(JSON.parse(JSON.stringify(a)), + JSON.parse(JSON.stringify(b))); +} +exports.jsonEqual = jsonEqual; diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/pem-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/pem-test.js new file mode 100644 index 0000000..dfbe7db --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/pem-test.js @@ -0,0 +1,54 @@ +var assert = require('assert'); +var asn1 = require('..'); +var BN = require('bn.js'); + +var Buffer = require('buffer').Buffer; + +describe('asn1.js PEM encoder/decoder', function() { + var model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('b').bitstr(), + this.key('c').int() + ); + }); + + var hundred = new Buffer(100); + hundred.fill('A'); + + it('should encode PEM', function() { + + var out = model.encode({ + a: new BN(123), + b: { + data: hundred, + unused: 0 + }, + c: new BN(456) + }, 'pem', { + label: 'MODEL' + }); + + var expected = + '-----BEGIN MODEL-----\n' + + 'MG4CAXsDZQBBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n' + + 'QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n' + + 'QUFBQUFBQUFBQUFBAgIByA==\n' + + '-----END MODEL-----'; + assert.equal(out, expected); + }); + + it('should decode PEM', function() { + var expected = + '-----BEGIN MODEL-----\n' + + 'MG4CAXsDZQBBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n' + + 'QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\n' + + 'QUFBQUFBQUFBQUFBAgIByA==\n' + + '-----END MODEL-----'; + + var out = model.decode(expected, 'pem', { label: 'MODEL' }); + assert.equal(out.a.toString(), '123'); + assert.equal(out.b.data.toString(), hundred.toString()); + assert.equal(out.c.toString(), '456'); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/ping-pong-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/ping-pong-test.js new file mode 100644 index 0000000..0e2be0a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/ping-pong-test.js @@ -0,0 +1,170 @@ +var assert = require('assert'); +var asn1 = require('..'); +var fixtures = require('./fixtures'); +var jsonEqual = fixtures.jsonEqual; + +var Buffer = require('buffer').Buffer; + +describe('asn1.js ping/pong', function() { + function test(name, model, input, expected) { + it('should support ' + name, function() { + var M = asn1.define('TestModel', model); + + var encoded = M.encode(input, 'der'); + var decoded = M.decode(encoded, 'der'); + jsonEqual(decoded, expected !== undefined ? expected : input); + }); + } + + describe('primitives', function() { + test('bigint', function() { + this.int(); + }, new asn1.bignum('0102030405060708', 16)); + + test('enum', function() { + this.enum({ 0: 'hello', 1: 'world' }); + }, 'world'); + + test('octstr', function() { + this.octstr(); + }, new Buffer('hello')); + + test('bitstr', function() { + this.bitstr(); + }, { unused: 4, data: new Buffer('hello!') }); + + test('ia5str', function() { + this.ia5str(); + }, 'hello'); + + test('utf8str', function() { + this.utf8str(); + }, 'hello'); + + test('bmpstr', function() { + this.bmpstr(); + }, 'hello'); + + test('numstr', function() { + this.numstr(); + }, '1234 5678 90'); + + test('printstr', function() { + this.printstr(); + }, 'hello'); + + test('gentime', function() { + this.gentime(); + }, 1385921175000); + + test('utctime', function() { + this.utctime(); + }, 1385921175000); + + test('utctime regression', function() { + this.utctime(); + }, 1414454400000); + + test('null', function() { + this.null_(); + }, null); + + test('objid', function() { + this.objid({ + '1 3 6 1 5 5 7 48 1 1': 'id-pkix-ocsp-basic' + }); + }, 'id-pkix-ocsp-basic'); + + test('true', function() { + this.bool(); + }, true); + + test('false', function() { + this.bool(); + }, false); + + test('any', function() { + this.any(); + }, new Buffer('02210081347a0d3d674aeeb563061d94a3aea5f6a7' + + 'c6dc153ea90a42c1ca41929ac1b9', 'hex')); + + test('default explicit', function() { + this.seq().obj( + this.key('version').def('v1').explicit(0).int({ + 0: 'v1', + 1: 'v2' + }) + ); + }, {}, {'version': 'v1'}); + + test('implicit', function() { + this.implicit(0).int({ + 0: 'v1', + 1: 'v2' + }); + }, 'v2', 'v2'); + }); + + describe('composite', function() { + test('2x int', function() { + this.seq().obj( + this.key('hello').int(), + this.key('world').int() + ); + }, { hello: 4, world: 2 }); + + test('enum', function() { + this.seq().obj( + this.key('hello').enum({ 0: 'world', 1: 'devs' }) + ); + }, { hello: 'devs' }); + + test('optionals', function() { + this.seq().obj( + this.key('hello').enum({ 0: 'world', 1: 'devs' }), + this.key('how').optional().def('are you').enum({ + 0: 'are you', + 1: 'are we?!' + }) + ); + }, { hello: 'devs', how: 'are we?!' }); + + test('optionals #2', function() { + this.seq().obj( + this.key('hello').enum({ 0: 'world', 1: 'devs' }), + this.key('how').optional().def('are you').enum({ + 0: 'are you', + 1: 'are we?!' + }) + ); + }, { hello: 'devs' }, { hello: 'devs', how: 'are you' }); + + test('optionals #3', function() { + this.seq().obj( + this.key('content').optional().int() + ); + }, {}, {}); + + test('optional + any', function() { + this.seq().obj( + this.key('content').optional().any() + ); + }, { content: new Buffer('0500', 'hex') }); + + test('seqof', function() { + var S = asn1.define('S', function() { + this.seq().obj( + this.key('a').def('b').int({ 0: 'a', 1: 'b' }), + this.key('c').def('d').int({ 2: 'c', 3: 'd' }) + ); + }); + this.seqof(S); + }, [{}, { a: 'a', c: 'c' }], [{ a: 'b', c: 'd' }, { a: 'a', c: 'c' }]); + + test('choice', function() { + this.choice({ + apple: this.bool() + }); + }, { type: 'apple', value: true }); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/use-test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/use-test.js new file mode 100644 index 0000000..93e088a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/asn1.js/test/use-test.js @@ -0,0 +1,128 @@ +var assert = require('assert'); +var asn1 = require('..'); +var bn = asn1.bignum; +var fixtures = require('./fixtures'); +var jsonEqual = fixtures.jsonEqual; + +var Buffer = require('buffer').Buffer; + +describe('asn1.js models', function() { + describe('plain use', function() { + it('should encode submodel', function() { + var SubModel = asn1.define('SubModel', function() { + this.seq().obj( + this.key('b').octstr() + ); + }); + var Model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('sub').use(SubModel) + ); + }); + + var data = {a: new bn(1), sub: {b: new Buffer("XXX")}}; + var wire = Model.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300a02010130050403585858'); + var back = Model.decode(wire, 'der'); + jsonEqual(back, data); + }); + + it('should honour implicit tag from parent', function() { + var SubModel = asn1.define('SubModel', function() { + this.seq().obj( + this.key('x').octstr() + ) + }); + var Model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('sub').use(SubModel).implicit(0) + ); + }); + + var data = {a: new bn(1), sub: {x: new Buffer("123")}}; + var wire = Model.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300a020101a0050403313233'); + var back = Model.decode(wire, 'der'); + jsonEqual(back, data); + }); + + it('should honour explicit tag from parent', function() { + var SubModel = asn1.define('SubModel', function() { + this.seq().obj( + this.key('x').octstr() + ) + }); + var Model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('sub').use(SubModel).explicit(0) + ); + }); + + var data = {a: new bn(1), sub: {x: new Buffer("123")}}; + var wire = Model.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300c020101a00730050403313233'); + var back = Model.decode(wire, 'der'); + jsonEqual(back, data); + + }); + + it('should get model with function call', function() { + var SubModel = asn1.define('SubModel', function() { + this.seq().obj( + this.key('x').octstr() + ) + }); + var Model = asn1.define('Model', function() { + this.seq().obj( + this.key('a').int(), + this.key('sub').use(function(obj) { + assert.equal(obj.a, 1); + return SubModel; + }) + ); + }); + + var data = {a: new bn(1), sub: {x: new Buffer("123")}}; + var wire = Model.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300a02010130050403313233'); + var back = Model.decode(wire, 'der'); + jsonEqual(back, data); + + }); + + it('should support recursive submodels', function() { + var PlainSubModel = asn1.define('PlainSubModel', function() { + this.int(); + }); + var RecursiveModel = asn1.define('RecursiveModel', function() { + this.seq().obj( + this.key('plain').bool(), + this.key('content').use(function(obj) { + if(obj.plain) { + return PlainSubModel; + } else { + return RecursiveModel; + } + }) + ); + }); + + var data = { + 'plain': false, + 'content': { + 'plain': true, + 'content': new bn(1) + } + }; + var wire = RecursiveModel.encode(data, 'der'); + assert.equal(wire.toString('hex'), '300b01010030060101ff020101'); + var back = RecursiveModel.decode(wire, 'der'); + jsonEqual(back, data); + }); + + }); +}); + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.eslintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.eslintrc new file mode 100644 index 0000000..bed248a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.eslintrc @@ -0,0 +1,132 @@ +{ + "ecmaFeatures": { + "modules": true, + "experimentalObjectRestSpread": true + }, + + "env": { + "browser": false, + "es6": true, + "node": true + }, + + "plugins": [ + "standard" + ], + + "globals": { + "document": false, + "navigator": false, + "window": false + }, + + "rules": { + "accessor-pairs": 2, + "arrow-spacing": [2, { "before": true, "after": true }], + "block-spacing": [2, "always"], + "brace-style": [2, "1tbs", { "allowSingleLine": true }], + "comma-dangle": [2, "never"], + "comma-spacing": [2, { "before": false, "after": true }], + "comma-style": [2, "last"], + "constructor-super": 2, + "curly": [2, "multi-line"], + "dot-location": [2, "property"], + "eol-last": 2, + "eqeqeq": [2, "allow-null"], + "generator-star-spacing": [2, { "before": true, "after": true }], + "handle-callback-err": [2, "^(err|error)$" ], + "indent": [2, 2, { "SwitchCase": 1 }], + "key-spacing": [2, { "beforeColon": false, "afterColon": true }], + "new-cap": [2, { "newIsCap": true, "capIsNew": false }], + "new-parens": 2, + "no-array-constructor": 2, + "no-caller": 2, + "no-class-assign": 2, + "no-cond-assign": 2, + "no-const-assign": 2, + "no-control-regex": 2, + "no-debugger": 2, + "no-delete-var": 2, + "no-dupe-args": 2, + "no-dupe-class-members": 2, + "no-dupe-keys": 2, + "no-duplicate-case": 2, + "no-empty-character-class": 2, + "no-empty-label": 2, + "no-eval": 2, + "no-ex-assign": 2, + "no-extend-native": 2, + "no-extra-bind": 2, + "no-extra-boolean-cast": 2, + "no-extra-parens": [2, "functions"], + "no-fallthrough": 2, + "no-floating-decimal": 2, + "no-func-assign": 2, + "no-implied-eval": 2, + "no-inner-declarations": [2, "functions"], + "no-invalid-regexp": 2, + "no-irregular-whitespace": 2, + "no-iterator": 2, + "no-label-var": 2, + "no-labels": 2, + "no-lone-blocks": 2, + "no-mixed-spaces-and-tabs": 2, + "no-multi-spaces": 2, + "no-multi-str": 2, + "no-multiple-empty-lines": [2, { "max": 1 }], + "no-native-reassign": 2, + "no-negated-in-lhs": 2, + "no-new": 2, + "no-new-func": 2, + "no-new-object": 2, + "no-new-require": 2, + "no-new-wrappers": 2, + "no-obj-calls": 2, + "no-octal": 2, + "no-octal-escape": 2, + "no-proto": 2, + "no-redeclare": 2, + "no-regex-spaces": 2, + "no-return-assign": 2, + "no-self-compare": 2, + "no-sequences": 2, + "no-shadow-restricted-names": 2, + "no-spaced-func": 2, + "no-sparse-arrays": 2, + "no-this-before-super": 2, + "no-throw-literal": 2, + "no-trailing-spaces": 2, + "no-undef": 2, + "no-undef-init": 2, + "no-unexpected-multiline": 2, + "no-unneeded-ternary": [2, { "defaultAssignment": false }], + "no-unreachable": 2, + "no-unused-vars": [2, { "vars": "all", "args": "none" }], + "no-useless-call": 2, + "no-with": 2, + "one-var": [2, { "initialized": "never" }], + "operator-linebreak": [2, "after", { "overrides": { "?": "before", ":": "before" } }], + "padded-blocks": [2, "never"], + "quotes": [2, "single", "avoid-escape"], + "radix": 2, + "semi": [2, "never"], + "semi-spacing": [2, { "before": false, "after": true }], + "space-after-keywords": [2, "always"], + "space-before-blocks": [2, "always"], + "space-before-function-paren": [2, "always"], + "space-before-keywords": [2, "always"], + "space-in-parens": [2, "never"], + "space-infix-ops": 2, + "space-return-throw-case": 2, + "space-unary-ops": [2, { "words": true, "nonwords": false }], + "spaced-comment": [2, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }], + "use-isnan": 2, + "valid-typeof": 2, + "wrap-iife": [2, "any"], + "yoda": [2, "never"], + + "standard/object-curly-even-spacing": [2, "either"], + "standard/array-bracket-even-spacing": [2, "either"], + "standard/computed-property-even-spacing": [2, "even"] + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.npmignore new file mode 100644 index 0000000..65e3ba2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.npmignore @@ -0,0 +1 @@ +test/ diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/LICENSE new file mode 100644 index 0000000..924b38b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 browserify-aes contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/aes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/aes.js new file mode 100644 index 0000000..4829057 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/aes.js @@ -0,0 +1,177 @@ +// based on the aes implimentation in triple sec +// https://github.com/keybase/triplesec + +// which is in turn based on the one from crypto-js +// https://code.google.com/p/crypto-js/ + +var uint_max = Math.pow(2, 32) +function fixup_uint32 (x) { + var ret, x_pos + ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x + return ret +} +function scrub_vec (v) { + for (var i = 0; i < v.length; v++) { + v[i] = 0 + } + return false +} + +function Global () { + this.SBOX = [] + this.INV_SBOX = [] + this.SUB_MIX = [[], [], [], []] + this.INV_SUB_MIX = [[], [], [], []] + this.init() + this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] +} + +Global.prototype.init = function () { + var d, i, sx, t, x, x2, x4, x8, xi, _i + d = (function () { + var _i, _results + _results = [] + for (i = _i = 0; _i < 256; i = ++_i) { + if (i < 128) { + _results.push(i << 1) + } else { + _results.push((i << 1) ^ 0x11b) + } + } + return _results + })() + x = 0 + xi = 0 + for (i = _i = 0; _i < 256; i = ++_i) { + sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 + this.SBOX[x] = sx + this.INV_SBOX[sx] = x + x2 = d[x] + x4 = d[x2] + x8 = d[x4] + t = (d[sx] * 0x101) ^ (sx * 0x1010100) + this.SUB_MIX[0][x] = (t << 24) | (t >>> 8) + this.SUB_MIX[1][x] = (t << 16) | (t >>> 16) + this.SUB_MIX[2][x] = (t << 8) | (t >>> 24) + this.SUB_MIX[3][x] = t + t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) + this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) + this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) + this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) + this.INV_SUB_MIX[3][sx] = t + if (x === 0) { + x = xi = 1 + } else { + x = x2 ^ d[d[d[x8 ^ x2]]] + xi ^= d[d[xi]] + } + } + return true +} + +var G = new Global() + +AES.blockSize = 4 * 4 + +AES.prototype.blockSize = AES.blockSize + +AES.keySize = 256 / 8 + +AES.prototype.keySize = AES.keySize + +function bufferToArray (buf) { + var len = buf.length / 4 + var out = new Array(len) + var i = -1 + while (++i < len) { + out[i] = buf.readUInt32BE(i * 4) + } + return out +} +function AES (key) { + this._key = bufferToArray(key) + this._doReset() +} + +AES.prototype._doReset = function () { + var invKsRow, keySize, keyWords, ksRow, ksRows, t + keyWords = this._key + keySize = keyWords.length + this._nRounds = keySize + 6 + ksRows = (this._nRounds + 1) * 4 + this._keySchedule = [] + for (ksRow = 0; ksRow < ksRows; ksRow++) { + this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t) + } + this._invKeySchedule = [] + for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { + ksRow = ksRows - invKsRow + t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)] + this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]] + } + return true +} + +AES.prototype.encryptBlock = function (M) { + M = bufferToArray(new Buffer(M)) + var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} + +AES.prototype.decryptBlock = function (M) { + M = bufferToArray(new Buffer(M)) + var temp = [M[3], M[1]] + M[1] = temp[0] + M[3] = temp[1] + var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[3], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[1], 12) + return buf +} + +AES.prototype.scrub = function () { + scrub_vec(this._keySchedule) + scrub_vec(this._invKeySchedule) + scrub_vec(this._key) +} + +AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) { + var ksRow, s0, s1, s2, s3, t0, t1, t2, t3 + + s0 = M[0] ^ keySchedule[0] + s1 = M[1] ^ keySchedule[1] + s2 = M[2] ^ keySchedule[2] + s3 = M[3] ^ keySchedule[3] + ksRow = 4 + for (var round = 1; round < this._nRounds; round++) { + t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++] + t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++] + t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + s2 = t2 + s3 = t3 + } + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] + t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] + t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + return [ + fixup_uint32(t0), + fixup_uint32(t1), + fixup_uint32(t2), + fixup_uint32(t3) + ] +} + +exports.AES = AES diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/authCipher.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/authCipher.js new file mode 100644 index 0000000..1107a01 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/authCipher.js @@ -0,0 +1,97 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var GHASH = require('./ghash') +var xor = require('buffer-xor') +inherits(StreamCipher, Transform) +module.exports = StreamCipher + +function StreamCipher (mode, key, iv, decrypt) { + if (!(this instanceof StreamCipher)) { + return new StreamCipher(mode, key, iv) + } + Transform.call(this) + this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])]) + iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])]) + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + this._cache = new Buffer('') + this._secCache = new Buffer('') + this._decrypt = decrypt + this._alen = 0 + this._len = 0 + iv.copy(this._prev) + this._mode = mode + var h = new Buffer(4) + h.fill(0) + this._ghash = new GHASH(this._cipher.encryptBlock(h)) + this._authTag = null + this._called = false +} +StreamCipher.prototype._update = function (chunk) { + if (!this._called && this._alen) { + var rump = 16 - (this._alen % 16) + if (rump < 16) { + rump = new Buffer(rump) + rump.fill(0) + this._ghash.update(rump) + } + } + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) + } else { + this._ghash.update(out) + } + this._len += chunk.length + return out +} +StreamCipher.prototype._final = function () { + if (this._decrypt && !this._authTag) { + throw new Error('Unsupported state or unable to authenticate data') + } + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) + if (this._decrypt) { + if (xorTest(tag, this._authTag)) { + throw new Error('Unsupported state or unable to authenticate data') + } + } else { + this._authTag = tag + } + this._cipher.scrub() +} +StreamCipher.prototype.getAuthTag = function getAuthTag () { + if (!this._decrypt && Buffer.isBuffer(this._authTag)) { + return this._authTag + } else { + throw new Error('Attempting to get auth tag in unsupported state') + } +} +StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { + if (this._decrypt) { + this._authTag = tag + } else { + throw new Error('Attempting to set auth tag in unsupported state') + } +} +StreamCipher.prototype.setAAD = function setAAD (buf) { + if (!this._called) { + this._ghash.update(buf) + this._alen += buf.length + } else { + throw new Error('Attempting to set AAD in unsupported state') + } +} +function xorTest (a, b) { + var out = 0 + if (a.length !== b.length) { + out++ + } + var len = Math.min(a.length, b.length) + var i = -1 + while (++i < len) { + out += (a[i] ^ b[i]) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/browser.js new file mode 100644 index 0000000..a058a84 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/browser.js @@ -0,0 +1,11 @@ +var ciphers = require('./encrypter') +exports.createCipher = exports.Cipher = ciphers.createCipher +exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv +var deciphers = require('./decrypter') +exports.createDecipher = exports.Decipher = deciphers.createDecipher +exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv +var modes = require('./modes') +function getCiphers () { + return Object.keys(modes) +} +exports.listCiphers = exports.getCiphers = getCiphers diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/decrypter.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/decrypter.js new file mode 100644 index 0000000..b7b8bb0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/decrypter.js @@ -0,0 +1,137 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var modes = require('./modes') +var StreamCipher = require('./streamCipher') +var AuthCipher = require('./authCipher') +var ebtk = require('evp_bytestokey') + +inherits(Decipher, Transform) +function Decipher (mode, key, iv) { + if (!(this instanceof Decipher)) { + return new Decipher(mode, key, iv) + } + Transform.call(this) + this._cache = new Splitter() + this._last = void 0 + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + iv.copy(this._prev) + this._mode = mode + this._autopadding = true +} +Decipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get(this._autopadding))) { + thing = this._mode.decrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} +Decipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)) + } else if (chunk) { + throw new Error('data not multiple of block length') + } +} +Decipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} +function Splitter () { + if (!(this instanceof Splitter)) { + return new Splitter() + } + this.cache = new Buffer('') +} +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function (autoPadding) { + var out + if (autoPadding) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } + return null +} +Splitter.prototype.flush = function () { + if (this.cache.length) { + return this.cache + } +} +function unpad (last) { + var padded = last[15] + var i = -1 + while (++i < padded) { + if (last[(i + (16 - padded))] !== padded) { + throw new Error('unable to decrypt data') + } + } + if (padded === 16) { + return + } + return last.slice(0, 16 - padded) +} + +var modelist = { + ECB: require('./modes/ecb'), + CBC: require('./modes/cbc'), + CFB: require('./modes/cfb'), + CFB8: require('./modes/cfb8'), + CFB1: require('./modes/cfb1'), + OFB: require('./modes/ofb'), + CTR: require('./modes/ctr'), + GCM: require('./modes/ctr') +} + +function createDecipheriv (suite, password, iv) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + if (typeof iv === 'string') { + iv = new Buffer(iv) + } + if (typeof password === 'string') { + password = new Buffer(password) + } + if (password.length !== config.key / 8) { + throw new TypeError('invalid key length ' + password.length) + } + if (iv.length !== config.iv) { + throw new TypeError('invalid iv length ' + iv.length) + } + if (config.type === 'stream') { + return new StreamCipher(modelist[config.mode], password, iv, true) + } else if (config.type === 'auth') { + return new AuthCipher(modelist[config.mode], password, iv, true) + } + return new Decipher(modelist[config.mode], password, iv) +} + +function createDecipher (suite, password) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, config.key, config.iv) + return createDecipheriv(suite, keys.key, keys.iv) +} +exports.createDecipher = createDecipher +exports.createDecipheriv = createDecipheriv diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/encrypter.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/encrypter.js new file mode 100644 index 0000000..3d3f561 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/encrypter.js @@ -0,0 +1,122 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') +var modes = require('./modes') +var ebtk = require('evp_bytestokey') +var StreamCipher = require('./streamCipher') +var AuthCipher = require('./authCipher') +inherits(Cipher, Transform) +function Cipher (mode, key, iv) { + if (!(this instanceof Cipher)) { + return new Cipher(mode, key, iv) + } + Transform.call(this) + this._cache = new Splitter() + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + iv.copy(this._prev) + this._mode = mode + this._autopadding = true +} +Cipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get())) { + thing = this._mode.encrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} +Cipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + chunk = this._mode.encrypt(this, chunk) + this._cipher.scrub() + return chunk + } else if (chunk.toString('hex') !== '10101010101010101010101010101010') { + this._cipher.scrub() + throw new Error('data not multiple of block length') + } +} +Cipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + if (!(this instanceof Splitter)) { + return new Splitter() + } + this.cache = new Buffer('') +} +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function () { + if (this.cache.length > 15) { + var out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + return null +} +Splitter.prototype.flush = function () { + var len = 16 - this.cache.length + var padBuff = new Buffer(len) + + var i = -1 + while (++i < len) { + padBuff.writeUInt8(len, i) + } + var out = Buffer.concat([this.cache, padBuff]) + return out +} +var modelist = { + ECB: require('./modes/ecb'), + CBC: require('./modes/cbc'), + CFB: require('./modes/cfb'), + CFB8: require('./modes/cfb8'), + CFB1: require('./modes/cfb1'), + OFB: require('./modes/ofb'), + CTR: require('./modes/ctr'), + GCM: require('./modes/ctr') +} + +function createCipheriv (suite, password, iv) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + if (typeof iv === 'string') { + iv = new Buffer(iv) + } + if (typeof password === 'string') { + password = new Buffer(password) + } + if (password.length !== config.key / 8) { + throw new TypeError('invalid key length ' + password.length) + } + if (iv.length !== config.iv) { + throw new TypeError('invalid iv length ' + iv.length) + } + if (config.type === 'stream') { + return new StreamCipher(modelist[config.mode], password, iv) + } else if (config.type === 'auth') { + return new AuthCipher(modelist[config.mode], password, iv) + } + return new Cipher(modelist[config.mode], password, iv) +} +function createCipher (suite, password) { + var config = modes[suite.toLowerCase()] + if (!config) { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, config.key, config.iv) + return createCipheriv(suite, keys.key, keys.iv) +} + +exports.createCipheriv = createCipheriv +exports.createCipher = createCipher diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/ghash.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/ghash.js new file mode 100644 index 0000000..0ca143c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/ghash.js @@ -0,0 +1,98 @@ +var zeros = new Buffer(16) +zeros.fill(0) +module.exports = GHASH +function GHASH (key) { + this.h = key + this.state = new Buffer(16) + this.state.fill(0) + this.cache = new Buffer('') +} +// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html +// by Juho Vähä-Herttua +GHASH.prototype.ghash = function (block) { + var i = -1 + while (++i < block.length) { + this.state[i] ^= block[i] + } + this._multiply() +} + +GHASH.prototype._multiply = function () { + var Vi = toArray(this.h) + var Zi = [0, 0, 0, 0] + var j, xi, lsb_Vi + var i = -1 + while (++i < 128) { + xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0 + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi = xor(Zi, Vi) + } + + // Store the value of LSB(V_i) + lsb_Vi = (Vi[3] & 1) !== 0 + + // V_i+1 = V_i >> 1 + for (j = 3; j > 0; j--) { + Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) + } + Vi[0] = Vi[0] >>> 1 + + // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R + if (lsb_Vi) { + Vi[0] = Vi[0] ^ (0xe1 << 24) + } + } + this.state = fromArray(Zi) +} +GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + this.ghash(chunk) + } +} +GHASH.prototype.final = function (abl, bl) { + if (this.cache.length) { + this.ghash(Buffer.concat([this.cache, zeros], 16)) + } + this.ghash(fromArray([ + 0, abl, + 0, bl + ])) + return this.state +} + +function toArray (buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] +} +function fromArray (out) { + out = out.map(fixup_uint32) + var buf = new Buffer(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} +var uint_max = Math.pow(2, 32) +function fixup_uint32 (x) { + var ret, x_pos + ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x + return ret +} +function xor (a, b) { + return [ + a[0] ^ b[0], + a[1] ^ b[1], + a[2] ^ b[2], + a[3] ^ b[3] + ] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/index.js new file mode 100644 index 0000000..58fa883 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/index.js @@ -0,0 +1,7 @@ +var crypto = require('crypto') + +exports.createCipher = exports.Cipher = crypto.createCipher +exports.createCipheriv = exports.Cipheriv = crypto.createCipheriv +exports.createDecipher = exports.Decipher = crypto.createDecipher +exports.createDecipheriv = exports.Decipheriv = crypto.createDecipheriv +exports.listCiphers = exports.getCiphers = crypto.getCiphers diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes.js new file mode 100644 index 0000000..c070086 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes.js @@ -0,0 +1,171 @@ +exports['aes-128-ecb'] = { + cipher: 'AES', + key: 128, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-192-ecb'] = { + cipher: 'AES', + key: 192, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-256-ecb'] = { + cipher: 'AES', + key: 256, + iv: 0, + mode: 'ECB', + type: 'block' +} +exports['aes-128-cbc'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes-192-cbc'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes-256-cbc'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CBC', + type: 'block' +} +exports['aes128'] = exports['aes-128-cbc'] +exports['aes192'] = exports['aes-192-cbc'] +exports['aes256'] = exports['aes-256-cbc'] +exports['aes-128-cfb'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-192-cfb'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-256-cfb'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB', + type: 'stream' +} +exports['aes-128-cfb8'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-192-cfb8'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-256-cfb8'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB8', + type: 'stream' +} +exports['aes-128-cfb1'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-192-cfb1'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-256-cfb1'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CFB1', + type: 'stream' +} +exports['aes-128-ofb'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-192-ofb'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-256-ofb'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'OFB', + type: 'stream' +} +exports['aes-128-ctr'] = { + cipher: 'AES', + key: 128, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-192-ctr'] = { + cipher: 'AES', + key: 192, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-256-ctr'] = { + cipher: 'AES', + key: 256, + iv: 16, + mode: 'CTR', + type: 'stream' +} +exports['aes-128-gcm'] = { + cipher: 'AES', + key: 128, + iv: 12, + mode: 'GCM', + type: 'auth' +} +exports['aes-192-gcm'] = { + cipher: 'AES', + key: 192, + iv: 12, + mode: 'GCM', + type: 'auth' +} +exports['aes-256-gcm'] = { + cipher: 'AES', + key: 256, + iv: 12, + mode: 'GCM', + type: 'auth' +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cbc.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cbc.js new file mode 100644 index 0000000..b133e40 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cbc.js @@ -0,0 +1,17 @@ +var xor = require('buffer-xor') + +exports.encrypt = function (self, block) { + var data = xor(block, self._prev) + + self._prev = self._cipher.encryptBlock(data) + return self._prev +} + +exports.decrypt = function (self, block) { + var pad = self._prev + + self._prev = block + var out = self._cipher.decryptBlock(block) + + return xor(out, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb.js new file mode 100644 index 0000000..0bfe4fa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb.js @@ -0,0 +1,31 @@ +var xor = require('buffer-xor') + +exports.encrypt = function (self, data, decrypt) { + var out = new Buffer('') + var len + + while (data.length) { + if (self._cache.length === 0) { + self._cache = self._cipher.encryptBlock(self._prev) + self._prev = new Buffer('') + } + + if (self._cache.length <= data.length) { + len = self._cache.length + out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) + data = data.slice(len) + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]) + break + } + } + + return out +} +function encryptStart (self, data, decrypt) { + var len = data.length + var out = xor(data, self._cache) + self._cache = self._cache.slice(len) + self._prev = Buffer.concat([self._prev, decrypt ? data : out]) + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb1.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb1.js new file mode 100644 index 0000000..335542e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb1.js @@ -0,0 +1,34 @@ +function encryptByte (self, byteParam, decrypt) { + var pad + var i = -1 + var len = 8 + var out = 0 + var bit, value + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev) + bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 + value = pad[0] ^ bit + out += ((value & 0x80) >> (i % 8)) + self._prev = shiftIn(self._prev, decrypt ? bit : value) + } + return out +} +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = new Buffer(len) + var i = -1 + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + return out +} +function shiftIn (buffer, value) { + var len = buffer.length + var i = -1 + var out = new Buffer(buffer.length) + buffer = Buffer.concat([buffer, new Buffer([value])]) + while (++i < len) { + out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb8.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb8.js new file mode 100644 index 0000000..c967a95 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/cfb8.js @@ -0,0 +1,15 @@ +function encryptByte (self, byteParam, decrypt) { + var pad = self._cipher.encryptBlock(self._prev) + var out = pad[0] ^ byteParam + self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])]) + return out +} +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = new Buffer(len) + var i = -1 + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ctr.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ctr.js new file mode 100644 index 0000000..0ef2278 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ctr.js @@ -0,0 +1,31 @@ +var xor = require('buffer-xor') + +function incr32 (iv) { + var len = iv.length + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } +} + +function getBlock (self) { + var out = self._cipher.encryptBlock(self._prev) + incr32(self._prev) + return out +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ecb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ecb.js new file mode 100644 index 0000000..4dd97e7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ecb.js @@ -0,0 +1,6 @@ +exports.encrypt = function (self, block) { + return self._cipher.encryptBlock(block) +} +exports.decrypt = function (self, block) { + return self._cipher.decryptBlock(block) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ofb.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ofb.js new file mode 100644 index 0000000..bd87558 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/modes/ofb.js @@ -0,0 +1,16 @@ +var xor = require('buffer-xor') + +function getBlock (self) { + self._prev = self._cipher.encryptBlock(self._prev) + return self._prev +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml new file mode 100644 index 0000000..d9f695b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +before_install: + - "npm install npm -g" +node_js: + - "0.12" +env: + - TEST_SUITE=standard + - TEST_SUITE=unit +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE new file mode 100644 index 0000000..bba5218 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Daniel Cousens + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/README.md new file mode 100644 index 0000000..007f058 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/README.md @@ -0,0 +1,41 @@ +# buffer-xor + +[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-xor.png)](http://travis-ci.org/crypto-browserify/buffer-xor) +[![NPM](http://img.shields.io/npm/v/buffer-xor.svg)](https://www.npmjs.org/package/buffer-xor) + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +A simple module for bitwise-xor on buffers. + + +## Examples + +``` javascript +var xor = require("buffer-xor") +var a = new Buffer('00ff0f', 'hex') +var b = new Buffer('f0f0', 'hex') + +console.log(xor(a, b)) +// => +``` + + +Or for those seeking those few extra cycles, perform the operation in place: + +``` javascript +var xorInplace = require("buffer-xor/inplace") +var a = new Buffer('00ff0f', 'hex') +var b = new Buffer('f0f0', 'hex') + +console.log(xorInplace(a, b)) +// => +// NOTE: xorInplace will return the shorter slice of its parameters + +// See that a has been mutated +console.log(a) +// => +``` + + +## License [MIT](LICENSE) + diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/index.js new file mode 100644 index 0000000..85ee6f6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/index.js @@ -0,0 +1,10 @@ +module.exports = function xor (a, b) { + var length = Math.min(a.length, b.length) + var buffer = new Buffer(length) + + for (var i = 0; i < length; ++i) { + buffer[i] = a[i] ^ b[i] + } + + return buffer +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inline.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inline.js new file mode 100644 index 0000000..8797570 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inline.js @@ -0,0 +1 @@ +module.exports = require('./inplace') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js new file mode 100644 index 0000000..d71c172 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/inplace.js @@ -0,0 +1,9 @@ +module.exports = function xorInplace (a, b) { + var length = Math.min(a.length, b.length) + + for (var i = 0; i < length; ++i) { + a[i] = a[i] ^ b[i] + } + + return a.slice(0, length) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/package.json new file mode 100644 index 0000000..31c573c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/package.json @@ -0,0 +1,45 @@ +{ + "name": "buffer-xor", + "version": "1.0.3", + "description": "A simple module for bitwise-xor on buffers", + "main": "index.js", + "scripts": { + "standard": "standard", + "test": "npm run-script unit", + "unit": "mocha" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/buffer-xor.git" + }, + "bugs": { + "url": "https://github.com/crypto-browserify/buffer-xor/issues" + }, + "homepage": "https://github.com/crypto-browserify/buffer-xor", + "keywords": [ + "bits", + "bitwise", + "buffer", + "buffer-xor", + "crypto", + "inline", + "math", + "memory", + "performance", + "xor" + ], + "author": { + "name": "Daniel Cousens" + }, + "license": "MIT", + "devDependencies": { + "mocha": "*", + "standard": "*" + }, + "readme": "# buffer-xor\n\n[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-xor.png)](http://travis-ci.org/crypto-browserify/buffer-xor)\n[![NPM](http://img.shields.io/npm/v/buffer-xor.svg)](https://www.npmjs.org/package/buffer-xor)\n\n[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n\nA simple module for bitwise-xor on buffers.\n\n\n## Examples\n\n``` javascript\nvar xor = require(\"buffer-xor\")\nvar a = new Buffer('00ff0f', 'hex')\nvar b = new Buffer('f0f0', 'hex')\n\nconsole.log(xor(a, b))\n// => \n```\n\n\nOr for those seeking those few extra cycles, perform the operation in place:\n\n``` javascript\nvar xorInplace = require(\"buffer-xor/inplace\")\nvar a = new Buffer('00ff0f', 'hex')\nvar b = new Buffer('f0f0', 'hex')\n\nconsole.log(xorInplace(a, b))\n// => \n// NOTE: xorInplace will return the shorter slice of its parameters\n\n// See that a has been mutated\nconsole.log(a)\n// => \n```\n\n\n## License [MIT](LICENSE)\n\n", + "readmeFilename": "README.md", + "_id": "buffer-xor@1.0.3", + "_shasum": "26e61ed1422fb70dd42e6e36729ed51d855fe8d9", + "_resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "_from": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json new file mode 100644 index 0000000..6f3431e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/fixtures.json @@ -0,0 +1,23 @@ +[ + { + "a": "000f", + "b": "f0ff", + "expected": "f0f0" + }, + { + "a": "000f0f", + "b": "f0ff", + "mutated": "f0f00f", + "expected": "f0f0" + }, + { + "a": "000f", + "b": "f0ffff", + "expected": "f0f0" + }, + { + "a": "000000", + "b": "000000", + "expected": "000000" + } +] diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js new file mode 100644 index 0000000..06eacab --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/buffer-xor/test/index.js @@ -0,0 +1,38 @@ +/* global describe, it */ + +var assert = require('assert') +var xor = require('../') +var xorInplace = require('../inplace') +var fixtures = require('./fixtures') + +describe('xor', function () { + fixtures.forEach(function (f) { + it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () { + var a = new Buffer(f.a, 'hex') + var b = new Buffer(f.b, 'hex') + var actual = xor(a, b) + + assert.equal(actual.toString('hex'), f.expected) + + // a/b unchanged + assert.equal(a.toString('hex'), f.a) + assert.equal(b.toString('hex'), f.b) + }) + }) +}) + +describe('xor/inplace', function () { + fixtures.forEach(function (f) { + it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () { + var a = new Buffer(f.a, 'hex') + var b = new Buffer(f.b, 'hex') + var actual = xorInplace(a, b) + + assert.equal(actual.toString('hex'), f.expected) + + // a mutated, b unchanged + assert.equal(a.toString('hex'), f.mutated || f.expected) + assert.equal(b.toString('hex'), f.b) + }) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc new file mode 100644 index 0000000..a755cdb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": ["standard"] +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml new file mode 100644 index 0000000..eb83acd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/index.js new file mode 100644 index 0000000..34fcae2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/index.js @@ -0,0 +1,90 @@ +var Transform = require('stream').Transform +var inherits = require('inherits') +var StringDecoder = require('string_decoder').StringDecoder +module.exports = CipherBase +inherits(CipherBase, Transform) +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + this._decoder = null + this._encoding = null +} +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = new Buffer(data, inputEnc) + } + var outData = this._update(data) + if (this.hashMode) { + return this + } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} + +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this._final()) + } catch (e) { + err = e + } finally { + done(err) + } +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this._final() || new Buffer('') + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, final) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + if (this._encoding !== enc) { + throw new Error('can\'t switch encodings') + } + var out = this._decoder.write(value) + if (final) { + out += this._decoder.end() + } + return out +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/package.json new file mode 100644 index 0000000..1e71e16 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/package.json @@ -0,0 +1,39 @@ +{ + "name": "cipher-base", + "version": "1.0.2", + "description": "abstract base class for crypto-streams", + "main": "index.js", + "scripts": { + "test": "node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/cipher-base.git" + }, + "keywords": [ + "cipher", + "stream" + ], + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/cipher-base/issues" + }, + "homepage": "https://github.com/crypto-browserify/cipher-base#readme", + "dependencies": { + "inherits": "^2.0.1" + }, + "devDependencies": { + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "cipher-base\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base)\n\nAbstract base class to inherit from if you want to create streams implementing\nthe same api as node crypto streams.\n\nRequires you to implement 2 methods `_final` and `_update`. `_update` takes a\nbuffer and should return a buffer, `_final` takes no arguments and should return\na buffer.\n\n\nThe constructor takes one argument and that is a string which if present switches\nit into hash mode, i.e. the object you get from crypto.createHash or\ncrypto.createSign, this switches the name of the final method to be the string\nyou passed instead of `final` and returns `this` from update.\n", + "readmeFilename": "readme.md", + "_id": "cipher-base@1.0.2", + "_shasum": "54ac1d1ebdf6a1bcd3559e6f369d72697f2cab8f", + "_resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz", + "_from": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/readme.md new file mode 100644 index 0000000..db9a781 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/readme.md @@ -0,0 +1,17 @@ +cipher-base +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) + +Abstract base class to inherit from if you want to create streams implementing +the same api as node crypto streams. + +Requires you to implement 2 methods `_final` and `_update`. `_update` takes a +buffer and should return a buffer, `_final` takes no arguments and should return +a buffer. + + +The constructor takes one argument and that is a string which if present switches +it into hash mode, i.e. the object you get from crypto.createHash or +crypto.createSign, this switches the name of the final method to be the string +you passed instead of `final` and returns `this` from update. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/test.js new file mode 100644 index 0000000..57d144a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/node_modules/cipher-base/test.js @@ -0,0 +1,108 @@ +var test = require('tape') +var CipherBase = require('./') +var inherits = require('inherits') + +test('basic version', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + return input + } + Cipher.prototype._final = function () { + // noop + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8', 'base64') + cipher.final('base64') + var string = (new Buffer(update, 'base64')).toString() + t.equals(utf8, string) + t.end() +}) +test('hash mode', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + var utf8 = 'abc123abcd' + var update = cipher.update(utf8, 'utf8').finalName('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('hash mode as stream', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this, 'finalName') + this._cache = [] + } + Cipher.prototype._update = function (input) { + t.ok(Buffer.isBuffer(input)) + this._cache.push(input) + } + Cipher.prototype._final = function () { + return Buffer.concat(this._cache) + } + var cipher = new Cipher() + cipher.on('error', function (e) { + t.notOk(e) + }) + var utf8 = 'abc123abcd' + cipher.end(utf8, 'utf8') + var update = cipher.read().toString('base64') + var string = (new Buffer(update, 'base64')).toString() + + t.equals(utf8, string) + t.end() +}) +test('encodings', function (t) { + inherits(Cipher, CipherBase) + function Cipher () { + CipherBase.call(this) + } + Cipher.prototype._update = function (input) { + return input + } + Cipher.prototype._final = function () { + // noop + } + t.test('mix and match encoding', function (t) { + t.plan(2) + + var cipher = new Cipher() + cipher.update('foo', 'utf8', 'utf8') + t.throws(function () { + cipher.update('foo', 'utf8', 'base64') + }) + cipher = new Cipher() + cipher.update('foo', 'utf8', 'base64') + t.doesNotThrow(function () { + cipher.update('foo', 'utf8') + cipher.final('base64') + }) + }) + t.test('handle long uft8 plaintexts', function (t) { + t.plan(1) + var txt = 'ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん' + + var cipher = new Cipher() + var decipher = new Cipher() + var enc = decipher.update(cipher.update(txt, 'utf8', 'base64'), 'base64', 'utf8') + enc += decipher.update(cipher.final('base64'), 'base64', 'utf8') + enc += decipher.final('utf8') + + t.equals(txt, enc) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/package.json new file mode 100644 index 0000000..5e83424 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/package.json @@ -0,0 +1,46 @@ +{ + "name": "browserify-aes", + "version": "1.0.6", + "description": "aes, for browserify", + "browser": "browser.js", + "main": "index.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "standard && node test/index.js|tspec" + }, + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/browserify-aes.git" + }, + "keywords": [ + "aes", + "crypto", + "browserify" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/browserify-aes/issues" + }, + "homepage": "https://github.com/crypto-browserify/browserify-aes", + "dependencies": { + "buffer-xor": "^1.0.2", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "inherits": "^2.0.1" + }, + "devDependencies": { + "standard": "^3.7.3", + "tap-spec": "^1.0.0", + "tape": "^3.0.0" + }, + "readme": "browserify-aes\n====\n\n[![Build Status](https://travis-ci.org/crypto-browserify/browserify-aes.svg)](https://travis-ci.org/crypto-browserify/browserify-aes)\n\nNode style aes for use in the browser. Implements:\n\n - createCipher\n - createCipheriv\n - createDecipher\n - createDecipheriv\n - getCiphers\n\nIn node.js, the `crypto` implementation is used, in browsers it falls back to a pure JavaScript implementation.\n\nMuch of this library has been taken from the aes implementation in [triplesec](https://github.com/keybase/triplesec), a partial derivation of [crypto-js](https://code.google.com/p/crypto-js/).\n\n`EVP_BytesToKey` is a straight up port of the same function from OpenSSL as there is literally no documenation on it beyond it using 'undocumented extensions' for longer keys.\n", + "readmeFilename": "readme.md", + "_id": "browserify-aes@1.0.6", + "_shasum": "5e7725dbdef1fd5930d4ebab48567ce451c48a0a", + "_resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz", + "_from": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/populateFixtures.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/populateFixtures.js new file mode 100644 index 0000000..ac31eb3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/populateFixtures.js @@ -0,0 +1,25 @@ +var modes = require('./modes') +var fixtures = require('./test/fixtures.json') +var crypto = require('crypto') +var types = ['aes-128-cfb1', 'aes-192-cfb1', 'aes-256-cfb1'] +var ebtk = require('./EVP_BytesToKey') +var fs = require('fs') + +fixtures.forEach(function (fixture) { + types.forEach(function (cipher) { + var suite = crypto.createCipher(cipher, new Buffer(fixture.password)) + var buf = new Buffer('') + buf = Buffer.concat([buf, suite.update(new Buffer(fixture.text))]) + buf = Buffer.concat([buf, suite.final()]) + fixture.results.ciphers[cipher] = buf.toString('hex') + if (modes[cipher].mode === 'ECB') { + return + } + var suite2 = crypto.createCipheriv(cipher, ebtk(crypto, fixture.password, modes[cipher].key).key, new Buffer(fixture.iv, 'hex')) + var buf2 = new Buffer('') + buf2 = Buffer.concat([buf2, suite2.update(new Buffer(fixture.text))]) + buf2 = Buffer.concat([buf2, suite2.final()]) + fixture.results.cipherivs[cipher] = buf2.toString('hex') + }) +}) +fs.writeFileSync('./test/fixturesNew.json', JSON.stringify(fixtures, false, 4)) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/readme.md new file mode 100644 index 0000000..1d7b085 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/readme.md @@ -0,0 +1,18 @@ +browserify-aes +==== + +[![Build Status](https://travis-ci.org/crypto-browserify/browserify-aes.svg)](https://travis-ci.org/crypto-browserify/browserify-aes) + +Node style aes for use in the browser. Implements: + + - createCipher + - createCipheriv + - createDecipher + - createDecipheriv + - getCiphers + +In node.js, the `crypto` implementation is used, in browsers it falls back to a pure JavaScript implementation. + +Much of this library has been taken from the aes implementation in [triplesec](https://github.com/keybase/triplesec), a partial derivation of [crypto-js](https://code.google.com/p/crypto-js/). + +`EVP_BytesToKey` is a straight up port of the same function from OpenSSL as there is literally no documenation on it beyond it using 'undocumented extensions' for longer keys. diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/streamCipher.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/streamCipher.js new file mode 100644 index 0000000..a55c762 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/browserify-aes/streamCipher.js @@ -0,0 +1,25 @@ +var aes = require('./aes') +var Transform = require('cipher-base') +var inherits = require('inherits') + +inherits(StreamCipher, Transform) +module.exports = StreamCipher +function StreamCipher (mode, key, iv, decrypt) { + if (!(this instanceof StreamCipher)) { + return new StreamCipher(mode, key, iv) + } + Transform.call(this) + this._cipher = new aes.AES(key) + this._prev = new Buffer(iv.length) + this._cache = new Buffer('') + this._secCache = new Buffer('') + this._decrypt = decrypt + iv.copy(this._prev) + this._mode = mode +} +StreamCipher.prototype._update = function (chunk) { + return this._mode.encrypt(this, chunk, this._decrypt) +} +StreamCipher.prototype._final = function () { + this._cipher.scrub() +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/index.js new file mode 100644 index 0000000..25fbc9c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/index.js @@ -0,0 +1,68 @@ +var md5 = require('create-hash/md5') +module.exports = EVP_BytesToKey +function EVP_BytesToKey (password, salt, keyLen, ivLen) { + if (!Buffer.isBuffer(password)) { + password = new Buffer(password, 'binary') + } + if (salt && !Buffer.isBuffer(salt)) { + salt = new Buffer(salt, 'binary') + } + keyLen = keyLen / 8 + ivLen = ivLen || 0 + var ki = 0 + var ii = 0 + var key = new Buffer(keyLen) + var iv = new Buffer(ivLen) + var addmd = 0 + var md_buf + var i + var bufs = [] + while (true) { + if (addmd++ > 0) { + bufs.push(md_buf) + } + bufs.push(password) + if (salt) { + bufs.push(salt) + } + md_buf = md5(Buffer.concat(bufs)) + bufs = [] + i = 0 + if (keyLen > 0) { + while (true) { + if (keyLen === 0) { + break + } + if (i === md_buf.length) { + break + } + key[ki++] = md_buf[i] + keyLen-- + i++ + } + } + if (ivLen > 0 && i !== md_buf.length) { + while (true) { + if (ivLen === 0) { + break + } + if (i === md_buf.length) { + break + } + iv[ii++] = md_buf[i] + ivLen-- + i++ + } + } + if (keyLen === 0 && ivLen === 0) { + break + } + } + for (i = 0; i < md_buf.length; i++) { + md_buf[i] = 0 + } + return { + key: key, + iv: iv + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/package.json new file mode 100644 index 0000000..66f2e69 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/package.json @@ -0,0 +1,40 @@ +{ + "name": "evp_bytestokey", + "version": "1.0.0", + "description": "he super secure key derivation algorithm from openssl", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/EVP_BytesToKey.git" + }, + "keywords": [ + "crypto", + "openssl" + ], + "author": { + "name": "Calvin Metcalf", + "email": "calvin.metcalf@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/EVP_BytesToKey/issues" + }, + "homepage": "https://github.com/crypto-browserify/EVP_BytesToKey", + "dependencies": { + "create-hash": "^1.1.1" + }, + "devDependencies": { + "standard": "^5.3.1", + "tap-spec": "^4.1.0", + "tape": "^4.2.0" + }, + "readme": "EVP_BytesToKey\n===\n\nThe super secure [key derivation algorithm from openssl](https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3)) (spoiler alert not actually secure, only every use it for compatibility reasons).\n\nApi:\n===\n\n```js\nvar result = EVP_BytesToKey('password', 'salt', keyLen, ivLen);\nBuffer.isBuffer(result.password); // true\nBuffer.isBuffer(result.iv); // true\n```\n", + "readmeFilename": "readme.md", + "_id": "evp_bytestokey@1.0.0", + "_shasum": "497b66ad9fef65cd7c08a6180824ba1476b66e53", + "_resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz", + "_from": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/readme.md new file mode 100644 index 0000000..86234db --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/readme.md @@ -0,0 +1,13 @@ +EVP_BytesToKey +=== + +The super secure [key derivation algorithm from openssl](https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3)) (spoiler alert not actually secure, only every use it for compatibility reasons). + +Api: +=== + +```js +var result = EVP_BytesToKey('password', 'salt', keyLen, ivLen); +Buffer.isBuffer(result.password); // true +Buffer.isBuffer(result.iv); // true +``` diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/test.js new file mode 100644 index 0000000..a638fa0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/node_modules/evp_bytestokey/test.js @@ -0,0 +1,19 @@ +var test = require('tape') +var evp = require('./') +var crypto = require('crypto') + +function runTest (password) { + test('password: ' + password, function (t) { + t.plan(1) + var keys = evp(password, false, 256, 16) + var nodeCipher = crypto.createCipher('aes-256-ctr', password) + var ourCipher = crypto.createCipheriv('aes-256-ctr', keys.key, keys.iv) + var nodeOut = nodeCipher.update('foooooo') + var ourOut = ourCipher.update('foooooo') + t.equals(nodeOut.toString('hex'), ourOut.toString('hex')) + }) +} +runTest('password') +runTest('ふっかつ あきる すぶり はやい つける まゆげ たんさん みんぞく ねほりはほり せまい たいまつばな ひはん') +runTest('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞') +runTest('💩') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/package.json new file mode 100644 index 0000000..bc3c4e6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/package.json @@ -0,0 +1,38 @@ +{ + "name": "parse-asn1", + "version": "5.0.0", + "description": "[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/parse-asn1.png)](http://travis-ci.org/crypto-browserify/parse-asn1) [![NPM](http://img.shields.io/npm/v/parse-asn1.svg)](https://www.npmjs.org/package/parse-asn1)", + "main": "index.js", + "scripts": { + "unit": "node ./test", + "standard": "standard", + "test": "npm run standard && npm run unit" + }, + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/parse-asn1.git" + }, + "author": "", + "license": "ISC", + "dependencies": { + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3" + }, + "devDependencies": { + "tape": "^3.4.0", + "standard": "^5.0.0" + }, + "readme": "#parse-asn1\n\n[![TRAVIS](https://secure.travis-ci.org/crypto-browserify/parse-asn1.png)](http://travis-ci.org/crypto-browserify/parse-asn1)\n[![NPM](http://img.shields.io/npm/v/parse-asn1.svg)](https://www.npmjs.org/package/parse-asn1)\n\n[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n\nutility library for parsing asn1 files for use with browserify-sign.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/crypto-browserify/parse-asn1/issues" + }, + "homepage": "https://github.com/crypto-browserify/parse-asn1#readme", + "_id": "parse-asn1@5.0.0", + "_shasum": "35060f6d5015d37628c770f4e091a0b5a278bc23", + "_resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.0.0.tgz", + "_from": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/1024.priv new file mode 100644 index 0000000..7206216 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/1024.priv @@ -0,0 +1,16 @@ +-----BEGIN PRIVATE KEY----- +MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKulUTZ8B1qccZ8c +DXRGSY08gW8KvLlcxxxGC4gZHNT3CBUF8n5R4KE30aZyYZ/rtsQZu05juZJxaJ0q +mbe75dlQ5d+Xc9BMXeQg/MpTZw5TAN7OIdGYYpFBe+1PLZ6wEfjkYrMqMUcfq2Lq +hTLdAbvBJnuRcYZLqmBeOQ8FTrKrAgMBAAECgYEAnkHRbEPU3/WISSQrP36iyCb2 +S/SBZwKkzmvCrBxDWhPeDswp9c/2JY76rNWfLzy8iXgUG8WUzvHje61Qh3gmBcKe +bUaTGl4Vy8Ha1YBADo5RfRrdm0FE4tvgvu/TkqFqpBBZweu54285hk5zlG7n/D7Y +dnNXUpu5MlNb5x3gW0kCQQDUL//cwcXUxY/evaJP4jSe+ZwEQZo+zXRLiPUulBoV +aw28CVMuxdgwqAo1X1IKefPeUaf7RQu8gCKaRnpGuEuXAkEAzxZTfMmvmCUDIew4 +5Gk6bK265XQWdhcgiq254lpBGOYmDj9yCE7yA+zmASQwMsXTdQOi1hOCEyrXuSJ5 +c++EDQJAFh3WrnzoEPByuYXMmET8tSFRWMQ5vpgNqh3haHR5b4gUC2hxaiunCBNL +1RpVY9AoUiDywGcG/SPh93CnKB3niwJBAKP7AtsifZgVXtiizB4aMThTjVYaSZrz +D0Kg9DuHylpkDChmFu77TGrNUQgAVuYtfhb/bRblVa/F0hJ4eQHT3JUCQBVT68tb +OgRUk0aP9tC3021VN82X6+klowSQN8oBPX8+TfDWSUilp/+j24Hky+Z29Do7yR/R +qutnL92CvBlVLV4= +-----END PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/1024.pub new file mode 100644 index 0000000..2dba785 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/1024.pub @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrpVE2fAdanHGfHA10RkmNPIFv +Cry5XMccRguIGRzU9wgVBfJ+UeChN9GmcmGf67bEGbtOY7mScWidKpm3u+XZUOXf +l3PQTF3kIPzKU2cOUwDeziHRmGKRQXvtTy2esBH45GKzKjFHH6ti6oUy3QG7wSZ7 +kXGGS6pgXjkPBU6yqwIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.1024.priv new file mode 100644 index 0000000..1145b7d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.1024.priv @@ -0,0 +1,18 @@ +-----BEGIN DSA PARAMETERS----- +MIIBHgKBgQDdFg3WQmpOZxObxraIe4rrbUhrBw99fbnz99IvLj60sM/7Uk7eHYvp +UrPaJBIcjPy68BjV4ekDljuPpFoAorsLzyvVSHuNvN6I/bRGm1TCOjDFVe98Oz6k +XmI6pRfIF0TiIPXkel/sWIfBYa1lqdoW82h9FIjhbxVHrKGfvMEc9wIVAOzmJHec +s6yBm+nE3+OmpWFYj0ylAoGAYxO6mFSoIY7PDRyRzKJEnULSzYXd3FoMkPwDCd5I +ch/piIoAUIIQ542TL54GT9wuiCL+0D48qi9GWKasPZABfPQ008WOzmKzD8ncrUTd +a7pzvUvdmwldA4Aa5/5xSXwtpK+DDye7KPlu+oi1BF6uj4TgfeGr1uxouxC2WhBE +qH0= +-----END DSA PARAMETERS----- +-----BEGIN PRIVATE KEY----- +MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAOY0KsTt5EpJ4LtlD3xRS5mDiGE1 +CMNp0S9X0sK8kP8Aps8iYwMLbZYglk18GCNnCk4SjbAnZHSB3kaIv6AKQc2J8W2Y +V5se3VhpKOFst7bqRtkGsl8uJtGlKTiXNclkv2jsKOrsBokSD1USGCECTNeMt3Og +ziRcZ1dS+djSOZ2nAhUAzB96SpxlAak+K/QLVJ+lDe5DcY0CgYEAtxX1/Hckvhlh +HQyKZWLQsDfZBILbhc+OLDpOyT6cJS/sJzfFIYZgK5M3rOS4OmzdYfJccQAuGq+T +VJQ3VcYOdbrIANJV8CDrn4jkkejTzJI6fCwAkPWOyxw8kbV1Hsoy6WLfSCHKpBUc +rogAqRGESqBVTawjyF/ECX667y/P49MEFgIUSeRVRgAXsLmeWR/V4Rh9Hex+9+s= +-----END PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.1024.pub new file mode 100644 index 0000000..80a731e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.1024.pub @@ -0,0 +1,12 @@ +-----BEGIN PUBLIC KEY----- +MIIBtzCCASwGByqGSM44BAEwggEfAoGBAOY0KsTt5EpJ4LtlD3xRS5mDiGE1CMNp +0S9X0sK8kP8Aps8iYwMLbZYglk18GCNnCk4SjbAnZHSB3kaIv6AKQc2J8W2YV5se +3VhpKOFst7bqRtkGsl8uJtGlKTiXNclkv2jsKOrsBokSD1USGCECTNeMt3OgziRc +Z1dS+djSOZ2nAhUAzB96SpxlAak+K/QLVJ+lDe5DcY0CgYEAtxX1/HckvhlhHQyK +ZWLQsDfZBILbhc+OLDpOyT6cJS/sJzfFIYZgK5M3rOS4OmzdYfJccQAuGq+TVJQ3 +VcYOdbrIANJV8CDrn4jkkejTzJI6fCwAkPWOyxw8kbV1Hsoy6WLfSCHKpBUcrogA +qRGESqBVTawjyF/ECX667y/P49MDgYQAAoGAXYmxO4+52C1gBzh7GgTwNLJl7bLn +gOhKTFlKhT36VjMjeFfdXmBVBVbfUottKZby/gVX1IXT38PStB/dswbF45bGDdoS +zMFjYmHTtLtrU/4hReVtvb5MYmrPDFX58SwcSRRO/cH6WJPvfu4Aq0cJZA9Kb0B9 +5Wo18JxAqvPtTB8= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.2048.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.2048.priv new file mode 100644 index 0000000..2a77c2e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.2048.priv @@ -0,0 +1,20 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIDVQIBAAKCAQEA0jDs9lLWX//NXYE1kNKw4UiDVMHHEtTF1OzJvBJvUh3/xMlU +ic8mUpIMU5mt7BTjcijyLLl/TeNBcI/xDvWH3PAfCjP1CmNzOMHwU6wKA4Q20m5v +zjauVycd7loRm5h+1XyD2JL1KmQTzhIIRAmRTeXMnr8LAHidYfUKmzCOCCrnctlE +EOh1S6e7BFxQBRrlUxZF0LTjcAz31rrjIH6wKkYR4mnpGuI2vVJ+qHGmEhvq1hAb +DvP0GN0iofxHlIVqOlfXYCZO388ZabfcBOQG57tTofm8aS4pnXCgbok9wEYPgbU5 +n6fEvDGOOObQyY109hZZaDJmfygr5mmD0TIXrQIhAMVBhV4liqAN2MrT/+ZUH6hY ++DhTazzSNLIZKQ5gfd+1AoIBADqHGUVQa9pbwyjbzooeWdijUM9W5P7UUj1OjrA0 +HIkcx37qHiYOVFqHpbjDs3tbgRBxBX5zBpwuhywC/6OetDiqzDy7zZCV/YMn06d2 +ncW2Ctjp3KPl7of39+HgXXePgTdKcfkjH9upJQTko88rA4NWwZbHYeA3Lv7DcA11 +XY3+TQHcxMtxf/E6aePjANJBsJsQjYLy3WyUiS87jkgi0Bigjg/cD3Nel4LToCTR +JvQ4m3w3T4W0xL1+8nPjRZ2q0GgmxZzPfwALrwiSYMgGZC/ov43wqOs6WXs0NnpJ +moU4oxutC/uDvTZmJvRj77FINjK0ZA20jmNvWmTIeEm1Xn4CggEABeRpOymQS5IS +X+u9ya7C+P3MPIRGm4dcWPWgPpD1QcclNYLGnhRp7JazNsbbPMjnx1qtF+2qjfy9 +JDeWTAR8qfCNVmQHPAhJsJtV0C/V4PUii71FRNPVC3EAYbcBk8deMGoUg99cxSac +6MCxIIOxuUKWpw8XPlMVpuXc8+lIMTYCPeLGinmT4DQ573t0MS6U3Ck/987xjkH9 +sos7zcYn3vnjywDCxXMidC0eUK1rxAAuY7PL4vQiKwXq8kFtWiKAnns/Zm5LTjiZ +NrwlhNlU2wQVvyIcKaGfSRPheb69IbP+9qp5b7Xe7DNWdo48S0jl2KAFeZ91BnhM +TH6WPtMpjQIgOaTTn6xYK0kZvvH3lZXrzkjp4aNlNY65R0JAKKNsx3s= +-----END DSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.2048.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.2048.pub new file mode 100644 index 0000000..9f6cac1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/dsa.2048.pub @@ -0,0 +1,20 @@ +-----BEGIN PUBLIC KEY----- +MIIDRjCCAjkGByqGSM44BAEwggIsAoIBAQDSMOz2UtZf/81dgTWQ0rDhSINUwccS +1MXU7Mm8Em9SHf/EyVSJzyZSkgxTma3sFONyKPIsuX9N40Fwj/EO9Yfc8B8KM/UK +Y3M4wfBTrAoDhDbSbm/ONq5XJx3uWhGbmH7VfIPYkvUqZBPOEghECZFN5cyevwsA +eJ1h9QqbMI4IKudy2UQQ6HVLp7sEXFAFGuVTFkXQtONwDPfWuuMgfrAqRhHiaeka +4ja9Un6ocaYSG+rWEBsO8/QY3SKh/EeUhWo6V9dgJk7fzxlpt9wE5Abnu1Oh+bxp +LimdcKBuiT3ARg+BtTmfp8S8MY445tDJjXT2FlloMmZ/KCvmaYPRMhetAiEAxUGF +XiWKoA3YytP/5lQfqFj4OFNrPNI0shkpDmB937UCggEAOocZRVBr2lvDKNvOih5Z +2KNQz1bk/tRSPU6OsDQciRzHfuoeJg5UWoeluMOze1uBEHEFfnMGnC6HLAL/o560 +OKrMPLvNkJX9gyfTp3adxbYK2Onco+Xuh/f34eBdd4+BN0px+SMf26klBOSjzysD +g1bBlsdh4Dcu/sNwDXVdjf5NAdzEy3F/8Tpp4+MA0kGwmxCNgvLdbJSJLzuOSCLQ +GKCOD9wPc16XgtOgJNEm9DibfDdPhbTEvX7yc+NFnarQaCbFnM9/AAuvCJJgyAZk +L+i/jfCo6zpZezQ2ekmahTijG60L+4O9NmYm9GPvsUg2MrRkDbSOY29aZMh4SbVe +fgOCAQUAAoIBAAXkaTspkEuSEl/rvcmuwvj9zDyERpuHXFj1oD6Q9UHHJTWCxp4U +aeyWszbG2zzI58darRftqo38vSQ3lkwEfKnwjVZkBzwISbCbVdAv1eD1Iou9RUTT +1QtxAGG3AZPHXjBqFIPfXMUmnOjAsSCDsblClqcPFz5TFabl3PPpSDE2Aj3ixop5 +k+A0Oe97dDEulNwpP/fO8Y5B/bKLO83GJ97548sAwsVzInQtHlCta8QALmOzy+L0 +IisF6vJBbVoigJ57P2ZuS044mTa8JYTZVNsEFb8iHCmhn0kT4Xm+vSGz/vaqeW+1 +3uwzVnaOPEtI5digBXmfdQZ4TEx+lj7TKY0= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.pass.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.pass.priv new file mode 100644 index 0000000..bf1836d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.pass.priv @@ -0,0 +1,7 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIHeMEkGCSqGSIb3DQEFDTA8MBsGCSqGSIb3DQEFDDAOBAi9LqZQx4JFXAICCAAw +HQYJYIZIAWUDBAECBBA+js1fG4Rv/yRN7oZvxbgyBIGQ/D4yj86M1x8lMsnAHQ/K +7/ryb/baDNHqN9LTZanEGBuyxgrTzt08SiL+h91yFGMoaly029K1VgEI8Lxu5Np/ +A+LK7ewh73ABzsbuxYdcXI+rKnrvLN9Tt6veDs4GlqTTsWwq5wF0C+6gaYRBXA74 +T1b6NykGh2UNL5U5pHZEYdOVLz+lRJL7gYqlweNHP/S3 +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.priv new file mode 100644 index 0000000..25fffbd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.priv @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHQCAQEEIDF6Xv8Sv//wGUWD+c780ppGrU0QdZWCAzxAQPQX8r/uoAcGBSuBBAAK +oUQDQgAEIZeowDylls4K/wfBjO18bYo7gGx8nYQRija4e/qEMikOHJai7geeUreU +r5Xky/Ax7s2dGtegsPNsPgGe5MpQvg== +-----END EC PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.pub new file mode 100644 index 0000000..2e39e5b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/ec.pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEIZeowDylls4K/wfBjO18bYo7gGx8nYQR +ija4e/qEMikOHJai7geeUreUr5Xky/Ax7s2dGtegsPNsPgGe5MpQvg== +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/index.js new file mode 100644 index 0000000..4d16030 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/index.js @@ -0,0 +1,92 @@ +var test = require('tape') +var fs = require('fs') +var parseKey = require('../') +var crypto = require('crypto') +var rsa1024 = { + private: fs.readFileSync(__dirname + '/rsa.1024.priv'), + public: fs.readFileSync(__dirname + '/rsa.1024.pub') +} +var rsa2028 = { + private: fs.readFileSync(__dirname + '/rsa.2028.priv'), + public: fs.readFileSync(__dirname + '/rsa.2028.pub') +} +var nonrsa1024 = { + private: fs.readFileSync(__dirname + '/1024.priv'), + public: fs.readFileSync(__dirname + '/1024.pub') +} +var pass1024 = { + private: { + passphrase: 'fooo', + key: fs.readFileSync(__dirname + '/pass.1024.priv') + }, + public: fs.readFileSync(__dirname + '/pass.1024.pub') +} +var ec = { + private: fs.readFileSync(__dirname + '/ec.priv'), + public: fs.readFileSync(__dirname + '/ec.pub') +} +var ecpass = { + private: { + key: fs.readFileSync(__dirname + '/ec.pass.priv'), + passphrase: 'bard' + }, + public: fs.readFileSync(__dirname + '/ec.pub') +} +var dsa = { + private: fs.readFileSync(__dirname + '/dsa.1024.priv'), + public: fs.readFileSync(__dirname + '/dsa.1024.pub') +} +var dsa2 = { + private: fs.readFileSync(__dirname + '/dsa.2048.priv'), + public: fs.readFileSync(__dirname + '/dsa.2048.pub') +} +var dsapass = { + private: { + key: fs.readFileSync(__dirname + '/pass.dsa.1024.priv'), + passphrase: 'password' + }, + public: fs.readFileSync(__dirname + '/pass.dsa.1024.pub') +} +var dsapass2 = { + private: { + key: fs.readFileSync(__dirname + '/pass2.dsa.1024.priv'), + passphrase: 'password' + }, + public: fs.readFileSync(__dirname + '/pass2.dsa.1024.pub') +} +var rsapass = { + private: { + key: fs.readFileSync(__dirname + '/pass.rsa.1024.priv'), + passphrase: 'password' + }, + public: fs.readFileSync(__dirname + '/pass.rsa.1024.pub') +} +var rsapass2 = { + private: { + key: fs.readFileSync(__dirname + '/pass.rsa.2028.priv'), + passphrase: 'password' + }, + public: fs.readFileSync(__dirname + '/pass.rsa.2028.pub') +} +var i = 0 +function testIt (keys) { + test('key ' + (++i), function (t) { + t.plan(2) + t.ok(parseKey(keys.public, crypto), 'public key') + t.ok(parseKey(keys.private, crypto), 'private key') + }) +} + +testIt(dsa) +testIt(dsa2) +testIt(rsa1024) +testIt(ec) +testIt(rsa2028) +testIt(nonrsa1024) +testIt(ecpass) +testIt(dsapass) +testIt(dsapass2) +testIt(rsapass) +testIt(rsapass2) +testIt(pass1024) +testIt(pass1024) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.1024.priv new file mode 100644 index 0000000..b9f3884 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.1024.priv @@ -0,0 +1,18 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIICzzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQIji3ZZ6JbsA4CAggA +MB0GCWCGSAFlAwQBFgQQC6MKblq8zyX90/KmgotsMQSCAoDghNf+yxPC/KRh7F3O +k0lMgtDkV+wCLDv7aBvUqy8Ry2zqFPIlfLb8XtSW943XEu6KUI13IZPEr8p9h1ve +Iye6L0g6uAgbFxBE2DwBBSI7mYr7lokr4v0k+inMKf4JeRdI9XWgwOILKTGf1vH7 +PhvBnqLhOg6BIOuF426qpiyYlmRda74d0Th4o6ZyhyMSzPI1XbWSg719Ew3N/tLe +OHdYl0eFrgNjq+xO4Ev+W7eNIh/XBMQtk9wo+mxeNdldRnX822HxTsL8fSSPs+9T +W5M/2EBTJMSsswSjZyFkq8ehtxovI2u0IBX1IiPulyUZLnSNPDV1eUVClK6rk+q1 +kVsfJhUr2qvIjNlQWlbEXQj4VwGtgl0++l8vdpj59MuN2J3Nx5TNMLjA6BYAa/tr +Bu928QoT7ET+SGx5XKCwKb5fwXmDlV5zZC4kZWTaF/d/Icvj5F+fDZuYFg1JOXNZ ++q2oA1qMYaHGX6lF3pbO84ebg1iwQTDM8iIqFeSMGUJTnk/3a7sqfaWQbEQwGb+X +fXnSTwkF+wO2rriPbFvWyzecWu67zDCP0ZWUgGb86sSJCM7xRGShESwCjOrb88F1 +5SZjyIqogrkc3IWiLH9gc5U8d86qoFjJnP6BfwYks1UIyXNGKfZTCqICpMphV+IS +b0N2jprjLTkWR6nxYGSH1bkKMs7x1M0FBLWWLAZqPn9X3pe6JwIBds04O6XjF0un +oxwDjcJdoxVs7PgRiM5d1Tubqu2zmpCCmXNiqi9B0+rV9/jHg9IA5gUfvYdCcEv+ +oAr90I+2+PuBFa9lgdbDV6DtZk4bSYluqamxVeLPg/vrewYfVfDv6jftfY1D0DEy +69H0 +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.1024.pub new file mode 100644 index 0000000..617e7fb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.1024.pub @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSK/7i5BV0x+gmX16Wrm7kRkCZ +y1QUt6wiM2g+SAZTYR0381VnSMX2cv7CpN3499lZj1rL5S7YTaZZwX3RvU5fz56/ +eDX6ciL/PZsbclN2KdkMWYgmcb9J1zUeoMQ3cjfFUCdQZ/ZvDWa+wY2Zg8os2Bow +AoufHtYHm3eOly/cWwIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.dsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.dsa.1024.priv new file mode 100644 index 0000000..aab5fc2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.dsa.1024.priv @@ -0,0 +1,11 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIBnzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQI1z4IJORFws4CAggA +MB0GCWCGSAFlAwQBAgQQq7f0CuKCTITfPS5Xax1H4wSCAVDFyIjYVXfBNe+BARqz +Tfo09y4vKkErOb7Sz4bQkAjRLjOXiUjM4eTNtivml8NqVrQTKAghN+ggxj416OD4 +oq6Ns7Ncbd4Xm5Ni8wrrWbJxVog6rAa/ioU0sfgRExYy/xE2Q9KkW+VE7SUwanwY +e81Od9qNM5KhZGM1yUSKa0JA6Xqb8dAqBo9rVt8DceumB9OP83xV3fLEimSZfR6p +slA1P/dTvKxwhpguQe4Z3OkzTzGCxyboqeRW1woNHKbxjzzSHcaki9SHQm3xpUW8 +hRAJd6OtDnLbkE9MnC+UcI3mjru1xfnR5MU7qG7e9nvOhEDVaDkiK3DbrSf0B0Bi +p1hyX1XsSXDewSEd/mlfMLdD8WecgUtl9ea7JzxY3/6R78yB951I5TmY45mp/v+N +tbxEv29B65UKf0ac7gVw4LNy8JF2ef/L/meEmBoIAE71f+8= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.dsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.dsa.1024.pub new file mode 100644 index 0000000..80a731e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.dsa.1024.pub @@ -0,0 +1,12 @@ +-----BEGIN PUBLIC KEY----- +MIIBtzCCASwGByqGSM44BAEwggEfAoGBAOY0KsTt5EpJ4LtlD3xRS5mDiGE1CMNp +0S9X0sK8kP8Aps8iYwMLbZYglk18GCNnCk4SjbAnZHSB3kaIv6AKQc2J8W2YV5se +3VhpKOFst7bqRtkGsl8uJtGlKTiXNclkv2jsKOrsBokSD1USGCECTNeMt3OgziRc +Z1dS+djSOZ2nAhUAzB96SpxlAak+K/QLVJ+lDe5DcY0CgYEAtxX1/HckvhlhHQyK +ZWLQsDfZBILbhc+OLDpOyT6cJS/sJzfFIYZgK5M3rOS4OmzdYfJccQAuGq+TVJQ3 +VcYOdbrIANJV8CDrn4jkkejTzJI6fCwAkPWOyxw8kbV1Hsoy6WLfSCHKpBUcrogA +qRGESqBVTawjyF/ECX667y/P49MDgYQAAoGAXYmxO4+52C1gBzh7GgTwNLJl7bLn +gOhKTFlKhT36VjMjeFfdXmBVBVbfUottKZby/gVX1IXT38PStB/dswbF45bGDdoS +zMFjYmHTtLtrU/4hReVtvb5MYmrPDFX58SwcSRRO/cH6WJPvfu4Aq0cJZA9Kb0B9 +5Wo18JxAqvPtTB8= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.1024.priv new file mode 100644 index 0000000..b67bd80 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.1024.priv @@ -0,0 +1,18 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-192-CBC,04D2D7882E0C474E07E542FE997D2A49 + +vfB5Gtm34n3SeI6JELjWiGw6O+j+tGR6Wbi3SNeAZkfSA8PTjei6PVHr+dGK5zMd +nTckd0EpxItqxEdtLK6GtBIa9KRd3cEbayHmyyybH2FC4STXJCUFBe2eb7ZKmnCl +RB5FcmAqExif+QOJwHnZw6DTzq+oGSwi9cSoy2qE62FgXkj8uKAYcBLONmsP1YQA +4zIub4bnEbIghL/swEB/HVS86FyMCsMXrHEOnSuUUBf/UfZFNypI6kVUNXlItnN1 +14eeRsBD37VkL7dAQPMx+Dwm7DbU07QWrVvzgmWlu3KqR0tRNA9e4a5f14XOYxgS +HZ+XVZK8iAd+76OnprlFtGDowDXGM0wUXPYq5j8WpKxNsVs2RV+S6U0gQLoSqNxt +We7UPWZufzEdjTUO8q9KhdGqFmJ53XIYClZf0bp148b+Bk3P+dN5TbmKQEfulScn +rTLTRo34fdTIAJr5BJh0OXGNs9rFlMJ9Nz4FwVTEB1DMerXtt9ICdhud9BktRhvq +axgoz+XA3LrBrlPPcrSCZyIYjZFydGSkzg439OyDEZ6+uRmc0qhWA4j6AgXx6gGR +NvvypoFVKvXqEq/2F+SVyyMGrm4xPmsr/HUBeE9SmuTzNzDfVAM/xerqIoR2szR0 +O0hwtOj4fk7//cd1CjFzd0JiF/SqMkHxkdbmIC9qlhshkWlQbvvhbefodYPuGxmj +L1TaPgX36OcrQSodzyWBN5tSmmX1Nmftcz7iwc4AKrqkdnM3sPS3SczsAjMWrjRr +7iYhdPQSZtxVCTjACU3h7scNAg9AU6l4YZrowR//J6U= +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.1024.pub new file mode 100644 index 0000000..3506c33 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.1024.pub @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGcMA0GCSqGSIb3DQEBAQUAA4GKADCBhgJ/OwswbFo/uyC8ltGf/yA1A+gV5IGd +nAgPbUSI3GzbHCA+x+TLG/tLvbRw3r1smppY/jkkpiVW1ErSMuN0uixp5gb78Z9r +H1XpWb5WWgp3WaY/9EHMjMdOkQ/9LVZvRvl/M/Fi6owP+q+amJI1BEjECYfbhGL3 +rmlVdq4qXc40QwIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.2028.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.2028.priv new file mode 100644 index 0000000..99e8213 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.2028.priv @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-256-CBC,7A6A055AD675947A657041422F06D439 + +HQdjzAKUuqqKhZHmpzzY/monfqFhiHnZ5c24jtR9fM4aQJXf/e1fz6MEhyIz6XON +sb4CnXZstnxUuVWDkHEu6KWQ/dKALgiDUuT+UdMawVoVPGdgyWZp35pQPWi3fT2V +XZn58YkG8bO3Y403eZPyhadOefD1VtuFuK6/f90jjzx6ZDnwveXpYgFV7Jy1/pFd +cLLMf07C+hbk416nX6UVipWe4GH+ADFom5ZCfAaUotM7n8i149dULNF4YYi2wP31 +1YaDH5vf1CqiaieDY7xLzpEixwJz6ZEg3gLXaUvz2MpF8owiGI3eP0g7voWp3xt4 +TQx/qDURlaXiaRriWdWtpKyW1MFuJ5+KdNtR1/kXr2BLPB/ZLwyqtynUy8ZYpb4+ +WIRYpUGeb//ZHGhlCH7CRMdABsal4wTwnzi9fW4Ax96ecJ2SlwCuKxwS7iEq2y1/ +FAfGwsE+XufHhme5p6XjKfiHx+zJMIB2NMkrm+wm4PbMTrGVnw5/41/r6XxOB8fe +iKi12Jth4dusc1vYGYfzKop9uEM6CZ6+Chqzb+Zyh/xUiZVlCX/BYnxr7yXUm9aR +PHQgxkn2Act8FgQB3Kgs3jCiCRIJrlsnybeWzQ3YO9TjC4MxygmmwODDBpsOKnEi +kXXS54+cZFjcsva4uJVwhAywRPVUkLzmTkH0tGiwCHjeQNECm+TLahkkEIXrVTb9 +c9creNXMgE6jVVz+R43HXsGvTcgMcBLyFRQJe2nVaj/dQ5JbF4uqNnQzRjAbD34K +uTpFaJ/kmlgcmeScRLnwaoYwFlmhSC+bK0dfY1Jr6AQRA6IDP7nIjqWNDCHNBB8r +Qj1v2KWoVQe3xNHaXhkbJPbA2DKlUIqffkBVtMKtt9KuG3Rccf3bVYAW6oid73/D +z7DMAF5G/OpVR8VbGh1WxXuR7zEVDUwpwsp9ek5dqN8BnBz1ppdZNIKqzszneckU +s2l/6mZBmgV1Nfy/cQU6U5s3S1Xc75UDQVLms3CIOpFTRIpecNTdfa31fYy/svy0 +M2lWTbCva0dOyuvMUhTgBL4I7Qa2dUMPXHMZatV5ooHYq/BZJA1r84C5cM5r+umE +2LLv/BlUr7RaQHhaKGn4Qhpzo5yRDE9mEqDpLVkbg8SxMsdf/pEF5/VyUwA9t8RT +fKVsInRd386tDqJSDbSFqKTvLztr/5YCyzZzvC2YB1voko/caOGd2d/G51Ij+bXU +xEN8U4fHDBsHwPUGb31uZUhTXpL37KiOqZmXFoH2usmuvx882XvyGcV0F4tstMaR +KLKzl2PwqzAYGFexLkYKMz0TYIeN6h3b86ETazPPU49nkaEU23Dx21J2Rb3UlH+I +lDQF3wuH1QlYiTnlcVa/Zu4QQg0/iP8ALkZ06mvn9e9mOtnA8gsh4B2oLqc19VLU +bcpv40dV1H3W9Lcx9B8JYUp0c/Oyno1D7Yj3tjGcwMKECmUpHi4kksehVo0/P933 +xmFmC6eyWYVdO9upvY/vKSB7b1dMt85iWr3gnMsSfRYc6jsbSxdjOPST46UsIzjx +wa1DS6+Bv5tiaC4uC6X+0tCAZo+UOQMYUbTGRR/7g/c= +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.2028.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.2028.pub new file mode 100644 index 0000000..655cc3a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass.rsa.2028.pub @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBHjANBgkqhkiG9w0BAQEFAAOCAQsAMIIBBgKB/gy7mjaWgPeFdVYDZWRCA9BN +iv3pPb0es27+FKY0hszLaOw47ExCtAWpDsH48TXAfyHBYwBLguayfk4LGIupxb+C +GMbRo3xEp0CbfY1Jby26T9vGjRC1foHDDUJG84uaRbyHqaf4i6zt4gVR+xlAEIjk +aFAAK8cOoXAT1CVqGLLljUCchL8PjaHj/yriZ/S7rdwlI3LnABxwwmLrmR/v71Wt +pmO/aNG8N+1po+QwaghTkyQ59E/ZvAuOkFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQ +aEDRbBFBmBqTv5fFGfk2WsAfKf/RG0/VFd+ZeM5251TeTvXH695nlSGauVl9AgMB +AAE= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass2.dsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass2.dsa.1024.priv new file mode 100644 index 0000000..29e3673 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass2.dsa.1024.priv @@ -0,0 +1,15 @@ +-----BEGIN DSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-128-CBC,DC173C6DFD455EBE462A35D6AB9A603A + +FoC3sxbdUFJTaNtRpooMxaX2lcQRLUz8qcRhzDBn5a1kaMHp2JM3KlHK5aauybT4 +ilmlKJ9sSm8pFLAWPKbkczSgZ+X6p/51v4zaEJSebZ98p32kQk87XJQE7aYroxYV +UfM5PSOoKWilj+LZQQEXV10qDoYGrnbSdoNSxYW5V1a1aP+ua0EO7m9MUYkoLxi3 +SJ/s2h/5KM3TOz7d7DOZuSoNm+0n6YC4aqQnR3lmEtAXEYLQqLhH2Q3FTKTHwBQw +HgMBAzcXOS1YSw6Ekwh1eZamizrOEC4I6oZEHoUBqRfbsQ8tu77kDq2ovQSyn8Fp +SeE64m3GgZOYdfcDuNZ0ccmm3shBBfTfD9AwR+1thklKO3oaaLEHb6TmnkD79rEz +9WsiVxoN7vqqWdgoeyl7REOB6WLQp8kYS4FoRG0QB/ZS8Hs/Tf17QPnrQNiMkvP7 +sJSHmlaMKXjWXK0VoN94kfZKUXwkzLD1VXuXFCnUkznWU0tahYi06b8/SVXc6EG+ +0mzylckH7UnjOQfxSFAlZ+e/PiX80tcPakxYbk+f1Nv7L0NOyhrDv18KUbv9mEpV +Ysild1m7/QSF0u1qmjmGNQ== +-----END DSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass2.dsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass2.dsa.1024.pub new file mode 100644 index 0000000..80a731e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/pass2.dsa.1024.pub @@ -0,0 +1,12 @@ +-----BEGIN PUBLIC KEY----- +MIIBtzCCASwGByqGSM44BAEwggEfAoGBAOY0KsTt5EpJ4LtlD3xRS5mDiGE1CMNp +0S9X0sK8kP8Aps8iYwMLbZYglk18GCNnCk4SjbAnZHSB3kaIv6AKQc2J8W2YV5se +3VhpKOFst7bqRtkGsl8uJtGlKTiXNclkv2jsKOrsBokSD1USGCECTNeMt3OgziRc +Z1dS+djSOZ2nAhUAzB96SpxlAak+K/QLVJ+lDe5DcY0CgYEAtxX1/HckvhlhHQyK +ZWLQsDfZBILbhc+OLDpOyT6cJS/sJzfFIYZgK5M3rOS4OmzdYfJccQAuGq+TVJQ3 +VcYOdbrIANJV8CDrn4jkkejTzJI6fCwAkPWOyxw8kbV1Hsoy6WLfSCHKpBUcrogA +qRGESqBVTawjyF/ECX667y/P49MDgYQAAoGAXYmxO4+52C1gBzh7GgTwNLJl7bLn +gOhKTFlKhT36VjMjeFfdXmBVBVbfUottKZby/gVX1IXT38PStB/dswbF45bGDdoS +zMFjYmHTtLtrU/4hReVtvb5MYmrPDFX58SwcSRRO/cH6WJPvfu4Aq0cJZA9Kb0B9 +5Wo18JxAqvPtTB8= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.1024.priv new file mode 100644 index 0000000..d3b5fda --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.1024.priv @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICVAIBAAJ/OwswbFo/uyC8ltGf/yA1A+gV5IGdnAgPbUSI3GzbHCA+x+TLG/tL +vbRw3r1smppY/jkkpiVW1ErSMuN0uixp5gb78Z9rH1XpWb5WWgp3WaY/9EHMjMdO +kQ/9LVZvRvl/M/Fi6owP+q+amJI1BEjECYfbhGL3rmlVdq4qXc40QwIDAQABAn8I +VZ0BPoAOhyF33KFMHxy8r28fsVgxJUYgM3NqQgdv4fFawCYXjhJz9duU5YJGFJGJ +WUGeHlkyYFlpi4f3m7tY7JawmQUWB0MNSoKHI3cgDX4/tfBN8ni+cO0eSoR5czBY +EsAHBU47p1awNFAHwd+ZEuv9H4RmMn7p279rQTtpAkAH3Nqs2/vrRF2cZUN4fIXf +4xHsQBByUayGq8a3J0UGaSFWv68zTUKFherr9uZotNp7NJ4jBXiARw0q8docXUG1 +AkAHgmOKHoORtAmikqpmFEJZOtsXMaLCIm4EszPo5ciYoLMBcVit09AdiQlt7ZJL +DY02svU1b0agCZ97kDkmHDkXAkACa8M9JELuDs/P/vIGYDkMVatIFfW6bWF02eFG +taWwMqCcSEsWvbw0xqYt34jURpNbCjmCyQVwYfAw/+TLhP9dAkAFwRjdwjw37qpj +ddg1mNiu37b7swFxmkiMOXZRxaNNsfb56A14RpN3zob3QdGUybGodMIKTFbmU/lu +CjqAxafJAkAG2yf6RWbwFIWfMyt7WYCh0VaGBCcgy574AinVieEo3ZZyFfC63+xm +3uoaNy4iLoJv4GCjqUBz3ZfcVaO/DDWG +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.1024.pub new file mode 100644 index 0000000..7ba0636 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.1024.pub @@ -0,0 +1,5 @@ +-----BEGIN RSA PUBLIC KEY----- +MIGGAn87CzBsWj+7ILyW0Z//IDUD6BXkgZ2cCA9tRIjcbNscID7H5Msb+0u9tHDe +vWyamlj+OSSmJVbUStIy43S6LGnmBvvxn2sfVelZvlZaCndZpj/0QcyMx06RD/0t +Vm9G+X8z8WLqjA/6r5qYkjUESMQJh9uEYveuaVV2ripdzjRDAgMBAAE= +-----END RSA PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.2028.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.2028.priv new file mode 100644 index 0000000..10e651d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.2028.priv @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEjwIBAAKB/gy7mjaWgPeFdVYDZWRCA9BNiv3pPb0es27+FKY0hszLaOw47ExC +tAWpDsH48TXAfyHBYwBLguayfk4LGIupxb+CGMbRo3xEp0CbfY1Jby26T9vGjRC1 +foHDDUJG84uaRbyHqaf4i6zt4gVR+xlAEIjkaFAAK8cOoXAT1CVqGLLljUCchL8P +jaHj/yriZ/S7rdwlI3LnABxwwmLrmR/v71WtpmO/aNG8N+1po+QwaghTkyQ59E/Z +vAuOkFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQaEDRbBFBmBqTv5fFGfk2WsAfKf/R +G0/VFd+ZeM5251TeTvXH695nlSGauVl9AgMBAAECgf4LrWHY/l54ouThZWvvbrug +pfz6sJX2g9l7yXmWlEWsPECVo/7SUbpYFpt6OZy99zSg+IKbGqWKfdhoKrTwIVtC +L0YZ0NlmdnANSIz0roxQG7ZxkL5+vHSw/PmD9x4Uwf+Cz8hATCmNBv1qc60dkyuW +4CLqe72qaTiVWRoO1iagQghNcLoo6vSy65ExLaCDTPha7yu2vw4hFZpWiEjW4dxf +rFdLiix52BC86YlAlxME/rLg8IJVvilbyo9aWdXmxOaUTLRv6PkFD1/gVdw8V9Qr +SLN9FlK2kkjiX0dzoibvZw3tMnt3yydAx0X87+sMRVahC1bp3kVPz4Hy0EWX4QJ/ +PM31vGiuITk2NCd51DXt1Ltn2OP5FaJSmCaEjh0XkU4qouYyjXWt8Bu6BTCl2vua +Fg0Uji9C+IkPLmaUMbMIOwaTk8cWqLthSxsLe70J5OkGrgfKUM/w+BHH1Pt/Pjzj +C++l0kiFaOVDVaAV9GpLPLCBoK/PC9Rb/rxMMoCCNwJ/NZuedIny2w3LMii77h/T +zSvergNGhjY6Rnva8lLXJ6dlrkcPAyps3gWwxqj4NR0T+GM0bDUPVLb7M07XV7SX +v7VJGm52JbRGwM1ss+r8XTTNemeGk+WRxG7TgtsMqYGXLfB8Qxk/f5/Mcc00Tl8u +wXFNsfxJxmt6AbsTr3g36wJ/IhOnibz9Ad+nchlBnN3QeW3CKHqzaR18voqvtVm2 +kJfHK15prH/sSGmxmiEGgrCJTZxtDbaNCO7/VBjnKudUUIhCAwsLtuq0/zub9vAd +8G1scfIpv5qaSNzmKoX8bOwArvrS6wP7yKrcTsuWIlHD8rJVI7IEDnQoTp5G8fK1 +hwJ/MIh8M5v0r5dUYEv6oIJWGcle6AH1JmsP5WIafgq72Z2288pHcCFHwNY8Dg9J +76QswVLnUhPTlmm3EOOPGEtam2iAD5r0Afytlb4lbNoQsj2szeXONDXB+6oueajh +VNELUr8HcSP5lgzRZjJW6aFIzj9LDRmQnUAOjGSXVOQtEwJ/MCQZ7N/v4dIKeDRA +8d8UExZ3+gGHumziztGRJ0tQryZH2PakP5I7V+1l7qEUnJ2c3mF+e1v41Ep9LCvh +bzrPKw9dxh18g4b+7bMpsWPnsraKh6ipxc7aaOaZV0Dxgez4zcZu0P1olO0cN3KM +nxJ0Pds3R8bAhNCDdS2JZaRp5Q== +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.2028.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.2028.pub new file mode 100644 index 0000000..b36dca4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/rsa.2028.pub @@ -0,0 +1,8 @@ +-----BEGIN RSA PUBLIC KEY----- +MIIBBgKB/gy7mjaWgPeFdVYDZWRCA9BNiv3pPb0es27+FKY0hszLaOw47ExCtAWp +DsH48TXAfyHBYwBLguayfk4LGIupxb+CGMbRo3xEp0CbfY1Jby26T9vGjRC1foHD +DUJG84uaRbyHqaf4i6zt4gVR+xlAEIjkaFAAK8cOoXAT1CVqGLLljUCchL8PjaHj +/yriZ/S7rdwlI3LnABxwwmLrmR/v71WtpmO/aNG8N+1po+QwaghTkyQ59E/ZvAuO +kFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQaEDRbBFBmBqTv5fFGfk2WsAfKf/RG0/V +Fd+ZeM5251TeTvXH695nlSGauVl9AgMBAAE= +-----END RSA PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector.js new file mode 100644 index 0000000..4b8d8cf --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector.js @@ -0,0 +1,7 @@ +module.exports = { + p: new Buffer('86F5CA03DCFEB225063FF830A0C769B9DD9D6153AD91D7CE27F787C43278B447E6533B86B18BED6E8A48B784A14C252C5BE0DBF60B86D6385BD2F12FB763ED8873ABFD3F5BA2E0A8C0A59082EAC056935E529DAF7C610467899C77ADEDFC846C881870B7B19B2B58F9BE0521A17002E3BDD6B86685EE90B3D9A1B02B782B1779', 'hex'), + q: new Buffer('996F967F6C8E388D9E28D01E205FBA957A5698B1', 'hex'), + g: new Buffer('07B0F92546150B62514BB771E2A0C0CE387F03BDA6C56B505209FF25FD3C133D89BBCD97E904E09114D9A7DEFDEADFC9078EA544D2E401AEECC40BB9FBBF78FD87995A10A1C27CB7789B594BA7EFB5C4326A9FE59A070E136DB77175464ADCA417BE5DCE2F40D10A46A3A3943F26AB7FD9C0398FF8C76EE0A56826A8A88F1DBD', 'hex'), + x: new Buffer('411602CB19A6CCC34494D79D98EF1E7ED5AF25F7', 'hex'), + y: new Buffer('5DF5E01DED31D0297E274E1691C192FE5868FEF9E19A84776454B100CF16F65392195A38B90523E2542EE61871C0440CB87C322FC4B4D2EC5E1E7EC766E1BE8D4CE935437DC11C3C8FD426338933EBFE739CB3465F4D3668C5E473508253B1E682F65CBDC4FAE93C2EA212390E54905A86E2223170B44EAA7DA5DD9FFCFB7F3B', 'hex') +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector.priv new file mode 100644 index 0000000..178bd1e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector.priv @@ -0,0 +1,12 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIBugIBAAKBgQCG9coD3P6yJQY/+DCgx2m53Z1hU62R184n94fEMni0R+ZTO4ax +i+1uiki3hKFMJSxb4Nv2C4bWOFvS8S+3Y+2Ic6v9P1ui4KjApZCC6sBWk15Sna98 +YQRniZx3re38hGyIGHC3sZsrWPm+BSGhcALjvda4ZoXukLPZobAreCsXeQIVAJlv +ln9sjjiNnijQHiBfupV6VpixAoGAB7D5JUYVC2JRS7dx4qDAzjh/A72mxWtQUgn/ +Jf08Ez2Ju82X6QTgkRTZp9796t/JB46lRNLkAa7sxAu5+794/YeZWhChwny3eJtZ +S6fvtcQyap/lmgcOE223cXVGStykF75dzi9A0QpGo6OUPyarf9nAOY/4x27gpWgm +qKiPHb0CgYBd9eAd7THQKX4nThaRwZL+WGj++eGahHdkVLEAzxb2U5IZWji5BSPi +VC7mGHHARAy4fDIvxLTS7F4efsdm4b6NTOk1Q33BHDyP1CYziTPr/nOcs0ZfTTZo +xeRzUIJTseaC9ly9xPrpPC6iEjkOVJBahuIiMXC0Tqp9pd2f/Pt/OwIUQRYCyxmm +zMNElNedmO8eftWvJfc= +-----END DSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector2.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector2.priv new file mode 100644 index 0000000..ef53f61 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/node_modules/parse-asn1/test/vector2.priv @@ -0,0 +1,19 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIDVQIBAAKCAQEAnbb7WVG2a7b+HhQPHSzlUCN0Fh/WU43xZIIYZC8LXEjI96Qa +rfoYcyS4dnT6GCKwDx7PgTaUPXxVdXJk5aGkT/4BLpk24AwdPpMQsBx9F5gF0wWL +Kp9Ltvlxa/5hF8a1s8xNm+NBEErUqArWyU4AX0uZPhTwketRdDvzMFDDjeI1Vn4b +NMPWpcDOqhoPNoITw9GYQ9C0sJ3Ln8ctOcjeQfG/FNS7RWPKKDcWIcrTMktqLTkh +Rb6/rHSIBSNvXKL+krhxzY+cNtMpK1UJyoyqd6Kt/Hv9d92m9xElp0Vv6hU+QzJW +oiYcagbtNpN5fnmV+tWqu8++PtonQeN1QEriWwIhAPLDEZN0znbJNWmQtGU3Shfy +P57TUIm9lp9hxt3pmYwfAoIBAFx/9rBvjxQ/6CiEM0k+R2nE2Yis5b4loOJICWcH +FsYT17DO5pMvj6p8RNLLJFI9pT++T27DWViS0apYxDKKBsRqFWYufqpwOh3s+Luy +0F2+LrlWwUKjOGYdEEYcDRNUcghQV/NJQwn/pzxhH3izKtu1dAw2HJ81vpCZfbIB +Ti71qmF4L1Kr64vWQyxN0Je8VCOyhdr7YNw2ToFh9KKjWso6ELHE0gPMdqRwozr9 +y92SlZhZq9i1bhclJS146sZucbqa4/HdJIcZmHQ5PNTYMhhoAGVHYOHjTAnk0VUX +n57A3ERz+Za9zm7tHKvti28Rb3rZz1Bd8PmY40qydRSw/+cCggEAZnCYxlRCbHjX ++CAerGwgPvAw1DYFAywvH6k35SN9vZSfNKCiVk/hJtyLcVxRQYAs4JecgkZGPEDm +tr2qJRP6YRcocWwuT9U7yVuJ5plJ2WUS6HO5yPjf1JnMMSiCVhreyzH2WOk0wMGX +8sTZawXLrWc4Hnt2iJHk2jhD0k2UzftRJum4vyHoNY7g4KMO8T/WpmTA3ONzH3+0 +mkhFpP2CVGh5cqLTglmcm6xODteZgZMHiRMDJVgTSXZBC4nSwXHRI6w1/ZdyGVl6p9FcGppCjlkZT3XHIevLz65EaWpJmvp04EKZ8TICZgFjjLh6t5GQ1KCYY +xXajuxlYck4mWvq3wIgacdUjCHQ3+prmlHJ6tTifDPTs/GAMW5byrkskz8OTbw= +-----END DSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/package.json new file mode 100644 index 0000000..9806f56 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/package.json @@ -0,0 +1,40 @@ +{ + "name": "public-encrypt", + "version": "4.0.0", + "description": "browserify version of publicEncrypt & privateDecrypt", + "main": "index.js", + "browser": "browser.js", + "directories": { + "test": "test" + }, + "scripts": { + "test": "node test/index.js | tspec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/crypto-browserify/publicEncrypt.git" + }, + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/publicEncrypt/issues" + }, + "homepage": "https://github.com/crypto-browserify/publicEncrypt", + "dependencies": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1" + }, + "devDependencies": { + "tape": "^3.0.3", + "tap-spec": "^2.1.2" + }, + "readme": "publicEncrypt\n===\n\n[![Build Status](https://travis-ci.org/crypto-browserify/publicEncrypt.svg)](https://travis-ci.org/crypto-browserify/publicEncrypt)\n\npublicEncrypt/privateDecrypt for browserify", + "readmeFilename": "readme.md", + "_id": "public-encrypt@4.0.0", + "_shasum": "39f699f3a46560dd5ebacbca693caf7c65c18cc6", + "_resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.0.tgz", + "_from": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/privateDecrypt.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/privateDecrypt.js new file mode 100644 index 0000000..9047c0e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/privateDecrypt.js @@ -0,0 +1,108 @@ +var parseKeys = require('parse-asn1'); +var mgf = require('./mgf'); +var xor = require('./xor'); +var bn = require('bn.js'); +var crt = require('browserify-rsa'); +var createHash = require('create-hash'); +var withPublic = require('./withPublic'); +module.exports = function privateDecrypt(private_key, enc, reverse) { + var padding; + if (private_key.padding) { + padding = private_key.padding; + } else if (reverse) { + padding = 1; + } else { + padding = 4; + } + + var key = parseKeys(private_key); + var k = key.modulus.byteLength(); + if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) { + throw new Error('decryption error'); + } + var msg; + if (reverse) { + msg = withPublic(new bn(enc), key); + } else { + msg = crt(enc, key); + } + var zBuffer = new Buffer(k - msg.length); + zBuffer.fill(0); + msg = Buffer.concat([zBuffer, msg], k); + if (padding === 4) { + return oaep(key, msg); + } else if (padding === 1) { + return pkcs1(key, msg, reverse); + } else if (padding === 3) { + return msg; + } else { + throw new Error('unknown padding'); + } +}; + +function oaep(key, msg){ + var n = key.modulus; + var k = key.modulus.byteLength(); + var mLen = msg.length; + var iHash = createHash('sha1').update(new Buffer('')).digest(); + var hLen = iHash.length; + var hLen2 = 2 * hLen; + if (msg[0] !== 0) { + throw new Error('decryption error'); + } + var maskedSeed = msg.slice(1, hLen + 1); + var maskedDb = msg.slice(hLen + 1); + var seed = xor(maskedSeed, mgf(maskedDb, hLen)); + var db = xor(maskedDb, mgf(seed, k - hLen - 1)); + if (compare(iHash, db.slice(0, hLen))) { + throw new Error('decryption error'); + } + var i = hLen; + while (db[i] === 0) { + i++; + } + if (db[i++] !== 1) { + throw new Error('decryption error'); + } + return db.slice(i); +} + +function pkcs1(key, msg, reverse){ + var p1 = msg.slice(0, 2); + var i = 2; + var status = 0; + while (msg[i++] !== 0) { + if (i >= msg.length) { + status++; + break; + } + } + var ps = msg.slice(2, i - 1); + var p2 = msg.slice(i - 1, i); + + if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){ + status++; + } + if (ps.length < 8) { + status++; + } + if (status) { + throw new Error('decryption error'); + } + return msg.slice(i); +} +function compare(a, b){ + a = new Buffer(a); + b = new Buffer(b); + var dif = 0; + var len = a.length; + if (a.length !== b.length) { + dif++; + len = Math.min(a.length, b.length); + } + var i = -1; + while (++i < len) { + dif += (a[i] ^ b[i]); + } + return dif; +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/publicEncrypt.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/publicEncrypt.js new file mode 100644 index 0000000..f1ce404 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/publicEncrypt.js @@ -0,0 +1,95 @@ +var parseKeys = require('parse-asn1'); +var randomBytes = require('randombytes'); +var createHash = require('create-hash'); +var mgf = require('./mgf'); +var xor = require('./xor'); +var bn = require('bn.js'); +var withPublic = require('./withPublic'); +var crt = require('browserify-rsa'); + +var constants = { + RSA_PKCS1_OAEP_PADDING: 4, + RSA_PKCS1_PADDIN: 1, + RSA_NO_PADDING: 3 +}; + +module.exports = function publicEncrypt(public_key, msg, reverse) { + var padding; + if (public_key.padding) { + padding = public_key.padding; + } else if (reverse) { + padding = 1; + } else { + padding = 4; + } + var key = parseKeys(public_key); + var paddedMsg; + if (padding === 4) { + paddedMsg = oaep(key, msg); + } else if (padding === 1) { + paddedMsg = pkcs1(key, msg, reverse); + } else if (padding === 3) { + paddedMsg = new bn(msg); + if (paddedMsg.cmp(key.modulus) >= 0) { + throw new Error('data too long for modulus'); + } + } else { + throw new Error('unknown padding'); + } + if (reverse) { + return crt(paddedMsg, key); + } else { + return withPublic(paddedMsg, key); + } +}; + +function oaep(key, msg){ + var k = key.modulus.byteLength(); + var mLen = msg.length; + var iHash = createHash('sha1').update(new Buffer('')).digest(); + var hLen = iHash.length; + var hLen2 = 2 * hLen; + if (mLen > k - hLen2 - 2) { + throw new Error('message too long'); + } + var ps = new Buffer(k - mLen - hLen2 - 2); + ps.fill(0); + var dblen = k - hLen - 1; + var seed = randomBytes(hLen); + var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen)); + var maskedSeed = xor(seed, mgf(maskedDb, hLen)); + return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k)); +} +function pkcs1(key, msg, reverse){ + var mLen = msg.length; + var k = key.modulus.byteLength(); + if (mLen > k - 11) { + throw new Error('message too long'); + } + var ps; + if (reverse) { + ps = new Buffer(k - mLen - 3); + ps.fill(0xff); + } else { + ps = nonZero(k - mLen - 3); + } + return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k)); +} +function nonZero(len, crypto) { + var out = new Buffer(len); + var i = 0; + var cache = randomBytes(len*2); + var cur = 0; + var num; + while (i < len) { + if (cur === cache.length) { + cache = randomBytes(len*2); + cur = 0; + } + num = cache[cur++]; + if (num) { + out[i++] = num; + } + } + return out; +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/readme.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/readme.md new file mode 100644 index 0000000..47c6940 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/readme.md @@ -0,0 +1,6 @@ +publicEncrypt +=== + +[![Build Status](https://travis-ci.org/crypto-browserify/publicEncrypt.svg)](https://travis-ci.org/crypto-browserify/publicEncrypt) + +publicEncrypt/privateDecrypt for browserify \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/1024.priv new file mode 100644 index 0000000..7206216 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/1024.priv @@ -0,0 +1,16 @@ +-----BEGIN PRIVATE KEY----- +MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKulUTZ8B1qccZ8c +DXRGSY08gW8KvLlcxxxGC4gZHNT3CBUF8n5R4KE30aZyYZ/rtsQZu05juZJxaJ0q +mbe75dlQ5d+Xc9BMXeQg/MpTZw5TAN7OIdGYYpFBe+1PLZ6wEfjkYrMqMUcfq2Lq +hTLdAbvBJnuRcYZLqmBeOQ8FTrKrAgMBAAECgYEAnkHRbEPU3/WISSQrP36iyCb2 +S/SBZwKkzmvCrBxDWhPeDswp9c/2JY76rNWfLzy8iXgUG8WUzvHje61Qh3gmBcKe +bUaTGl4Vy8Ha1YBADo5RfRrdm0FE4tvgvu/TkqFqpBBZweu54285hk5zlG7n/D7Y +dnNXUpu5MlNb5x3gW0kCQQDUL//cwcXUxY/evaJP4jSe+ZwEQZo+zXRLiPUulBoV +aw28CVMuxdgwqAo1X1IKefPeUaf7RQu8gCKaRnpGuEuXAkEAzxZTfMmvmCUDIew4 +5Gk6bK265XQWdhcgiq254lpBGOYmDj9yCE7yA+zmASQwMsXTdQOi1hOCEyrXuSJ5 +c++EDQJAFh3WrnzoEPByuYXMmET8tSFRWMQ5vpgNqh3haHR5b4gUC2hxaiunCBNL +1RpVY9AoUiDywGcG/SPh93CnKB3niwJBAKP7AtsifZgVXtiizB4aMThTjVYaSZrz +D0Kg9DuHylpkDChmFu77TGrNUQgAVuYtfhb/bRblVa/F0hJ4eQHT3JUCQBVT68tb +OgRUk0aP9tC3021VN82X6+klowSQN8oBPX8+TfDWSUilp/+j24Hky+Z29Do7yR/R +qutnL92CvBlVLV4= +-----END PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/1024.pub new file mode 100644 index 0000000..2dba785 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/1024.pub @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrpVE2fAdanHGfHA10RkmNPIFv +Cry5XMccRguIGRzU9wgVBfJ+UeChN9GmcmGf67bEGbtOY7mScWidKpm3u+XZUOXf +l3PQTF3kIPzKU2cOUwDeziHRmGKRQXvtTy2esBH45GKzKjFHH6ti6oUy3QG7wSZ7 +kXGGS6pgXjkPBU6yqwIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.pass.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.pass.priv new file mode 100644 index 0000000..bf1836d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.pass.priv @@ -0,0 +1,7 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIHeMEkGCSqGSIb3DQEFDTA8MBsGCSqGSIb3DQEFDDAOBAi9LqZQx4JFXAICCAAw +HQYJYIZIAWUDBAECBBA+js1fG4Rv/yRN7oZvxbgyBIGQ/D4yj86M1x8lMsnAHQ/K +7/ryb/baDNHqN9LTZanEGBuyxgrTzt08SiL+h91yFGMoaly029K1VgEI8Lxu5Np/ +A+LK7ewh73ABzsbuxYdcXI+rKnrvLN9Tt6veDs4GlqTTsWwq5wF0C+6gaYRBXA74 +T1b6NykGh2UNL5U5pHZEYdOVLz+lRJL7gYqlweNHP/S3 +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.priv new file mode 100644 index 0000000..25fffbd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.priv @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHQCAQEEIDF6Xv8Sv//wGUWD+c780ppGrU0QdZWCAzxAQPQX8r/uoAcGBSuBBAAK +oUQDQgAEIZeowDylls4K/wfBjO18bYo7gGx8nYQRija4e/qEMikOHJai7geeUreU +r5Xky/Ax7s2dGtegsPNsPgGe5MpQvg== +-----END EC PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.pub new file mode 100644 index 0000000..2e39e5b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/ec.pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEIZeowDylls4K/wfBjO18bYo7gGx8nYQR +ija4e/qEMikOHJai7geeUreUr5Xky/Ax7s2dGtegsPNsPgGe5MpQvg== +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/index.js new file mode 100644 index 0000000..ea472b6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/index.js @@ -0,0 +1,117 @@ +var test = require('tape'); +var fs = require('fs'); +var constants = require('constants'); +var parseKeys = require('parse-asn1'); +require('./nodeTests'); +var priv1024 = fs.readFileSync(__dirname + '/rsa.1024.priv'); +var rsa1024 = { + private: fs.readFileSync(__dirname + '/rsa.1024.priv'), + public: fs.readFileSync(__dirname + '/rsa.1024.pub') +}; +var rsa1024priv = { + private: fs.readFileSync(__dirname + '/rsa.1024.priv'), + public: fs.readFileSync(__dirname + '/rsa.1024.priv') +}; +var rsa1024 = { + private: fs.readFileSync(__dirname + '/rsa.1024.priv'), + public: fs.readFileSync(__dirname + '/rsa.1024.pub') +}; +var rsa2028 = { + private: fs.readFileSync(__dirname + '/rsa.2028.priv'), + public: fs.readFileSync(__dirname + '/rsa.2028.pub') +}; +var nonrsa1024 = { + private: fs.readFileSync(__dirname + '/1024.priv'), + public: fs.readFileSync(__dirname + '/1024.pub') +}; +var nonrsa1024str = { + private: fs.readFileSync(__dirname + '/1024.priv').toString(), + public: fs.readFileSync(__dirname + '/1024.pub').toString() +}; +var pass1024 = { + private: { + passphrase: 'fooo', + key:fs.readFileSync(__dirname + '/pass.1024.priv') + }, + public: fs.readFileSync(__dirname + '/pass.1024.pub') +}; +var pass2028 = { + private: { + passphrase: 'password', + key:fs.readFileSync(__dirname + '/rsa.pass.priv') + }, + public: fs.readFileSync(__dirname + '/rsa.pass.pub') +}; + +var nodeCrypto = require('../'); +var myCrypto = require('../browser'); +function _testIt(keys, message, t) { + var pub = keys.public; + var priv = keys.private; + t.test(message.toString(), function (t) { + t.plan(8); + + var myEnc = myCrypto.publicEncrypt(pub, message); + var nodeEnc = nodeCrypto.publicEncrypt(pub, message); + t.equals(myCrypto.privateDecrypt(priv, myEnc).toString('hex'), message.toString('hex'), 'my decrypter my message'); + t.equals(myCrypto.privateDecrypt(priv, nodeEnc).toString('hex'), message.toString('hex'), 'my decrypter node\'s message'); + t.equals(nodeCrypto.privateDecrypt(priv, myEnc).toString('hex'), message.toString('hex'), 'node decrypter my message'); + t.equals(nodeCrypto.privateDecrypt(priv, nodeEnc).toString('hex'), message.toString('hex'), 'node decrypter node\'s message'); + myEnc = myCrypto.privateEncrypt(priv, message); + nodeEnc = nodeCrypto.privateEncrypt(priv, message); + t.equals(myCrypto.publicDecrypt(pub, myEnc).toString('hex'), message.toString('hex'), 'reverse methods my decrypter my message'); + t.equals(myCrypto.publicDecrypt(pub, nodeEnc).toString('hex'), message.toString('hex'), 'reverse methods my decrypter node\'s message'); + t.equals(nodeCrypto.publicDecrypt(pub, myEnc).toString('hex'), message.toString('hex'), 'reverse methods node decrypter my message'); + t.equals(nodeCrypto.publicDecrypt(pub, nodeEnc).toString('hex'), message.toString('hex'), 'reverse methods node decrypter node\'s message'); + + }); +} +function testIt(keys, message, t) { + _testIt(keys, message, t); + _testIt(paddingObject(keys, 1), Buffer.concat([message, new Buffer(' with RSA_PKCS1_PADDING')]), t); + var parsedKey = parseKeys(keys.public); + var k = parsedKey.modulus.byteLength(); + var zBuf = new Buffer(k); + zBuf.fill(0); + var msg = Buffer.concat([zBuf, message, new Buffer(' with no padding')]).slice(-k); + _testIt(paddingObject(keys, 3), msg, t); +} +function paddingObject(keys, padding) { + return { + public: addPadding(keys.public, padding), + private: addPadding(keys.private, padding) + }; +} +function addPadding(key, padding) { + if (typeof key === 'string' || Buffer.isBuffer(key)) { + return { + key: key, + padding: padding + }; + } + var out = { + key: key.key, + padding:padding + }; + if ('passphrase' in key) { + out.passphrase = key.passphrase; + } + return out; +} +function testRun(i) { + test('run ' + i, function (t) { + testIt(rsa1024priv, new Buffer('1024 2 private keys'), t); + testIt(rsa1024, new Buffer('1024 keys'), t); + testIt(rsa2028, new Buffer('2028 keys'), t); + testIt(nonrsa1024, new Buffer('1024 keys non-rsa key'), t); + testIt(pass1024, new Buffer('1024 keys and password'), t); + testIt(nonrsa1024str, new Buffer('1024 keys non-rsa key as a string'), t); + testIt(pass2028, new Buffer('2028 rsa key with variant passwords'), t); + }); +} + +var i = 0; +var num = 20; +while (++i <= 20) { + testRun(i); +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/nodeTests.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/nodeTests.js new file mode 100644 index 0000000..f168e93 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/nodeTests.js @@ -0,0 +1,51 @@ +var crypto = require('../browser'); +var test = require('tape'); +var fs = require('fs'); + +// Test RSA encryption/decryption +test('node tests', function (t) { + var certPem = fs.readFileSync(__dirname + '/test_cert.pem', 'ascii'); + var keyPem = fs.readFileSync(__dirname + '/test_key.pem', 'ascii'); + var rsaPubPem = fs.readFileSync(__dirname + '/test_rsa_pubkey.pem', + 'ascii'); + var rsaKeyPem = fs.readFileSync(__dirname + '/test_rsa_privkey.pem', + 'ascii'); + var rsaKeyPemEncrypted = fs.readFileSync( + __dirname + '/test_rsa_privkey_encrypted.pem', 'ascii'); + var input = 'I AM THE WALRUS'; + var bufferToEncrypt = new Buffer(input); + + var encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); + + var decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); + t.equal(input, decryptedBuffer.toString()); + + var decryptedBufferWithPassword = crypto.privateDecrypt({ + key: rsaKeyPemEncrypted, + passphrase: 'password' + }, encryptedBuffer); + t.equal(input, decryptedBufferWithPassword.toString()); + + // encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt); + + // decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); + // t.equal(input, decryptedBuffer.toString()); + + encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt); + + decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); + t.equal(input, decryptedBuffer.toString()); + + encryptedBuffer = crypto.privateEncrypt(keyPem, bufferToEncrypt); + + decryptedBuffer = crypto.publicDecrypt(keyPem, encryptedBuffer); + t.equal(input, decryptedBuffer.toString()); + + t.throws(function() { + crypto.privateDecrypt({ + key: rsaKeyPemEncrypted, + passphrase: 'wrong' + }, encryptedBuffer); + }); + t.end(); +}); \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/pass.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/pass.1024.priv new file mode 100644 index 0000000..b9f3884 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/pass.1024.priv @@ -0,0 +1,18 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIICzzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQIji3ZZ6JbsA4CAggA +MB0GCWCGSAFlAwQBFgQQC6MKblq8zyX90/KmgotsMQSCAoDghNf+yxPC/KRh7F3O +k0lMgtDkV+wCLDv7aBvUqy8Ry2zqFPIlfLb8XtSW943XEu6KUI13IZPEr8p9h1ve +Iye6L0g6uAgbFxBE2DwBBSI7mYr7lokr4v0k+inMKf4JeRdI9XWgwOILKTGf1vH7 +PhvBnqLhOg6BIOuF426qpiyYlmRda74d0Th4o6ZyhyMSzPI1XbWSg719Ew3N/tLe +OHdYl0eFrgNjq+xO4Ev+W7eNIh/XBMQtk9wo+mxeNdldRnX822HxTsL8fSSPs+9T +W5M/2EBTJMSsswSjZyFkq8ehtxovI2u0IBX1IiPulyUZLnSNPDV1eUVClK6rk+q1 +kVsfJhUr2qvIjNlQWlbEXQj4VwGtgl0++l8vdpj59MuN2J3Nx5TNMLjA6BYAa/tr +Bu928QoT7ET+SGx5XKCwKb5fwXmDlV5zZC4kZWTaF/d/Icvj5F+fDZuYFg1JOXNZ ++q2oA1qMYaHGX6lF3pbO84ebg1iwQTDM8iIqFeSMGUJTnk/3a7sqfaWQbEQwGb+X +fXnSTwkF+wO2rriPbFvWyzecWu67zDCP0ZWUgGb86sSJCM7xRGShESwCjOrb88F1 +5SZjyIqogrkc3IWiLH9gc5U8d86qoFjJnP6BfwYks1UIyXNGKfZTCqICpMphV+IS +b0N2jprjLTkWR6nxYGSH1bkKMs7x1M0FBLWWLAZqPn9X3pe6JwIBds04O6XjF0un +oxwDjcJdoxVs7PgRiM5d1Tubqu2zmpCCmXNiqi9B0+rV9/jHg9IA5gUfvYdCcEv+ +oAr90I+2+PuBFa9lgdbDV6DtZk4bSYluqamxVeLPg/vrewYfVfDv6jftfY1D0DEy +69H0 +-----END ENCRYPTED PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/pass.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/pass.1024.pub new file mode 100644 index 0000000..617e7fb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/pass.1024.pub @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSK/7i5BV0x+gmX16Wrm7kRkCZ +y1QUt6wiM2g+SAZTYR0381VnSMX2cv7CpN3499lZj1rL5S7YTaZZwX3RvU5fz56/ +eDX6ciL/PZsbclN2KdkMWYgmcb9J1zUeoMQ3cjfFUCdQZ/ZvDWa+wY2Zg8os2Bow +AoufHtYHm3eOly/cWwIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.1024.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.1024.priv new file mode 100644 index 0000000..d3b5fda --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.1024.priv @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICVAIBAAJ/OwswbFo/uyC8ltGf/yA1A+gV5IGdnAgPbUSI3GzbHCA+x+TLG/tL +vbRw3r1smppY/jkkpiVW1ErSMuN0uixp5gb78Z9rH1XpWb5WWgp3WaY/9EHMjMdO +kQ/9LVZvRvl/M/Fi6owP+q+amJI1BEjECYfbhGL3rmlVdq4qXc40QwIDAQABAn8I +VZ0BPoAOhyF33KFMHxy8r28fsVgxJUYgM3NqQgdv4fFawCYXjhJz9duU5YJGFJGJ +WUGeHlkyYFlpi4f3m7tY7JawmQUWB0MNSoKHI3cgDX4/tfBN8ni+cO0eSoR5czBY +EsAHBU47p1awNFAHwd+ZEuv9H4RmMn7p279rQTtpAkAH3Nqs2/vrRF2cZUN4fIXf +4xHsQBByUayGq8a3J0UGaSFWv68zTUKFherr9uZotNp7NJ4jBXiARw0q8docXUG1 +AkAHgmOKHoORtAmikqpmFEJZOtsXMaLCIm4EszPo5ciYoLMBcVit09AdiQlt7ZJL +DY02svU1b0agCZ97kDkmHDkXAkACa8M9JELuDs/P/vIGYDkMVatIFfW6bWF02eFG +taWwMqCcSEsWvbw0xqYt34jURpNbCjmCyQVwYfAw/+TLhP9dAkAFwRjdwjw37qpj +ddg1mNiu37b7swFxmkiMOXZRxaNNsfb56A14RpN3zob3QdGUybGodMIKTFbmU/lu +CjqAxafJAkAG2yf6RWbwFIWfMyt7WYCh0VaGBCcgy574AinVieEo3ZZyFfC63+xm +3uoaNy4iLoJv4GCjqUBz3ZfcVaO/DDWG +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.1024.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.1024.pub new file mode 100644 index 0000000..7ba0636 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.1024.pub @@ -0,0 +1,5 @@ +-----BEGIN RSA PUBLIC KEY----- +MIGGAn87CzBsWj+7ILyW0Z//IDUD6BXkgZ2cCA9tRIjcbNscID7H5Msb+0u9tHDe +vWyamlj+OSSmJVbUStIy43S6LGnmBvvxn2sfVelZvlZaCndZpj/0QcyMx06RD/0t +Vm9G+X8z8WLqjA/6r5qYkjUESMQJh9uEYveuaVV2ripdzjRDAgMBAAE= +-----END RSA PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.2028.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.2028.priv new file mode 100644 index 0000000..10e651d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.2028.priv @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEjwIBAAKB/gy7mjaWgPeFdVYDZWRCA9BNiv3pPb0es27+FKY0hszLaOw47ExC +tAWpDsH48TXAfyHBYwBLguayfk4LGIupxb+CGMbRo3xEp0CbfY1Jby26T9vGjRC1 +foHDDUJG84uaRbyHqaf4i6zt4gVR+xlAEIjkaFAAK8cOoXAT1CVqGLLljUCchL8P +jaHj/yriZ/S7rdwlI3LnABxwwmLrmR/v71WtpmO/aNG8N+1po+QwaghTkyQ59E/Z +vAuOkFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQaEDRbBFBmBqTv5fFGfk2WsAfKf/R +G0/VFd+ZeM5251TeTvXH695nlSGauVl9AgMBAAECgf4LrWHY/l54ouThZWvvbrug +pfz6sJX2g9l7yXmWlEWsPECVo/7SUbpYFpt6OZy99zSg+IKbGqWKfdhoKrTwIVtC +L0YZ0NlmdnANSIz0roxQG7ZxkL5+vHSw/PmD9x4Uwf+Cz8hATCmNBv1qc60dkyuW +4CLqe72qaTiVWRoO1iagQghNcLoo6vSy65ExLaCDTPha7yu2vw4hFZpWiEjW4dxf +rFdLiix52BC86YlAlxME/rLg8IJVvilbyo9aWdXmxOaUTLRv6PkFD1/gVdw8V9Qr +SLN9FlK2kkjiX0dzoibvZw3tMnt3yydAx0X87+sMRVahC1bp3kVPz4Hy0EWX4QJ/ +PM31vGiuITk2NCd51DXt1Ltn2OP5FaJSmCaEjh0XkU4qouYyjXWt8Bu6BTCl2vua +Fg0Uji9C+IkPLmaUMbMIOwaTk8cWqLthSxsLe70J5OkGrgfKUM/w+BHH1Pt/Pjzj +C++l0kiFaOVDVaAV9GpLPLCBoK/PC9Rb/rxMMoCCNwJ/NZuedIny2w3LMii77h/T +zSvergNGhjY6Rnva8lLXJ6dlrkcPAyps3gWwxqj4NR0T+GM0bDUPVLb7M07XV7SX +v7VJGm52JbRGwM1ss+r8XTTNemeGk+WRxG7TgtsMqYGXLfB8Qxk/f5/Mcc00Tl8u +wXFNsfxJxmt6AbsTr3g36wJ/IhOnibz9Ad+nchlBnN3QeW3CKHqzaR18voqvtVm2 +kJfHK15prH/sSGmxmiEGgrCJTZxtDbaNCO7/VBjnKudUUIhCAwsLtuq0/zub9vAd +8G1scfIpv5qaSNzmKoX8bOwArvrS6wP7yKrcTsuWIlHD8rJVI7IEDnQoTp5G8fK1 +hwJ/MIh8M5v0r5dUYEv6oIJWGcle6AH1JmsP5WIafgq72Z2288pHcCFHwNY8Dg9J +76QswVLnUhPTlmm3EOOPGEtam2iAD5r0Afytlb4lbNoQsj2szeXONDXB+6oueajh +VNELUr8HcSP5lgzRZjJW6aFIzj9LDRmQnUAOjGSXVOQtEwJ/MCQZ7N/v4dIKeDRA +8d8UExZ3+gGHumziztGRJ0tQryZH2PakP5I7V+1l7qEUnJ2c3mF+e1v41Ep9LCvh +bzrPKw9dxh18g4b+7bMpsWPnsraKh6ipxc7aaOaZV0Dxgez4zcZu0P1olO0cN3KM +nxJ0Pds3R8bAhNCDdS2JZaRp5Q== +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.2028.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.2028.pub new file mode 100644 index 0000000..b36dca4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.2028.pub @@ -0,0 +1,8 @@ +-----BEGIN RSA PUBLIC KEY----- +MIIBBgKB/gy7mjaWgPeFdVYDZWRCA9BNiv3pPb0es27+FKY0hszLaOw47ExCtAWp +DsH48TXAfyHBYwBLguayfk4LGIupxb+CGMbRo3xEp0CbfY1Jby26T9vGjRC1foHD +DUJG84uaRbyHqaf4i6zt4gVR+xlAEIjkaFAAK8cOoXAT1CVqGLLljUCchL8PjaHj +/yriZ/S7rdwlI3LnABxwwmLrmR/v71WtpmO/aNG8N+1po+QwaghTkyQ59E/ZvAuO +kFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQaEDRbBFBmBqTv5fFGfk2WsAfKf/RG0/V +Fd+ZeM5251TeTvXH695nlSGauVl9AgMBAAE= +-----END RSA PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.pass.priv b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.pass.priv new file mode 100644 index 0000000..99e8213 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.pass.priv @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-256-CBC,7A6A055AD675947A657041422F06D439 + +HQdjzAKUuqqKhZHmpzzY/monfqFhiHnZ5c24jtR9fM4aQJXf/e1fz6MEhyIz6XON +sb4CnXZstnxUuVWDkHEu6KWQ/dKALgiDUuT+UdMawVoVPGdgyWZp35pQPWi3fT2V +XZn58YkG8bO3Y403eZPyhadOefD1VtuFuK6/f90jjzx6ZDnwveXpYgFV7Jy1/pFd +cLLMf07C+hbk416nX6UVipWe4GH+ADFom5ZCfAaUotM7n8i149dULNF4YYi2wP31 +1YaDH5vf1CqiaieDY7xLzpEixwJz6ZEg3gLXaUvz2MpF8owiGI3eP0g7voWp3xt4 +TQx/qDURlaXiaRriWdWtpKyW1MFuJ5+KdNtR1/kXr2BLPB/ZLwyqtynUy8ZYpb4+ +WIRYpUGeb//ZHGhlCH7CRMdABsal4wTwnzi9fW4Ax96ecJ2SlwCuKxwS7iEq2y1/ +FAfGwsE+XufHhme5p6XjKfiHx+zJMIB2NMkrm+wm4PbMTrGVnw5/41/r6XxOB8fe +iKi12Jth4dusc1vYGYfzKop9uEM6CZ6+Chqzb+Zyh/xUiZVlCX/BYnxr7yXUm9aR +PHQgxkn2Act8FgQB3Kgs3jCiCRIJrlsnybeWzQ3YO9TjC4MxygmmwODDBpsOKnEi +kXXS54+cZFjcsva4uJVwhAywRPVUkLzmTkH0tGiwCHjeQNECm+TLahkkEIXrVTb9 +c9creNXMgE6jVVz+R43HXsGvTcgMcBLyFRQJe2nVaj/dQ5JbF4uqNnQzRjAbD34K +uTpFaJ/kmlgcmeScRLnwaoYwFlmhSC+bK0dfY1Jr6AQRA6IDP7nIjqWNDCHNBB8r +Qj1v2KWoVQe3xNHaXhkbJPbA2DKlUIqffkBVtMKtt9KuG3Rccf3bVYAW6oid73/D +z7DMAF5G/OpVR8VbGh1WxXuR7zEVDUwpwsp9ek5dqN8BnBz1ppdZNIKqzszneckU +s2l/6mZBmgV1Nfy/cQU6U5s3S1Xc75UDQVLms3CIOpFTRIpecNTdfa31fYy/svy0 +M2lWTbCva0dOyuvMUhTgBL4I7Qa2dUMPXHMZatV5ooHYq/BZJA1r84C5cM5r+umE +2LLv/BlUr7RaQHhaKGn4Qhpzo5yRDE9mEqDpLVkbg8SxMsdf/pEF5/VyUwA9t8RT +fKVsInRd386tDqJSDbSFqKTvLztr/5YCyzZzvC2YB1voko/caOGd2d/G51Ij+bXU +xEN8U4fHDBsHwPUGb31uZUhTXpL37KiOqZmXFoH2usmuvx882XvyGcV0F4tstMaR +KLKzl2PwqzAYGFexLkYKMz0TYIeN6h3b86ETazPPU49nkaEU23Dx21J2Rb3UlH+I +lDQF3wuH1QlYiTnlcVa/Zu4QQg0/iP8ALkZ06mvn9e9mOtnA8gsh4B2oLqc19VLU +bcpv40dV1H3W9Lcx9B8JYUp0c/Oyno1D7Yj3tjGcwMKECmUpHi4kksehVo0/P933 +xmFmC6eyWYVdO9upvY/vKSB7b1dMt85iWr3gnMsSfRYc6jsbSxdjOPST46UsIzjx +wa1DS6+Bv5tiaC4uC6X+0tCAZo+UOQMYUbTGRR/7g/c= +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.pass.pub b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.pass.pub new file mode 100644 index 0000000..655cc3a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/rsa.pass.pub @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBHjANBgkqhkiG9w0BAQEFAAOCAQsAMIIBBgKB/gy7mjaWgPeFdVYDZWRCA9BN +iv3pPb0es27+FKY0hszLaOw47ExCtAWpDsH48TXAfyHBYwBLguayfk4LGIupxb+C +GMbRo3xEp0CbfY1Jby26T9vGjRC1foHDDUJG84uaRbyHqaf4i6zt4gVR+xlAEIjk +aFAAK8cOoXAT1CVqGLLljUCchL8PjaHj/yriZ/S7rdwlI3LnABxwwmLrmR/v71Wt +pmO/aNG8N+1po+QwaghTkyQ59E/ZvAuOkFWHok2q/R6PYAa2jdZ9zim0FqOP+nkQ +aEDRbBFBmBqTv5fFGfk2WsAfKf/RG0/VFd+ZeM5251TeTvXH695nlSGauVl9AgMB +AAE= +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_cert.pem b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_cert.pem new file mode 100644 index 0000000..a3c1e4a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV +BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l +czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh +dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw +OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG +A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz +dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG +9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO +kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR +AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k +d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG +A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG +EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx +EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl +MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G +CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP +e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n +dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN +-----END CERTIFICATE----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_key.pem b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_key.pem new file mode 100644 index 0000000..48fd93c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_key.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd +CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre +535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB +AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 +kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb +aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 +2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC +M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg +lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM +wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm +Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR +9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd +0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_privkey.pem b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_privkey.pem new file mode 100644 index 0000000..425518a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_privkey.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF +NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F +UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB +AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA +QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK +kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg +f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u +412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc +mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 +kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA +gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW +G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI +7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_privkey_encrypted.pem b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_privkey_encrypted.pem new file mode 100644 index 0000000..08e7617 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_privkey_encrypted.pem @@ -0,0 +1,18 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-128-CBC,9D916E00476DFF9E70FA4BA9E3A6CB0E + +oj0VC35ShSEqlfJ0rLGgkqJCyIK+mXSsa/X/xAur+lI/RVOVTWd7oQQGTdI/0rLX +PdQR02Na3X9Rptezh6J04PfMGeFysxdT6RpC+rkHRPVbN0F4TqxSNNXzkwK70+EF +dSuDMyVKv9YN4wWDf0g6VKe4ShAH/sqICQBrVyzWyYLvH/hwZmZZ1QEab6ylIKtb +EJunwu9BxVVA04bbuATKkKjJOqDn0fG8hb4bYbyD02dJwgLePzzn36F31kcBCEHI +tESlD3RsS+EtfpfgPkplXNOhqYzkD9auDb7Zy+ZwL20fjnJb75OSGu8gOg3KTljt +mApZOg0nJ5Jk9ATAdyzyVSFOM1Hhcw12ws06Dq9KRnXgO6bbuadLTFRDdvSYDFvD +ijUb+97UolQfYIXQMqXli3EIvHr7CTWe/3mpoDgK1mtr0+923Bm97XgE7KSr0L46 +n5QpNjCZf1vbXldNmW+TRifiJMgtVdS7x0N4vqDPNEe+FelVv3U4Pz3HIOtFuWLr +ZCxlgVxJY4IsyYlV0ItQjIv8fJiAyemZdO2lA9K6h0eEF+9Apr3i79JGWUi74p5D +Ooak4le0Va9O34f6FxCGn/a54A6bhKu24Ub/0gr/e4WRa7693euEdgIAZXhtMu2Z +taU5SKjjXPzjmRCM2kINHTCENlaU4oFzTmj3TYY/jdKyNP1bHa07NhlomladkIHK +GD6HaYkcbuwvh8hOPsopSwuS+NqjnGPq9Vv4ecBC+9veDEmpIE1iR6FK9Hjrre88 +kLoMQNmA+vuc8jG4/FIHM3SauQiR1ZJ6+zkz97kcmOf+X7LRaS4j6lfFR6qHiJ6y +-----END RSA PRIVATE KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_pubkey.pem b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_pubkey.pem new file mode 100644 index 0000000..b3bbf6c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/test/test_rsa_pubkey.pem @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3 +6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6 +Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw +oYi+1hqp1fIekaxsyQIDAQAB +-----END PUBLIC KEY----- diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/withPublic.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/withPublic.js new file mode 100644 index 0000000..abdbe35 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/withPublic.js @@ -0,0 +1,10 @@ +var bn = require('bn.js'); +function withPublic(paddedMsg, key) { + return new Buffer(paddedMsg + .toRed(bn.mont(key.modulus)) + .redPow(new bn(key.publicExponent)) + .fromRed() + .toArray()); +} + +module.exports = withPublic; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/xor.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/xor.js new file mode 100644 index 0000000..aca8131 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/public-encrypt/xor.js @@ -0,0 +1,8 @@ +module.exports = function xor(a, b) { + var len = a.length; + var i = -1; + while (++i < len) { + a[i] ^= b[i]; + } + return a +}; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/.travis.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/.travis.yml new file mode 100644 index 0000000..f8eebd8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +matrix: + include: + - node_js: '0.10' + env: TEST_SUITE=test + - node_js: '0.12' + env: TEST_SUITE=test + - node_js: '5' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=phantom +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/.zuul.yml new file mode 100644 index 0000000..96d9cfb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/.zuul.yml @@ -0,0 +1 @@ +ui: tape diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/README.md b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/README.md new file mode 100644 index 0000000..3bacba4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/README.md @@ -0,0 +1,14 @@ +randombytes +=== + +[![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes) + +randombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues + +```js +var randomBytes = require('randombytes'); +randomBytes(16);//get 16 random bytes +randomBytes(16, function (err, resp) { + // resp is 16 random bytes +}); +``` diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/browser.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/browser.js new file mode 100644 index 0000000..1aa3edc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/browser.js @@ -0,0 +1,36 @@ +'use strict' + +function oldBrowser () { + throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') +} + +var crypto = global.crypto || global.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > 65536) throw new Error('requested too many random bytes') + // in case browserify isn't using the Uint8Array version + var rawBytes = new global.Uint8Array(size) + + // This will not work in older browsers. + // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + if (size > 0) { // getRandomValues fails on IE if size == 0 + crypto.getRandomValues(rawBytes) + } + // phantomjs doesn't like a buffer being passed here + var bytes = new Buffer(rawBytes.buffer) + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/index.js new file mode 100644 index 0000000..a2d9e39 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').randomBytes diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/package.json new file mode 100644 index 0000000..b47927b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/package.json @@ -0,0 +1,39 @@ +{ + "name": "randombytes", + "version": "2.0.3", + "description": "random bytes from browserify stand alone", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec", + "phantom": "zuul --phantom -- test.js", + "local": "zuul --local --no-coverage -- test.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/crypto-browserify/randombytes.git" + }, + "keywords": [ + "crypto", + "random" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/randombytes/issues" + }, + "homepage": "https://github.com/crypto-browserify/randombytes", + "browser": "browser.js", + "devDependencies": { + "phantomjs": "^1.9.9", + "standard": "^3.3.0", + "tap-spec": "^2.1.2", + "tape": "^3.0.3", + "zuul": "^3.7.2" + }, + "readme": "randombytes\n===\n\n[![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes)\n\nrandombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues\n\n```js\nvar randomBytes = require('randombytes');\nrandomBytes(16);//get 16 random bytes\nrandomBytes(16, function (err, resp) {\n // resp is 16 random bytes\n});\n```\n", + "readmeFilename": "README.md", + "_id": "randombytes@2.0.3", + "_shasum": "674c99760901c3c4112771a31e521dc349cc09ec", + "_resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.0.3.tgz", + "_from": "https://registry.npmjs.org/randombytes/-/randombytes-2.0.3.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/test.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/test.js new file mode 100644 index 0000000..8e34dca --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/node_modules/randombytes/test.js @@ -0,0 +1,56 @@ +var test = require('tape') +var randomBytes = require('./') + +test('sync', function (t) { + t.plan(4) + t.equals(randomBytes(0).length, 0, 'len: ' + 0) + t.equals(randomBytes(3).length, 3, 'len: ' + 3) + t.equals(randomBytes(30).length, 30, 'len: ' + 30) + t.equals(randomBytes(300).length, 300, 'len: ' + 300) +}) + +test('async', function (t) { + t.plan(4) + + randomBytes(0, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 0, 'len: ' + 0) + }) + + randomBytes(3, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 3, 'len: ' + 3) + }) + + randomBytes(30, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 30, 'len: ' + 30) + }) + + randomBytes(300, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 300, 'len: ' + 300) + }) +}) + +if (process.browser) { + test('requesting to much throws', function (t) { + t.plan(1) + t.throws(function () { + randomBytes(65537) + }) + }) + + test('requesting to much throws async', function (t) { + t.plan(1) + t.throws(function () { + randomBytes(65537, function () { + t.ok(false, 'should not get here') + }) + }) + }) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/package.json new file mode 100644 index 0000000..2832a1f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/package.json @@ -0,0 +1,57 @@ +{ + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "name": "crypto-browserify", + "description": "implementation of crypto for the browser", + "version": "3.11.0", + "homepage": "https://github.com/crypto-browserify/crypto-browserify", + "repository": { + "type": "git", + "url": "git://github.com/crypto-browserify/crypto-browserify.git" + }, + "scripts": { + "standard": "standard", + "test": "npm run standard && npm run unit", + "unit": "node test/", + "browser": "zuul --browser-version $BROWSER_VERSION --browser-name $BROWSER_NAME -- test/index.js" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0" + }, + "devDependencies": { + "hash-test-vectors": "~1.3.2", + "pseudorandombytes": "^2.0.0", + "standard": "^5.0.2", + "tape": "~2.3.2", + "zuul": "^3.6.0" + }, + "optionalDependencies": {}, + "browser": { + "crypto": false + }, + "license": "MIT", + "readme": "# crypto-browserify\n\nA port of node's `crypto` module to the browser.\n\n[![Build Status](https://travis-ci.org/crypto-browserify/crypto-browserify.svg?branch=master)](https://travis-ci.org/crypto-browserify/crypto-browserify)\n[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n[![Sauce Test Status](https://saucelabs.com/browser-matrix/crypto-browserify.svg)](https://saucelabs.com/u/crypto-browserify)\n\nThe goal of this module is to reimplement node's crypto module,\nin pure javascript so that it can run in the browser.\n\nHere is the subset that is currently implemented:\n\n* createHash (sha1, sha224, sha256, sha384, sha512, md5, rmd160)\n* createHmac (sha1, sha224, sha256, sha384, sha512, md5, rmd160)\n* pbkdf2\n* pbkdf2Sync\n* randomBytes\n* pseudoRandomBytes\n* createCipher (aes)\n* createDecipher (aes)\n* createDiffieHellman\n* createSign (rsa, ecdsa)\n* createVerify (rsa, ecdsa)\n* createECDH (secp256k1)\n* publicEncrypt/privateDecrypt (rsa)\n\n## todo\n\nthese features from node's `crypto` are still unimplemented.\n\n* createCredentials\n\n## contributions\n\nIf you are interested in writing a feature, please implement as a new module,\nwhich will be incorporated into crypto-browserify as a dependency.\n\nAll deps must be compatible with node's crypto\n(generate example inputs and outputs with node,\nand save base64 strings inside JSON, so that tests can run in the browser.\nsee [sha.js](https://github.com/dominictarr/sha.js)\n\nCrypto is _extra serious_ so please do not hesitate to review the code,\nand post comments if you do.\n\n## License\n\nMIT\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/crypto-browserify/crypto-browserify/issues" + }, + "_id": "crypto-browserify@3.11.0", + "_shasum": "3652a0906ab9b2a7e0c3ce66a408e957a2485522", + "_resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.11.0.tgz", + "_from": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.11.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/aes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/aes.js new file mode 100644 index 0000000..916a019 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/aes.js @@ -0,0 +1,49 @@ +var test = require('tape') +var crypto = require('browserify-cipher/browser') +var randomBytes = require('pseudorandombytes') + +function runIt (i) { + crypto.listCiphers().forEach(function (cipher) { + test('run: ' + i, function (t) { + t.test('ciphers: ' + cipher, function (t) { + t.plan(1) + var data = randomBytes(562) + var password = randomBytes(20) + var crypter = crypto.createCipher(cipher, password) + var decrypter = crypto.createDecipher(cipher, password) + var out = [] + out.push(decrypter.update(crypter.update(data))) + out.push(decrypter.update(crypter.final())) + if (cipher.indexOf('gcm') > -1) { + decrypter.setAuthTag(crypter.getAuthTag()) + } + out.push(decrypter.final()) + t.equals(data.toString('hex'), Buffer.concat(out).toString('hex')) + }) + }) + }) + if (i < 4) { + setTimeout(runIt, 0, i + 1) + } +} +runIt(1) +test('getCiphers', function (t) { + t.plan(1) + t.ok(crypto.getCiphers().length, 'get ciphers returns an array') +}) + +test('through crypto browserify works', function (t) { + t.plan(2) + var crypto = require('../') + var cipher = 'aes-128-ctr' + var data = randomBytes(562) + var password = randomBytes(20) + var crypter = crypto.createCipher(cipher, password) + var decrypter = crypto.createDecipher(cipher, password) + var out = [] + out.push(decrypter.update(crypter.update(data))) + out.push(decrypter.update(crypter.final())) + out.push(decrypter.final()) + t.equals(data.toString('hex'), Buffer.concat(out).toString('hex')) + t.ok(crypto.getCiphers().length, 'get ciphers returns an array') +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/create-hash.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/create-hash.js new file mode 100644 index 0000000..33532fd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/create-hash.js @@ -0,0 +1,50 @@ +var test = require('tape') + +var algorithms = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'] +var encodings = ['hex', 'base64'] // FIXME: test binary +var vectors = require('hash-test-vectors') + +testLib('createHash in crypto-browserify', require('../').createHash) +testLib('create-hash/browser', require('create-hash/browser')) + +function testLib (name, createHash) { + algorithms.forEach(function (algorithm) { + runTest(name, createHash, algorithm) + }) +} +function runTest (name, createHash, algorithm) { + test(name + ' test ' + algorithm + ' against test vectors', function (t) { + run(0) + function run (i) { + if (i >= vectors.length) { + return t.end() + } + var obj = vectors[i] + + var input = new Buffer(obj.input, 'base64') + var node = obj[algorithm] + var js = createHash(algorithm).update(input).digest('hex') + if (js !== node) { + t.equal(js, node, algorithm + '(testVector[' + i + ']) == ' + node) + } + + encodings.forEach(function (encoding) { + var input = new Buffer(obj.input, 'base64').toString(encoding) + var node = obj[algorithm] + var js = createHash(algorithm).update(input, encoding).digest('hex') + if (js !== node) { + t.equal(js, node, algorithm + '(testVector[' + i + '], ' + encoding + ') == ' + node) + } + }) + input = new Buffer(obj.input, 'base64') + node = obj[algorithm] + var hash = createHash(algorithm) + hash.end(input) + js = hash.read().toString('hex') + if (js !== node) { + t.equal(js, node, algorithm + '(testVector[' + i + ']) == ' + node) + } + setTimeout(run, 0, i + 1) + } + }) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/create-hmac.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/create-hmac.js new file mode 100644 index 0000000..08488ab --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/create-hmac.js @@ -0,0 +1,50 @@ +var test = require('tape') + +var algorithms = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'] +var vectors = require('hash-test-vectors/hmac') +testLib('createHmac in crypto-browserify', require('../').createHmac) +testLib('create-hmac/browser', require('create-hmac/browser')) + +function testLib (name, createHmac) { + algorithms.forEach(function (alg) { + test(name + ' hmac(' + alg + ')', function (t) { + run(0) + function run (i) { + if (i >= vectors.length) { + return t.end() + } + var input = vectors[i] + var output = createHmac(alg, new Buffer(input.key, 'hex')) + .update(input.data, 'hex').digest() + + output = input.truncate ? output.slice(0, input.truncate) : output + output = output.toString('hex') + if (output !== input[alg]) { + t.equal(output, input[alg]) + } + setTimeout(run, 0, i + 1) + } + }) + + test('hmac(' + alg + ')', function (t) { + run(0) + function run (i) { + if (i >= vectors.length) { + return t.end() + } + var input = vectors[i] + var hmac = createHmac(alg, new Buffer(input.key, 'hex')) + + hmac.end(input.data, 'hex') + var output = hmac.read() + + output = input.truncate ? output.slice(0, input.truncate) : output + output = output.toString('hex') + if (output !== input[alg]) { + t.equal(output, input[alg]) + } + setTimeout(run, 0, i + 1) + } + }) + }) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/dh.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/dh.js new file mode 100644 index 0000000..61fd074 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/dh.js @@ -0,0 +1,49 @@ +var test = require('tape') +var crypto = require('diffie-hellman/browser') + +test('diffie-hellman mod groups', function (t) { + [ + 'modp1', 'modp2', 'modp5', 'modp14', 'modp15', 'modp16' + ].forEach(function (mod) { + t.test(mod, function (t) { + t.plan(3) + var dh1 = crypto.getDiffieHellman(mod) + var p1 = dh1.getPrime().toString('hex') + dh1.generateKeys() + var dh2 = crypto.getDiffieHellman(mod) + var p2 = dh2.getPrime().toString('hex') + dh2.generateKeys() + t.equals(p1, p2, 'equal primes') + var pubk1 = dh1.getPublicKey() + var pubk2 = dh2.getPublicKey() + t.notEquals(pubk1, pubk2, 'diff public keys') + var pub1 = dh1.computeSecret(pubk2).toString('hex') + var pub2 = dh2.computeSecret(dh1.getPublicKey()).toString('hex') + t.equals(pub1, pub2, 'equal secrets') + }) + }) +}) + +test('diffie-hellman key lengths', function (t) { + [ + 64, 65, 192 + ].forEach(function (len) { + t.test('' + len, function (t) { + t.plan(3) + var dh2 = crypto.createDiffieHellman(len) + var prime2 = dh2.getPrime() + var p2 = prime2.toString('hex') + var dh1 = crypto.createDiffieHellman(prime2) + var p1 = dh1.getPrime().toString('hex') + dh1.generateKeys() + dh2.generateKeys() + t.equals(p1, p2, 'equal primes') + var pubk1 = dh1.getPublicKey() + var pubk2 = dh2.getPublicKey() + t.notEquals(pubk1, pubk2, 'diff public keys') + var pub1 = dh1.computeSecret(pubk2).toString('hex') + var pub2 = dh2.computeSecret(dh1.getPublicKey()).toString('hex') + t.equals(pub1, pub2, 'equal secrets') + }) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/ecdh.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/ecdh.js new file mode 100644 index 0000000..86b5aed --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/ecdh.js @@ -0,0 +1,61 @@ +var mods = [ + 'secp256k1', + 'secp224r1', + 'prime256v1', + 'prime192v1' +] +var test = require('tape') +var _crypto = require('../') +var createECDH1 = _crypto.createECDH +var createECDH2 = require('create-ecdh/browser') + +mods.forEach(function (mod) { + test('createECDH: ' + mod + ' uncompressed', function (t) { + t.plan(2) + var dh1 = createECDH1(mod) + dh1.generateKeys() + var dh2 = createECDH2(mod) + dh2.generateKeys() + var pubk1 = dh1.getPublicKey() + var pubk2 = dh2.getPublicKey() + t.notEquals(pubk1.toString('hex'), pubk2.toString('hex'), 'diff public keys') + var pub1 = dh1.computeSecret(pubk2).toString('hex') + var pub2 = dh2.computeSecret(pubk1).toString('hex') + t.equals(pub1, pub2, 'equal secrets') + }) + + test('createECDH: ' + mod + ' compressed', function (t) { + t.plan(2) + var dh1 = createECDH1(mod) + dh1.generateKeys() + var dh2 = createECDH2(mod) + dh2.generateKeys() + var pubk1 = dh1.getPublicKey(null, 'compressed') + var pubk2 = dh2.getPublicKey(null, 'compressed') + t.notEquals(pubk1.toString('hex'), pubk2.toString('hex'), 'diff public keys') + var pub1 = dh1.computeSecret(pubk2).toString('hex') + var pub2 = dh2.computeSecret(pubk1).toString('hex') + t.equals(pub1, pub2, 'equal secrets') + }) + + test('createECDH: ' + mod + ' set stuff', function (t) { + t.plan(5) + var dh1 = createECDH1(mod) + var dh2 = createECDH2(mod) + dh1.generateKeys() + dh2.generateKeys() + dh1.setPrivateKey(dh2.getPrivateKey()) + dh1.setPublicKey(dh2.getPublicKey()) + var priv1 = dh1.getPrivateKey('hex') + var priv2 = dh2.getPrivateKey('hex') + t.equals(priv1, priv2, 'same private key') + var pubk1 = dh1.getPublicKey() + var pubk2 = dh2.getPublicKey() + t.equals(pubk1.toString('hex'), pubk2.toString('hex'), 'same public keys, uncompressed') + t.equals(dh1.getPublicKey('hex', 'compressed'), dh2.getPublicKey('hex', 'compressed'), 'same public keys compressed') + t.equals(dh1.getPublicKey('hex', 'hybrid'), dh2.getPublicKey('hex', 'hybrid'), 'same public keys hybrid') + var pub1 = dh1.computeSecret(pubk2).toString('hex') + var pub2 = dh2.computeSecret(pubk1).toString('hex') + t.equals(pub1, pub2, 'equal secrets') + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/index.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/index.js new file mode 100644 index 0000000..0a9d290 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/index.js @@ -0,0 +1,18 @@ + +require('./create-hash') +require('./create-hmac') +if (!process.browser) { + require('./dh') +} + +require('./pbkdf2') +try { + require('randombytes')(8) + require('./ecdh') + require('./public-encrypt') + require('./random-bytes') + require('./sign') +} catch (e) { + console.log('no secure rng avaiable') +} +require('./aes') diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/node/dh.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/node/dh.js new file mode 100644 index 0000000..0b3aa71 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/node/dh.js @@ -0,0 +1,51 @@ +var test = require('tape') +var cryptoB = require('../../') +var crypto = require('crypto') + +test('diffie-hellman mod groups', function (t) { + [ + 'modp1', 'modp2', 'modp5', 'modp14', 'modp15', 'modp16' + ].forEach(function (mod) { + t.test(mod, function (t) { + t.plan(3) + var dh1 = cryptoB.getDiffieHellman(mod) + var p1 = dh1.getPrime().toString('hex') + dh1.generateKeys() + + var dh2 = crypto.getDiffieHellman(mod) + var p2 = dh2.getPrime().toString('hex') + dh2.generateKeys() + t.equals(p1, p2, 'equal primes') + var pubk1 = dh1.getPublicKey() + var pubk2 = dh2.getPublicKey() + t.notEquals(pubk1, pubk2, 'diff public keys') + var pub1 = dh1.computeSecret(pubk2).toString('hex') + var pub2 = dh2.computeSecret(pubk1).toString('hex') + t.equals(pub1, pub2, 'equal secrets') + }) + }) +}) + +test('diffie-hellman key lengths', function (t) { + [ + 64, 65, 192 + ].forEach(function (len) { + t.test('' + len, function (t) { + t.plan(3) + var dh2 = cryptoB.createDiffieHellman(len) + var prime2 = dh2.getPrime() + var p2 = prime2.toString('hex') + var dh1 = crypto.createDiffieHellman(prime2) + var p1 = dh1.getPrime().toString('hex') + dh1.generateKeys() + dh2.generateKeys() + t.equals(p1, p2, 'equal primes') + var pubk1 = dh1.getPublicKey() + var pubk2 = dh2.getPublicKey() + t.notEquals(pubk1, pubk2, 'diff public keys') + var pub1 = dh1.computeSecret(pubk2).toString('hex') + var pub2 = dh2.computeSecret(dh1.getPublicKey()).toString('hex') + t.equals(pub1, pub2, 'equal secrets') + }) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/pbkdf2.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/pbkdf2.js new file mode 100644 index 0000000..084014e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/pbkdf2.js @@ -0,0 +1,21 @@ +var tape = require('tape') +var crypto = require('pbkdf2/browser') + +var vectors = require('hash-test-vectors/pbkdf2') + +tape('pbkdf2', function (t) { + vectors.forEach(function (input) { + // skip inputs that will take way too long + if (input.iterations > 10000) return + + var key = crypto.pbkdf2Sync(input.password, input.salt, input.iterations, input.length) + + if (key.toString('hex') !== input.sha1) { + console.log(input) + } + + t.equal(key.toString('hex'), input.sha1) + }) + + t.end() +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/public-encrypt.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/public-encrypt.js new file mode 100644 index 0000000..edb435c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/public-encrypt.js @@ -0,0 +1,36 @@ +var test = require('tape') +var crypto1 = require('../') +var rsa = { + 'private': '2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a4d4949456a77494241414b422f6779376d6a615767506546645659445a5752434139424e69763370506230657332372b464b593068737a4c614f7734374578430a744157704473483438545841667948425977424c67756179666b344c4749757078622b43474d62526f337845703043626659314a62793236543976476a5243310a666f484444554a4738347561526279487161663469367a74346756522b786c4145496a6b614641414b38634f6f58415431435671474c4c6c6a554363684c38500a6a61486a2f7972695a2f53377264776c49334c6e41427877776d4c726d522f7637315774706d4f2f614e47384e2b31706f2b5177616768546b79513539452f5a0a7641754f6b4657486f6b32712f523650594161326a645a397a696d3046714f502b6e6b5161454452624246426d4271547635664647666b32577341664b662f520a47302f5646642b5a654d353235315465547658483639356e6c53476175566c3941674d42414145436766344c725748592f6c35346f7554685a577676627275670a70667a36734a583267396c3779586d576c455773504543566f2f375355627059467074364f5a7939397a53672b494b624771574b6664686f4b725477495674430a4c30595a304e6c6d646e414e53497a30726f785147375a786b4c352b764853772f506d443978345577662b437a38684154436d4e42763171633630646b7975570a34434c71653732716154695657526f4f316961675167684e634c6f6f36765379363545784c614344545068613779753276773468465a705769456a57346478660a7246644c696978353242433836596c416c784d452f724c6738494a5676696c62796f39615764586d784f6155544c527636506b4644312f6756647738563951720a534c4e39466c4b326b6b6a695830647a6f6962765a7733744d6e74337979644178305838372b734d5256616843316270336b56507a3448793045575834514a2f0a504d33317647697549546b324e43643531445874314c746e324f503546614a536d4361456a6830586b5534716f7559796a585774384275364254436c327675610a466730556a6939432b496b504c6d61554d624d494f7761546b386357714c74685378734c6537304a354f6b477267664b554d2f772b4248483150742f506a7a6a0a432b2b6c306b6946614f5644566141563947704c504c43426f4b2f50433952622f72784d4d6f43434e774a2f4e5a756564496e793277334c4d69693737682f540a7a53766572674e47686a5936526e7661386c4c584a36646c726b6350417970733367577778716a344e5230542b474d3062445550564c62374d303758563753580a7637564a476d35324a625247774d3173732b72385854544e656d65476b2b5752784737546774734d715947584c66423851786b2f66352f4d63633030546c38750a7758464e7366784a786d7436416273547233673336774a2f49684f6e69627a3941642b6e63686c426e4e3351655733434b48717a61523138766f717674566d320a6b4a66484b31357072482f7353476d786d6945476772434a545a78744462614e434f372f56426a6e4b756455554968434177734c747571302f7a7562397641640a384731736366497076357161534e7a6d4b6f5838624f77417276725336775037794b726354737557496c484438724a5649374945446e516f5470354738664b310a68774a2f4d4968384d35763072356455594576366f494a5747636c65364148314a6d73503557496166677137325a32323838704863434648774e59384467394a0a3736517377564c6e556850546c6d6d33454f4f50474574616d32694144357230416679746c62346c624e6f51736a32737a65584f4e4458422b366f7565616a680a564e454c55723848635350356c677a525a6a4a57366146497a6a394c44526d516e55414f6a475358564f517445774a2f4d43515a374e2f763464494b654452410a3864385545785a332b674748756d7a697a7447524a30745172795a483250616b50354937562b316c377145556e4a3263336d462b65317634314570394c4376680a627a72504b773964786831386734622b37624d707357506e7372614b6836697078633761614f615a5630447867657a347a635a753050316f6c4f30634e334b4d0a6e784a305064733352386241684e43446453324a5a61527035513d3d0a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a', + 'public': '2d2d2d2d2d424547494e20525341205055424c4943204b45592d2d2d2d2d0a4d49494242674b422f6779376d6a615767506546645659445a5752434139424e69763370506230657332372b464b593068737a4c614f773437457843744157700a4473483438545841667948425977424c67756179666b344c4749757078622b43474d62526f337845703043626659314a62793236543976476a524331666f48440a44554a4738347561526279487161663469367a74346756522b786c4145496a6b614641414b38634f6f58415431435671474c4c6c6a554363684c38506a61486a0a2f7972695a2f53377264776c49334c6e41427877776d4c726d522f7637315774706d4f2f614e47384e2b31706f2b5177616768546b79513539452f5a7641754f0a6b4657486f6b32712f523650594161326a645a397a696d3046714f502b6e6b5161454452624246426d4271547635664647666b32577341664b662f5247302f560a46642b5a654d353235315465547658483639356e6c53476175566c3941674d424141453d0a2d2d2d2d2d454e4420525341205055424c4943204b45592d2d2d2d2d0a' +} +var crypto2 = require('public-encrypt/browser') +rsa.private = new Buffer(rsa.private, 'hex') +rsa.public = new Buffer(rsa.public, 'hex') +var encrypted = '0bcd6462ad7a563be2d42b0b73e0b0a163886304e7723b025f97605144fe1781e84acdc4031327d6bccd67fe13183e8fbdc8c5fe947b49d011ce3ebb08b11e83b87a77328ca57ee77cfdc78743b0749366643d7a21b2abcd4aa32dee9832938445540ee3007b7a70191c8dc9ff2ad76fe8dfaa5362d9d2c4b31a67b816d7b7970a293cb95bf3437a301bedb9f431b7075aa2f9df77b4385bea2a37982beda467260b384a58258b5eb4e36a0e0bf7dff83589636f5f97bf542084f0f76868c9f3f989a27fee5b8cd2bfee0bae1eae958df7c3184e5a40fda101196214f371606feca4330b221f30577804bbd4f61578a84e85dcd298849f509e630d275280' + +test('publicEncrypt/privateDecrypt', function (t) { + t.test('can decrypt', function (t) { + t.plan(2) + // note encryption is ranomized so can't test to see if they encrypt the same + t.equals(crypto1.privateDecrypt(rsa.private, new Buffer(encrypted, 'hex')).toString(), 'hello there I am a nice message', 'decrypt it properly') + t.equals(crypto2.privateDecrypt(rsa.private, new Buffer(encrypted, 'hex')).toString(), 'hello there I am a nice message', 'decrypt it properly') + }) + t.test('can round trip', function (t) { + t.plan(2) + var msg = 'this is a message' + // note encryption is ranomized so can't test to see if they encrypt the same + t.equals(crypto1.privateDecrypt(rsa.private, crypto2.publicEncrypt(rsa.public, new Buffer(msg))).toString(), msg, 'round trip it') + t.equals(crypto2.privateDecrypt(rsa.private, crypto1.publicEncrypt(rsa.public, new Buffer(msg))).toString(), msg, 'round trip it') + }) +}) + +test('privateEncrypt/publicDecrypt', function (t) { + t.test('can round trip', function (t) { + t.plan(2) + var msg = 'this is a message' + // note encryption is ranomized so can't test to see if they encrypt the same + t.equals(crypto1.publicDecrypt(rsa.public, crypto2.privateEncrypt(rsa.private, new Buffer(msg))).toString(), msg, 'round trip it') + t.equals(crypto2.publicDecrypt(rsa.public, crypto1.privateEncrypt(rsa.private, new Buffer(msg))).toString(), msg, 'round trip it') + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/random-bytes.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/random-bytes.js new file mode 100644 index 0000000..398af24 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/random-bytes.js @@ -0,0 +1,60 @@ +var test = require('tape') +var crypto = require('../') + +var randomBytesFunctions = { + randomBytes: require('randombytes'), + pseudoRandomBytes: crypto.pseudoRandomBytes +} + +for (var randomBytesName in randomBytesFunctions) { + // Both randomBytes and pseudoRandomBytes should provide the same interface + var randomBytes = randomBytesFunctions[randomBytesName] + + test('get error message', function (t) { + try { + var b = randomBytes(10) + t.ok(Buffer.isBuffer(b)) + t.end() + } catch (err) { + t.ok(/not supported/.test(err.message), '"not supported" is in error message') + t.end() + } + }) + + test(randomBytesName, function (t) { + t.plan(5) + t.equal(randomBytes(10).length, 10) + t.ok(Buffer.isBuffer(randomBytes(10))) + randomBytes(10, function (ex, bytes) { + t.error(ex) + t.equal(bytes.length, 10) + t.ok(Buffer.isBuffer(bytes)) + t.end() + }) + }) + + test(randomBytesName + ' seem random', function (t) { + var L = 1000 + var b = randomBytes(L) + + var mean = [].reduce.call(b, function (a, b) { return a + b }, 0) / L + + // test that the random numbers are plausably random. + // Math.random() will pass this, but this will catch + // terrible mistakes such as this blunder: + // https://github.com/dominictarr/crypto-browserify/commit/3267955e1df7edd1680e52aeede9a89506ed2464#commitcomment-7916835 + + // this doesn't check that the bytes are in a random *order* + // but it's better than nothing. + + var expected = 256 / 2 + var smean = Math.sqrt(mean) + + // console.log doesn't work right on testling, *grumble grumble* + console.log(JSON.stringify([expected - smean, mean, expected + smean])) + t.ok(mean < expected + smean) + t.ok(mean > expected - smean) + + t.end() + }) +} diff --git a/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/sign.js b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/sign.js new file mode 100644 index 0000000..7d67685 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/crypto-browserify/test/sign.js @@ -0,0 +1,59 @@ +var test = require('tape') +var nodeCrypto = require('../') +var ourCrypto = require('browserify-sign/browser') + +var rsa = { + 'private': '2d2d2d2d2d424547494e205253412050524956415445204b45592d2d2d2d2d0a4d4949456a77494241414b422f6779376d6a615767506546645659445a5752434139424e69763370506230657332372b464b593068737a4c614f7734374578430a744157704473483438545841667948425977424c67756179666b344c4749757078622b43474d62526f337845703043626659314a62793236543976476a5243310a666f484444554a4738347561526279487161663469367a74346756522b786c4145496a6b614641414b38634f6f58415431435671474c4c6c6a554363684c38500a6a61486a2f7972695a2f53377264776c49334c6e41427877776d4c726d522f7637315774706d4f2f614e47384e2b31706f2b5177616768546b79513539452f5a0a7641754f6b4657486f6b32712f523650594161326a645a397a696d3046714f502b6e6b5161454452624246426d4271547635664647666b32577341664b662f520a47302f5646642b5a654d353235315465547658483639356e6c53476175566c3941674d42414145436766344c725748592f6c35346f7554685a577676627275670a70667a36734a583267396c3779586d576c455773504543566f2f375355627059467074364f5a7939397a53672b494b624771574b6664686f4b725477495674430a4c30595a304e6c6d646e414e53497a30726f785147375a786b4c352b764853772f506d443978345577662b437a38684154436d4e42763171633630646b7975570a34434c71653732716154695657526f4f316961675167684e634c6f6f36765379363545784c614344545068613779753276773468465a705769456a57346478660a7246644c696978353242433836596c416c784d452f724c6738494a5676696c62796f39615764586d784f6155544c527636506b4644312f6756647738563951720a534c4e39466c4b326b6b6a695830647a6f6962765a7733744d6e74337979644178305838372b734d5256616843316270336b56507a3448793045575834514a2f0a504d33317647697549546b324e43643531445874314c746e324f503546614a536d4361456a6830586b5534716f7559796a585774384275364254436c327675610a466730556a6939432b496b504c6d61554d624d494f7761546b386357714c74685378734c6537304a354f6b477267664b554d2f772b4248483150742f506a7a6a0a432b2b6c306b6946614f5644566141563947704c504c43426f4b2f50433952622f72784d4d6f43434e774a2f4e5a756564496e793277334c4d69693737682f540a7a53766572674e47686a5936526e7661386c4c584a36646c726b6350417970733367577778716a344e5230542b474d3062445550564c62374d303758563753580a7637564a476d35324a625247774d3173732b72385854544e656d65476b2b5752784737546774734d715947584c66423851786b2f66352f4d63633030546c38750a7758464e7366784a786d7436416273547233673336774a2f49684f6e69627a3941642b6e63686c426e4e3351655733434b48717a61523138766f717674566d320a6b4a66484b31357072482f7353476d786d6945476772434a545a78744462614e434f372f56426a6e4b756455554968434177734c747571302f7a7562397641640a384731736366497076357161534e7a6d4b6f5838624f77417276725336775037794b726354737557496c484438724a5649374945446e516f5470354738664b310a68774a2f4d4968384d35763072356455594576366f494a5747636c65364148314a6d73503557496166677137325a32323838704863434648774e59384467394a0a3736517377564c6e556850546c6d6d33454f4f50474574616d32694144357230416679746c62346c624e6f51736a32737a65584f4e4458422b366f7565616a680a564e454c55723848635350356c677a525a6a4a57366146497a6a394c44526d516e55414f6a475358564f517445774a2f4d43515a374e2f763464494b654452410a3864385545785a332b674748756d7a697a7447524a30745172795a483250616b50354937562b316c377145556e4a3263336d462b65317634314570394c4376680a627a72504b773964786831386734622b37624d707357506e7372614b6836697078633761614f615a5630447867657a347a635a753050316f6c4f30634e334b4d0a6e784a305064733352386241684e43446453324a5a61527035513d3d0a2d2d2d2d2d454e44205253412050524956415445204b45592d2d2d2d2d0a', + 'public': '2d2d2d2d2d424547494e20525341205055424c4943204b45592d2d2d2d2d0a4d49494242674b422f6779376d6a615767506546645659445a5752434139424e69763370506230657332372b464b593068737a4c614f773437457843744157700a4473483438545841667948425977424c67756179666b344c4749757078622b43474d62526f337845703043626659314a62793236543976476a524331666f48440a44554a4738347561526279487161663469367a74346756522b786c4145496a6b614641414b38634f6f58415431435671474c4c6c6a554363684c38506a61486a0a2f7972695a2f53377264776c49334c6e41427877776d4c726d522f7637315774706d4f2f614e47384e2b31706f2b5177616768546b79513539452f5a7641754f0a6b4657486f6b32712f523650594161326a645a397a696d3046714f502b6e6b5161454452624246426d4271547635664647666b32577341664b662f5247302f560a46642b5a654d353235315465547658483639356e6c53476175566c3941674d424141453d0a2d2d2d2d2d454e4420525341205055424c4943204b45592d2d2d2d2d0a' +} + +var ec = { + 'private': '2d2d2d2d2d424547494e2045432050524956415445204b45592d2d2d2d2d0a4d485143415145454944463658763853762f2f77475557442b6337383070704772553051645a5743417a78415150515838722f756f416347425375424241414b0a6f55514451674145495a656f7744796c6c73344b2f7766426a4f313862596f37674778386e595152696a6134652f71454d696b4f484a616937676565557265550a7235586b792f4178377332644774656773504e7350674765354d705176673d3d0a2d2d2d2d2d454e442045432050524956415445204b45592d2d2d2d2d0a', + 'public': '2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d465977454159484b6f5a497a6a3043415159464b34454541416f4451674145495a656f7744796c6c73344b2f7766426a4f313862596f37674778386e5951520a696a6134652f71454d696b4f484a616937676565557265557235586b792f4178377332644774656773504e7350674765354d705176673d3d0a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a' +} + +rsa.private = new Buffer(rsa.private, 'hex') +rsa.public = new Buffer(rsa.public, 'hex') +ec.private = new Buffer(ec.private, 'hex') +ec.public = new Buffer(ec.public, 'hex') + +function testit (keys, message, scheme) { + var pub = keys.public + var priv = keys.private + test(message.toString(), function (t) { + t.test('js sign and verify', function (t) { + t.plan(t) + var mySign = ourCrypto.createSign(scheme) + var mySig = mySign.update(message).sign(priv) + var myVer = ourCrypto.createVerify(scheme) + t.ok(myVer.update(message).verify(pub, mySig), 'validates') + }) + + t.test('node sign and verify', function (t) { + t.plan(t) + var mySign = nodeCrypto.createSign(scheme) + var mySig = mySign.update(message).sign(priv) + var myVer = nodeCrypto.createVerify(scheme) + t.ok(myVer.update(message).verify(pub, mySig), 'validates') + }) + + t.test('node sign and js verify', function (t) { + t.plan(t) + var mySign = nodeCrypto.createSign(scheme) + var mySig = mySign.update(message).sign(priv) + var myVer = ourCrypto.createVerify(scheme) + t.ok(myVer.update(message).verify(pub, mySig), 'validates') + }) + + t.test('js sign and node verify', function (t) { + t.plan(t) + var mySign = ourCrypto.createSign(scheme) + var mySig = mySign.update(message).sign(priv) + var myVer = nodeCrypto.createVerify(scheme) + t.ok(myVer.update(message).verify(pub, mySig), 'validates') + }) + }) +} + +testit(rsa, new Buffer('rsa with sha256'), 'RSA-SHA256') +testit(ec, new Buffer('ec with sha1'), 'ecdsa-with-SHA1') diff --git a/node_modules/meteor-node-stubs/node_modules/domain-browser/.eslintrc.js b/node_modules/meteor-node-stubs/node_modules/domain-browser/.eslintrc.js new file mode 100644 index 0000000..b623886 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/domain-browser/.eslintrc.js @@ -0,0 +1,701 @@ +// 2015 December 1 +// https://github.com/bevry/base +// http://eslint.org +/* eslint no-warning-comments: 0 */ +'use strict' + +const IGNORE = 0, WARN = 1, ERROR = 2, MAX_PARAMS = 4 + +module.exports = { + // parser: 'babel-eslint', + // ^ the bundled ESLINT parser is now actually quite good, and supports the ecmaFeatures property + ecmaFeatures: { + // this property only works with the bundled ESLINT parser, not babel-eslint + arrowFunctions: true, + binaryLiterals: true, + blockBindings: true, + classes: true, + defaultParams: true, + destructuring: true, + forOf: true, + generators: true, + modules: false, // Disabled due to https://twitter.com/balupton/status/671519915795345410 + objectLiteralComputedProperties: true, + objectLiteralDuplicateProperties: true, + objectLiteralShorthandMethods: true, + objectLiteralShorthandProperties: true, + octalLiterals: true, + regexUFlag: true, + regexYFlag: true, + restParams: true, + spread: true, + superInFunctions: true, + templateStrings: true, + unicodeCodePointEscapes: true, + globalReturn: true, + jsx: true, + experimentalObjectRestSpread: true + }, + env: { + browser: true, + node: true, + es6: true, + commonjs: true, + amd: true + }, + rules: { + // ---------------------------- + // Problems with these rules + // If we can figure out how to enable the following, that would be great + + // Two spaces after one line if or else: + // if ( blah ) return + // Insead of one space: + // if ( blah ) return + + // No spaces on embedded function: + // .forEach(function(key, value){ + // instead of: + // .forEach(function (key, value) { + + // Else and catch statements on the same line as closing brace: + // } else { + // } catch (e) { + // instead of: + // } + // else { + + + // -------------------------------------- + // Possible Errors + // The following rules point out areas where you might have made mistakes. + + // ES6 supports dangling commas + 'comma-dangle': IGNORE, + + // Don't allow assignments in conditional statements (if, while, etc.) + 'no-cond-assign': [ERROR, 'always'], + + // Warn but don't error about console statements + 'no-console': WARN, + + // Allow while(true) loops + 'no-constant-condition': IGNORE, + + // Seems like a good idea to error about this + 'no-control-regex': ERROR, + + // Warn but don't error about console statements + 'no-debugger': WARN, + + // Don't allow duplicate arguments in a function, they can cause errors + 'no-dupe-args': ERROR, + + // Disallow duplicate keys in an object, they can cause errors + 'no-dupe-keys': ERROR, + + // Disallow duplicate case statements in a switch + 'no-duplicate-case': ERROR, + + // Disallow empty [] in regular expressions as they cause unexpected behaviour + 'no-empty-character-class': ERROR, + + // Allow empty block statements, they are useful for clarity + 'no-empty': IGNORE, + + // Overwriting the exception argument in a catch statement can cause memory leaks in some browsers + 'no-ex-assign': ERROR, + + // Disallow superflous boolean casts, they offer no value + 'no-extra-boolean-cast': ERROR, + + // Allow superflous parenthesis as they offer clarity in some cases + 'no-extra-parens': IGNORE, + + // Disallow superflous semicolons, they offer no value + 'no-extra-semi': IGNORE, + + // Seems like a good idea to error about this + 'no-func-assign': ERROR, + + // Seems like a good idea to error about this + 'no-inner-declarations': ERROR, + + // Seems like a good idea to error about this + 'no-invalid-regexp': ERROR, + + // Seems like a good idea to error about this + 'no-irregular-whitespace': ERROR, + + // Seems like a good idea to error about this + 'no-negated-in-lhs': ERROR, + + // Seems like a good idea to error about this + 'no-obj-calls': ERROR, + + // Seems like a good idea to error about this + // Instead of / / used / {ERROR}/ instead + 'no-regex-spaces': ERROR, + + // Seems like a good idea to error about this + 'no-sparse-arrays': ERROR, + + // Seems like a good idea to error about this + 'no-unexpected-multiline': ERROR, + + // Seems like a good idea to error about this + 'no-unreachable': ERROR, + + // Seems like a good idea to error about this + 'use-isnan': ERROR, + + // We use YUIdoc, not JSDoc + 'valid-jsdoc': IGNORE, + + // Seems like a good idea to error about this + 'valid-typeof': ERROR, + + + // -------------------------------------- + // Best Practices + // These are rules designed to prevent you from making mistakes. They either prescribe a better way of doing something or help you avoid footguns. + + // Meh + 'accessor-pairs': IGNORE, + + // This rule seems buggy + 'block-scoped-var': IGNORE, + + // Disable complexity checks, they are annoying and not that useful in detecting actual complexity + 'complexity': IGNORE, + + // We use blank returns for break statements + 'consistent-return': IGNORE, + + // Always require curly braces unless the statement is all on a single line + 'curly': [ERROR, 'multi-line'], + + // If we don't have a default cause, it probably means we should throw an error + 'default-case': ERROR, + + // Dots should be on the newlines + // chainableThingy + // .doSomething() + // .doSomethingElse() + 'dot-location': [ERROR, 'property'], + + // Use dot notation where possible + 'dot-notation': ERROR, + + // Unless you are doing == null, then force === to avoid truthy/falsey mistakes + 'eqeqeq': [ERROR, 'allow-null'], + + // Always use hasOwnProperty when doing for in + 'guard-for-in': ERROR, + + // Warn about alert statements in our code + // Use one of the suggested alternatives instead + // Reasoning is they could be mistaken for left over debugging statements + 'no-alert': WARN, + + // They are very slow + 'no-caller': ERROR, + + // Wow... + 'no-case-declarations': ERROR, + + // Seems like a good idea to error about this + 'no-div-regex': ERROR, + + // Returns in else statements offer code clarity, so disable this rule + 'no-else-return': IGNORE, + + // Seems like a good idea to error about this + 'no-empty-label': ERROR, + + // Seems sensible + 'no-empty-pattern': ERROR, + + // We know that == null is a null and undefined check + 'no-eq-null': IGNORE, + + // Eval is slow and unsafe, use vm's instead + 'no-eval': ERROR, + + // There is never a good reason for this + 'no-extend-native': ERROR, + + // Don't allow useless binds + 'no-extra-bind': ERROR, + + // Don't allow switch case statements to follow through, use continue keyword instead + 'no-fallthrough': ERROR, + + // Use zero when doing decimals, otherwise it is confusing + 'no-floating-decimal': ERROR, + + // Cleverness is unclear + 'no-implicit-coercion': ERROR, + + // A sneaky way to do evals + 'no-implied-eval': ERROR, + + // This throws for a lot of senseless things, like chainy functions + 'no-invalid-this': IGNORE, + + // Use proper iterators instead + 'no-iterator': ERROR, + + // We never use this, it seems silly to allow this + 'no-labels': ERROR, + + // We never use this, it seems silly to allow this + 'no-lone-blocks': ERROR, + + // Loop functions always cause problems, as the scope isn't clear through iterations + 'no-loop-func': ERROR, + + // This is a great idea + // Although ignore -1 and 0 as it is common with indexOf + 'no-magic-numbers': [WARN, { ignore: [-1, 0] }], + + // We like multi spaces for clarity + // E.g. We like + // if ( blah ) return foo + // Instead of: + // if ( blah ) return foo + // @TODO would be great to enforce the above + 'no-multi-spaces': IGNORE, + + // Use ES6 template strings instead + 'no-multi-str': ERROR, + + // Would be silly to allow this + 'no-native-reassign': ERROR, + + // We never use this, it seems silly to allow this + 'no-new-func': ERROR, + + // We never use this, it seems silly to allow this + 'no-new-wrappers': ERROR, + + // We never use this, it seems silly to allow this + 'no-new': ERROR, + + // We never use this, it seems silly to allow this + 'no-octal-escape': ERROR, + + // We never use this, it seems silly to allow this + 'no-octal': ERROR, + + // We got to be pretty silly if we don't realise we are doing this + // As such, take any usage as intentional and aware + 'no-param-reassign': IGNORE, + + // We use process.env wisely + 'no-process-env': IGNORE, + + // We never use this, it seems silly to allow this + 'no-proto': ERROR, + + // We never use this, it seems silly to allow this + 'no-redeclare': ERROR, + + // We never use this, it seems silly to allow this + 'no-return-assign': ERROR, + + // We never use this, it seems silly to allow this + 'no-script-url': ERROR, + + // We never use this, it seems silly to allow this + 'no-self-compare': ERROR, + + // We never use this, it seems silly to allow this + 'no-sequences': ERROR, + + // We always want proper error objects as they have stack traces and respond to instanceof Error checks + 'no-throw-literal': ERROR, + + // We never use this, it seems silly to allow this + 'no-unused-expressions': ERROR, + + // Seems sensible + 'no-useless-call': ERROR, + + // Seems sensible + 'no-useless-concat': ERROR, + + // We never use this, it seems silly to allow this + 'no-void': ERROR, + + // Warn about todos + 'no-warning-comments': [WARN, { terms: ['todo', 'fixme'], location: 'anywhere' }], + + // We never use this, it seems silly to allow this + 'no-with': ERROR, + + // Always specify a radix to avoid errors + 'radix': ERROR, + + // We appreciate the clarity late defines offer + 'vars-on-top': IGNORE, + + // Wrap instant called functions in parenthesis for clearer intent + 'wrap-iife': ERROR, + + // Because we force === and never allow assignments in conditions + // we have no need for yoda statements, so disable them + 'yoda': [ERROR, 'never'], + + + // -------------------------------------- + // Strict Mode + // These rules relate to using strict mode. + + // Ensure that use strict is specified to prevent the runtime erorr: + // SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode + 'strict': [ERROR, 'global'], + + + // -------------------------------------- + // Variables + // These rules have to do with variable declarations. + + // We don't care + 'init-declaration': IGNORE, + + // Don't allow the catch method to shadow objects as browsers handle this differently + // Update: We don't care for IE8 + 'no-catch-shadow': IGNORE, + + // Don't use delete, it disables optimisations + 'no-delete-var': ERROR, + + // We never use this, it seems silly to allow this + 'no-label-var': ERROR, + + // We never use this, it seems silly to allow this + 'no-shadow-restricted-names': ERROR, + + // We use shadowing + 'no-shadow': IGNORE, + + // Makes sense + 'no-undef-init': ERROR, + + // Error when an undefined variable is used + 'no-undef': ERROR, + + // typeof blah === 'undefined' should always be used + 'no-undefined': ERROR, + + // Warn us when we don't use something + 'no-unused-vars': WARN, + + // Error when we try and use something before it is defined + 'no-use-before-define': ERROR, + + + // -------------------------------------- + // Node.js and CommonJS + // These rules are specific to JavaScript running on Node.js or using CommonJS in the browser. + + // Seems to difficult to enforce + 'callback-return': IGNORE, + + // We use require where it is appropriate to use it + 'global-require': IGNORE, + + // Force handling of callback errors + 'handle-callback-err': ERROR, + + // @TODO decide if this is good or not + 'no-mixed-requires': ERROR, + + // Disallow error prone syntax + 'no-new-require': ERROR, + + // Always use path.join for windows support + 'no-path-concat': ERROR, + + // We know what we are doing + 'no-process-exit': IGNORE, + + // No need to disallow any modules + 'no-restricted-modules': IGNORE, + + // Sometimes sync methods are useful, so warn but don't error + 'no-sync': WARN, + + + // -------------------------------------- + // Stylistic + // These rules are purely matters of style and are quite subjective. + + // We don't use spaces with brackets + 'array-bracket-spacing': [ERROR, 'never'], + + // Disallow or enforce spaces inside of single line blocks + 'block-spacing': [ERROR, 'always'], + + // Opening brace on same line, closing brace on its own line, except when statement is a single line + 'brace-style': [ERROR, 'stroustrup', { allowSingleLine: true }], + + // Use camel case + 'camelcase': ERROR, + + // Require a comma after always + 'comma-spacing': [ERROR, { before: false, after: true }], + + // Commas go last, we have tooling to detect if we forget a comma + 'comma-style': [ERROR, 'last'], + + // Require or disallow padding inside computed properties + 'computed-property-spacing': [ERROR, 'never'], + + // Enabling this was incredibly annoying when doing layers of nesting + 'consistent-this': IGNORE, + + // Enable to make UNIX people's lives easier + 'eol-last': ERROR, + + // We like anonymous functions + 'func-names': IGNORE, + + // Prefer to define functions via variables + 'func-style': [WARN, 'declaration'], + + // Sometimes short names are appropriate + 'id-length': IGNORE, + + // Camel case handles this for us + 'id-match': IGNORE, + + // Use tabs and indent case blocks + 'indent': [ERROR, 'tab', { SwitchCase: WARN }], + + // Prefer double qoutes for JSX properties: , + 'jsx-quotes': [ERROR, 'prefer-double'], + + // Space after the colon + 'key-spacing': [ERROR, { + beforeColon: false, + afterColon: true + }], + + // Enforce unix line breaks + 'linebreak-style': [ERROR, 'unix'], + + // Enforce new lines before block comments + 'lines-around-comment': [ERROR, { beforeBlockComment: true, allowBlockStart: true }], + + // Disabled to ensure consistency with complexity option + 'max-depth': IGNORE, + + // We use soft wrap + 'max-len': IGNORE, + + // We are smart enough to know if this is bad or not + 'max-nested-callbacks': IGNORE, + + // Sometimes we have no control over this for compat reasons, so just warn + 'max-params': [WARN, MAX_PARAMS], + + // We should be able to use whatever feels right + 'max-statements': IGNORE, + + // Constructors should be CamelCase + 'new-cap': ERROR, + + // Always use parens when instantiating a class + 'new-parens': ERROR, + + // Too difficult to enforce correctly as too many edge-cases + 'newline-after-var': IGNORE, + + // Don't use the array constructor when it is not needed + 'no-array-constructor': ERROR, + + // We never use bitwise, they are too clever + 'no-bitwise': ERROR, + + // We use continue + 'no-continue': IGNORE, + + // We like inline comments + 'no-inline-comments': IGNORE, + + // The code could be optimised if this error occurs + 'no-lonely-if': ERROR, + + // Don't mix spaces and tabs + // @TODO maybe [ERROR, 'smart-tabs'] will be better, we will see + 'no-mixed-spaces-and-tabs': ERROR, + + // We use multiple empty lines for styling + 'no-multiple-empty-lines': IGNORE, + + // Sometimes it is more understandable with a negated condition + 'no-negated-condition': IGNORE, + + // Sometimes these are useful + 'no-nested-ternary': IGNORE, + + // Use {} instead of new Object() + 'no-new-object': ERROR, + + // We use plus plus + 'no-plusplus': IGNORE, + + // Handled by other rules + 'no-restricted-syntax': IGNORE, + + // We never use this, it seems silly to allow this + 'no-spaced-func': ERROR, + + // Sometimes ternaries are useful + 'no-ternary': IGNORE, + + // Disallow trailing spaces + 'no-trailing-spaces': ERROR, + + // Sometimes this is useful when avoiding shadowing + 'no-underscore-dangle': IGNORE, + + // Sensible + 'no-unneeded-ternary': ERROR, + + // Desirable, but too many edge cases it turns out where it is actually preferred + 'object-curly-spacing': IGNORE, // [ERROR, 'always'], + + // We like multiple var statements + 'one-var': IGNORE, + + // Force use of shorthands when available + 'operator-assignment': [ERROR, 'always'], + + // Should be before, but not with =, *=, /=, += lines + // @TODO figure out how to enforce + 'operator-linebreak': IGNORE, + + // This rule doesn't appear to work correclty + 'padded-blocks': IGNORE, + + // Seems like a good idea to error about this + 'quote-props': [ERROR, 'consistent-as-needed'], + + // Use single quotes where escaping isn't needed + 'quotes': [ERROR, 'single', 'avoid-escape'], + + // We use YUIdoc + 'require-jsdoc': IGNORE, + + // If semi's are used, then add spacing after + 'semi-spacing': [ERROR, { before: false, after: true }], + + // Never use semicolons + 'semi': [ERROR, 'never'], + + // We don't care if our vars are alphabetical + 'sort-vars': IGNORE, + + // Always force a space after a keyword + 'space-after-keywords': [ERROR, 'always'], + + // Always force a space before a { + 'space-before-blocks': [ERROR, 'always'], + + // function () {, get blah () { + 'space-before-function-paren': [ERROR, 'always'], + + // We do this + 'space-before-keywords': [ERROR, 'always'], + + // This is for spacing between [], so [ WARN, ERROR, 3 ] which we don't want + 'space-in-brackets': IGNORE, + + // This is for spacing between (), so doSomething( WARN, ERROR, 3 ) or if ( WARN === 3 ) + // which we want for ifs, but don't want for calls + 'space-in-parens': IGNORE, + + // We use this + 'space-infix-ops': ERROR, + + // We use this + 'space-return-throw-case': ERROR, + + // We use this + 'space-unary-ops': ERROR, + + // We use this + // 'spaced-line-comment': ERROR, + 'spaced-comment': ERROR, + + // We use this + // @TODO revise this + 'wrap-regex': ERROR, + + + // -------------------------------------- + // ECMAScript 6 + + // Sensible to create more informed and clear code + 'arrow-body-style': [ERROR, 'as-needed'], + + // We do this, no reason why, just what we do + 'arrow-parens': [ERROR, 'always'], + + // Require consistent spacing for arrow functions + 'arrow-spacing': ERROR, + + // Makes sense as otherwise runtime error will occur + 'constructor-super': ERROR, + + // Seems the most consistent location for it + 'generator-star-spacing': [ERROR, 'before'], + + // Seems sensible + 'no-arrow-condition': ERROR, + + // Seems sensible + 'no-class-assign': ERROR, + + // Makes sense as otherwise runtime error will occur + 'no-const-assign': ERROR, + + // Makes sense as otherwise runtime error will occur + 'no-dupe-class-members': ERROR, + + // Makes sense as otherwise runtime error will occur + 'no-this-before-super': ERROR, + + // @TODO This probably should be an error + // however it is useful for: for ( var key in obj ) { + // which hopefully is more performant than let (@TODO check if it actually is more performant) + 'no-var': WARN, + + // Enforce ES6 object shorthand + 'object-shorthand': ERROR, + + // Better performance when running native + // but horrible performance if not running native as could fallback to bind + // https://travis-ci.org/bevry/es6-benchmarks + 'prefer-arrow-callback': IGNORE, + + // Sure, why not + 'prefer-const': WARN, + + // Controversial change, but makes sense to move towards to reduce the risk of bad people overwriting apply and call + // https://github.com/eslint/eslint/issues/ERROR939 + 'prefer-reflect': WARN, + + // Sure, why not + 'prefer-spread': ERROR, + + // Too annoying to enforce + 'prefer-template': IGNORE, + + // Makes sense + 'require-yield': ERROR + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/domain-browser/.npmignore b/node_modules/meteor-node-stubs/node_modules/domain-browser/.npmignore new file mode 100644 index 0000000..27859c1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/domain-browser/.npmignore @@ -0,0 +1,44 @@ +# 2015 September 18 +# https://github.com/bevry/base + +# Temp Files +**/.docpad.db +**/out.* +**/*.log +**/*.cpuprofile +**/*.heapsnapshot + +# Build Files +build/ +components/ +bower_components/ +node_modules/ + +# Private Files +.env + +# Development Files +.editorconfig +.eslintrc +.jshintrc +.jscrc +coffeelint.json +.travis* +nakefile.js +Cakefile +Makefile +BACKERS.md +CONTRIBUTING.md +HISTORY.md +**/src/ +**/test/ + +# Other Package Definitions +template.js +component.json +bower.json + +# ===================================== +# CUSTOM MODIFICATIONS + +# None diff --git a/node_modules/meteor-node-stubs/node_modules/domain-browser/HISTORY.md b/node_modules/meteor-node-stubs/node_modules/domain-browser/HISTORY.md new file mode 100644 index 0000000..758a44f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/domain-browser/HISTORY.md @@ -0,0 +1,42 @@ +# History + +## v1.1.7 2015 December 12 +- Revert minimum node version from 0.12 back to 0.4 + - Thanks to [Alexander Sorokin](https://github.com/syrnick) for [this comment](https://github.com/bevry/domain-browser/commit/c66ee3445e87955e70d0d60d4515f2d26a81b9c4#commitcomment-14938325) + +## v1.1.6 2015 December 12 +- Fixed `assert-helpers` sneaking into `dependencies` + - Thanks to [Bogdan Chadkin](https://github.com/TrySound) for [Pull Request #8](https://github.com/bevry/domain-browser/pull/8) + +## v1.1.5 2015 December 9 +- Updated internal conventions +- Added better jspm support + - Thanks to [Guy Bedford](https://github.com/guybedford) for [Pull Request #7](https://github.com/bevry/domain-browser/pull/7) + +## v1.1.4 2015 February 3 +- Added + - `domain.enter()` + - `domain.exit()` + - `domain.bind()` + - `domain.intercept()` + +## v1.1.3 2014 October 10 +- Added + - `domain.add()` + - `domain.remove()` + +## v1.1.2 2014 June 8 +- Added `domain.createDomain()` alias + - Thanks to [James Halliday](https://github.com/substack) for [Pull Request #1](https://github.com/bevry/domain-browser/pull/1) + +## v1.1.1 2013 December 27 +- Fixed `domain.create()` not returning anything + +## v1.1.0 2013 November 1 +- Dropped component.io and bower support, just use ender or browserify + +## v1.0.1 2013 September 18 +- Now called `domain-browser` everywhere + +## v1.0.0 2013 September 18 +- Initial release diff --git a/node_modules/meteor-node-stubs/node_modules/domain-browser/LICENSE.md b/node_modules/meteor-node-stubs/node_modules/domain-browser/LICENSE.md new file mode 100644 index 0000000..08d8802 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/domain-browser/LICENSE.md @@ -0,0 +1,23 @@ + + +

License

+ +Unless stated otherwise all works are: + +
+ +and licensed under: + + + +

MIT License

+ +
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+ + diff --git a/node_modules/meteor-node-stubs/node_modules/domain-browser/README.md b/node_modules/meteor-node-stubs/node_modules/domain-browser/README.md new file mode 100644 index 0000000..43502ef --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/domain-browser/README.md @@ -0,0 +1,111 @@ + + +

domain-browser

+ + + + + + +Travis CI Build Status +NPM version +NPM downloads +Dependency Status +Dev Dependency Status +
+Slack community badge +Patreon donate button +Gratipay donate button +Flattr donate button +PayPal donate button +Bitcoin donate button +Wishlist browse button + + + + + + +Node's domain module for the web browser. This is merely an evented try...catch with the same API as node, nothing more. + + + + + + +

Install

+ +

NPM

    +
  • Install: npm install --save domain-browser
  • +
  • Use: require('domain-browser')
+ +

Browserify

    +
  • Install: npm install --save domain-browser
  • +
  • Use: require('domain-browser')
  • +
  • CDN URL: //wzrd.in/bundle/domain-browser@1.1.7
+ +

Ender

    +
  • Install: ender add domain-browser
  • +
  • Use: require('domain-browser')
+ + + + + + +

History

+ +Discover the release history by heading on over to the HISTORY.md file. + + + + + + +

Backers

+ +

Maintainers

+ +These amazing people are maintaining this project: + + + +

Sponsors

+ +No sponsors yet! Will you be the first? + +Patreon donate button +Gratipay donate button +Flattr donate button +PayPal donate button +Bitcoin donate button +Wishlist browse button + +

Contributors

+ +These amazing people have contributed code to this project: + + + +Discover how you can contribute by heading on over to the CONTRIBUTING.md file. + + + + + + +

License

+ +Unless stated otherwise all works are: + + + +and licensed under: + + + + diff --git a/node_modules/meteor-node-stubs/node_modules/domain-browser/index.js b/node_modules/meteor-node-stubs/node_modules/domain-browser/index.js new file mode 100644 index 0000000..f6cd7f7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/domain-browser/index.js @@ -0,0 +1,69 @@ +// This file should be ES5 compatible +/* eslint prefer-spread:0, no-var:0, prefer-reflect:0, no-magic-numbers:0 */ +'use strict' +module.exports = (function () { + // Import Events + var events = require('events') + + // Export Domain + var domain = {} + domain.createDomain = domain.create = function () { + var d = new events.EventEmitter() + + function emitError (e) { + d.emit('error', e) + } + + d.add = function (emitter) { + emitter.on('error', emitError) + } + d.remove = function (emitter) { + emitter.removeListener('error', emitError) + } + d.bind = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments) + try { + fn.apply(null, args) + } + catch (err) { + emitError(err) + } + } + } + d.intercept = function (fn) { + return function (err) { + if ( err ) { + emitError(err) + } + else { + var args = Array.prototype.slice.call(arguments, 1) + try { + fn.apply(null, args) + } + catch (err) { + emitError(err) + } + } + } + } + d.run = function (fn) { + try { + fn() + } + catch (err) { + emitError(err) + } + return this + } + d.dispose = function () { + this.removeAllListeners() + return this + } + d.enter = d.exit = function () { + return this + } + return d + } + return domain +}).call(this) diff --git a/node_modules/meteor-node-stubs/node_modules/domain-browser/package.json b/node_modules/meteor-node-stubs/node_modules/domain-browser/package.json new file mode 100644 index 0000000..49f0135 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/domain-browser/package.json @@ -0,0 +1,130 @@ +{ + "name": "domain-browser", + "version": "1.1.7", + "description": "Node's domain module for the web browser. This is merely an evented try...catch with the same API as node, nothing more.", + "homepage": "https://github.com/bevry/domain-browser", + "license": "MIT", + "badges": { + "list": [ + "travisci", + "npmversion", + "npmdownloads", + "daviddm", + "daviddmdev", + "---", + "slackin", + "patreon", + "gratipay", + "flattr", + "paypal", + "bitcoin", + "wishlist" + ], + "config": { + "patreonUsername": "bevry", + "gratipayUsername": "bevry", + "flattrCode": "344188/balupton-on-Flattr", + "paypalButtonID": "QB8GQPZAH84N6", + "bitcoinURL": "https://bevry.me/bitcoin", + "wishlistURL": "https://bevry.me/wishlist", + "slackinURL": "https://slack.bevry.me" + } + }, + "keywords": [ + "domain", + "trycatch", + "try", + "catch", + "node-compat", + "ender.js", + "component", + "component.io", + "umd", + "amd", + "require.js", + "browser" + ], + "author": { + "name": "2013+ Bevry Pty Ltd", + "email": "us@bevry.me", + "url": "http://bevry.me" + }, + "maintainers": [ + { + "name": "Benjamin Lupton", + "email": "b@lupton.cc", + "url": "http://balupton.com" + } + ], + "contributors": [ + { + "name": "Benjamin Lupton", + "email": "b@lupton.cc", + "url": "http://balupton.com" + }, + { + "name": "Evan Solomon", + "url": "http://evansolomon.me" + }, + { + "name": "James Halliday", + "email": "substack@gmail.com", + "url": "http://substack.net/" + }, + { + "name": "Guy Bedford", + "email": "guybedford@gmail.com", + "url": "twitter.com/guybedford" + }, + { + "name": "Bogdan Chadkin", + "email": "trysound@yandex.ru", + "url": "https://github.com/TrySound" + } + ], + "bugs": { + "url": "https://github.com/bevry/domain-browser/issues" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/bevry/domain-browser.git" + }, + "engines": { + "node": ">=0.4", + "npm": ">=1.2" + }, + "browsers": true, + "main": "./index.js", + "jspm": { + "map": { + "./index.js": { + "node": "@node/domain" + } + } + }, + "dependencies": {}, + "devDependencies": { + "assert-helpers": "^4.1.0", + "eslint": "^1.10.3", + "joe": "^1.6.0", + "joe-reporter-console": "^1.2.1", + "projectz": "^1.0.8" + }, + "scripts": { + "clean": "node --harmony nakefile.js clean", + "setup": "node --harmony nakefile.js setup", + "compile": "node --harmony nakefile.js compile", + "watch": "node --harmony nakefile.js watch", + "verify": "node --harmony nakefile.js verify", + "meta": "node --harmony nakefile.js meta", + "prepare": "node --harmony nakefile.js prepare", + "release": "node --harmony nakefile.js release", + "test": "node --harmony ./test.js" + }, + "readme": "\n\n

domain-browser

\n\n\n\n\n\n\n\"Travis\n\"NPM\n\"NPM\n\"Dependency\n\"Dev\n
\n\"Slack\n\"Patreon\n\"Gratipay\n\"Flattr\n\"PayPal\n\"Bitcoin\n\"Wishlist\n\n\n\n\n\n\nNode's domain module for the web browser. This is merely an evented try...catch with the same API as node, nothing more.\n\n\n\n\n\n\n

Install

\n\n

NPM

    \n
  • Install: npm install --save domain-browser
  • \n
  • Use: require('domain-browser')
\n\n

Browserify

    \n
  • Install: npm install --save domain-browser
  • \n
  • Use: require('domain-browser')
  • \n
  • CDN URL: //wzrd.in/bundle/domain-browser@1.1.7
\n\n

Ender

    \n
  • Install: ender add domain-browser
  • \n
  • Use: require('domain-browser')
\n\n\n\n\n\n\n

History

\n\nDiscover the release history by heading on over to the HISTORY.md file.\n\n\n\n\n\n\n

Backers

\n\n

Maintainers

\n\nThese amazing people are maintaining this project:\n\n\n\n

Sponsors

\n\nNo sponsors yet! Will you be the first?\n\n\"Patreon\n\"Gratipay\n\"Flattr\n\"PayPal\n\"Bitcoin\n\"Wishlist\n\n

Contributors

\n\nThese amazing people have contributed code to this project:\n\n\n\nDiscover how you can contribute by heading on over to the CONTRIBUTING.md file.\n\n\n\n\n\n\n

License

\n\nUnless stated otherwise all works are:\n\n\n\nand licensed under:\n\n\n\n\n", + "readmeFilename": "README.md", + "_id": "domain-browser@1.1.7", + "_shasum": "867aa4b093faa05f1de08c06f4d7b21fdf8698bc", + "_resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.1.7.tgz", + "_from": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.1.7.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/domain-browser/test.js b/node_modules/meteor-node-stubs/node_modules/domain-browser/test.js new file mode 100644 index 0000000..70efcfc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/domain-browser/test.js @@ -0,0 +1,100 @@ +/* eslint handle-callback-err:0, no-magic-numbers:0, no-unused-vars:0 */ +'use strict' + +// Import +const events = require('events') +const equal = require('assert-helpers').equal +const joe = require('joe') +const domain = require('./') + +// ===================================== +// Tests + +joe.describe('domain-browser', function (describe, it) { + it('should work on throws', function (done) { + const d = domain.create() + d.on('error', function (err) { + equal(err && err.message, 'a thrown error', 'error message') + done() + }) + d.run(function () { + throw new Error('a thrown error') + }) + }) + + it('should be able to add emitters', function (done) { + const d = domain.create() + const emitter = new events.EventEmitter() + + d.add(emitter) + d.on('error', function (err) { + equal(err && err.message, 'an emitted error', 'error message') + done() + }) + + emitter.emit('error', new Error('an emitted error')) + }) + + it('should be able to remove emitters', function (done) { + const emitter = new events.EventEmitter() + const d = domain.create() + let domainGotError = false + + d.add(emitter) + d.on('error', function (err) { + domainGotError = true + }) + + emitter.on('error', function (err) { + equal(err && err.message, 'This error should not go to the domain', 'error message') + + // Make sure nothing race condition-y is happening + setTimeout(function () { + equal(domainGotError, false, 'no domain error') + done() + }, 0) + }) + + d.remove(emitter) + emitter.emit('error', new Error('This error should not go to the domain')) + }) + + it('bind should work', function (done) { + const d = domain.create() + d.on('error', function (err) { + equal(err && err.message, 'a thrown error', 'error message') + done() + }) + d.bind(function (err, a, b) { + equal(err && err.message, 'a passed error', 'error message') + equal(a, 2, 'value of a') + equal(b, 3, 'value of b') + throw new Error('a thrown error') + })(new Error('a passed error'), 2, 3) + }) + + it('intercept should work', function (done) { + const d = domain.create() + let count = 0 + d.on('error', function (err) { + if ( count === 0 ) { + equal(err && err.message, 'a thrown error', 'error message') + } + else if ( count === 1 ) { + equal(err && err.message, 'a passed error', 'error message') + done() + } + count++ + }) + + d.intercept(function (a, b) { + equal(a, 2, 'value of a') + equal(b, 3, 'value of b') + throw new Error('a thrown error') + })(null, 2, 3) + + d.intercept(function (a, b) { + throw new Error('should never reach here') + })(new Error('a passed error'), 2, 3) + }) +}) diff --git a/node_modules/meteor-node-stubs/node_modules/events/.npmignore b/node_modules/meteor-node-stubs/node_modules/events/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/events/.travis.yml b/node_modules/meteor-node-stubs/node_modules/events/.travis.yml new file mode 100644 index 0000000..e716bc0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: +- '0.10' +env: + global: + - secure: XcBiD8yReflut9q7leKsigDZ0mI3qTKH+QrNVY8DaqlomJOZw8aOrVuX9Jz12l86ZJ41nbxmKnRNkFzcVr9mbP9YaeTb3DpeOBWmvaoSfud9Wnc16VfXtc1FCcwDhSVcSiM3UtnrmFU5cH+Dw1LPh5PbfylYOS/nJxUvG0FFLqI= + - secure: jNWtEbqhUdQ0xXDHvCYfUbKYeJCi6a7B4LsrcxYCyWWn4NIgncE5x2YbB+FSUUFVYfz0dsn5RKP1oHB99f0laUEo18HBNkrAS/rtyOdVzcpJjbQ6kgSILGjnJD/Ty1B57Rcz3iyev5Y7bLZ6Y1FbDnk/i9/l0faOGz8vTC3Vdkc= diff --git a/node_modules/meteor-node-stubs/node_modules/events/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/events/.zuul.yml new file mode 100644 index 0000000..a8e35af --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/.zuul.yml @@ -0,0 +1,12 @@ +ui: mocha-qunit +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: 5..latest + - name: iphone + version: latest + - name: ie + version: 8..latest diff --git a/node_modules/meteor-node-stubs/node_modules/events/History.md b/node_modules/meteor-node-stubs/node_modules/events/History.md new file mode 100644 index 0000000..79661a0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/History.md @@ -0,0 +1,38 @@ +# 1.1.0 (2015-09-29) + + - add Emitter#listerCount (to match node v4 api) + +# 1.0.2 (2014-08-28) + + - remove un-reachable code + - update devDeps + +## 1.0.1 / 2014-05-11 + + - check for console.trace before using it + +## 1.0.0 / 2013-12-10 + + - Update to latest events code from node.js 0.10 + - copy tests from node.js + +## 0.4.0 / 2011-07-03 ## + + - Switching to graphquire@0.8.0 + +## 0.3.0 / 2011-07-03 ## + + - Switching to URL based module require. + +## 0.2.0 / 2011-06-10 ## + + - Simplified package structure. + - Graphquire for dependency management. + +## 0.1.1 / 2011-05-16 ## + + - Unhandled errors are logged via console.error + +## 0.1.0 / 2011-04-22 ## + + - Initial release diff --git a/node_modules/meteor-node-stubs/node_modules/events/LICENSE b/node_modules/meteor-node-stubs/node_modules/events/LICENSE new file mode 100644 index 0000000..52ed3b0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/LICENSE @@ -0,0 +1,22 @@ +MIT + +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/events/Readme.md b/node_modules/meteor-node-stubs/node_modules/events/Readme.md new file mode 100644 index 0000000..02694ef --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/Readme.md @@ -0,0 +1,19 @@ +# events [![Build Status](https://travis-ci.org/Gozala/events.png?branch=master)](https://travis-ci.org/Gozala/events) + +Node's event emitter for all engines. + +## Install ## + +``` +npm install events +``` + +## Require ## + +```javascript +var EventEmitter = require('events').EventEmitter +``` + +## Usage ## + +See the [node.js event emitter docs](http://nodejs.org/api/events.html) diff --git a/node_modules/meteor-node-stubs/node_modules/events/events.js b/node_modules/meteor-node-stubs/node_modules/events/events.js new file mode 100644 index 0000000..27346eb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/events.js @@ -0,0 +1,298 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} diff --git a/node_modules/meteor-node-stubs/node_modules/events/package.json b/node_modules/meteor-node-stubs/node_modules/events/package.json new file mode 100644 index 0000000..11b85b8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/package.json @@ -0,0 +1,44 @@ +{ + "name": "events", + "id": "events", + "version": "1.1.0", + "description": "Node's event emitter for all engines.", + "keywords": [ + "events", + "eventEmitter", + "eventDispatcher", + "listeners" + ], + "author": { + "name": "Irakli Gozalishvili", + "email": "rfobic@gmail.com", + "url": "http://jeditoolkit.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Gozala/events.git", + "web": "https://github.com/Gozala/events" + }, + "bugs": { + "url": "http://github.com/Gozala/events/issues/" + }, + "main": "./events.js", + "engines": { + "node": ">=0.4.x" + }, + "devDependencies": { + "mocha": "~1.21.4", + "zuul": "~1.10.2" + }, + "scripts": { + "test": "mocha --ui qunit -- tests/index.js && zuul -- tests/index.js" + }, + "license": "MIT", + "readme": "# events [![Build Status](https://travis-ci.org/Gozala/events.png?branch=master)](https://travis-ci.org/Gozala/events)\n\nNode's event emitter for all engines.\n\n## Install ##\n\n```\nnpm install events\n```\n\n## Require ##\n\n```javascript\nvar EventEmitter = require('events').EventEmitter\n```\n\n## Usage ##\n\nSee the [node.js event emitter docs](http://nodejs.org/api/events.html)\n", + "readmeFilename": "Readme.md", + "homepage": "https://github.com/Gozala/events#readme", + "_id": "events@1.1.0", + "_shasum": "4b389fc200f910742ebff3abb2efe33690f45429", + "_resolved": "https://registry.npmjs.org/events/-/events-1.1.0.tgz", + "_from": "https://registry.npmjs.org/events/-/events-1.1.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/events/tests/add-listeners.js b/node_modules/meteor-node-stubs/node_modules/events/tests/add-listeners.js new file mode 100644 index 0000000..5ab874c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/tests/add-listeners.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var events = require('../'); + +var e = new events.EventEmitter(); + +var events_new_listener_emited = []; +var listeners_new_listener_emited = []; +var times_hello_emited = 0; + +// sanity check +assert.equal(e.addListener, e.on); + +e.on('newListener', function(event, listener) { + console.log('newListener: ' + event); + events_new_listener_emited.push(event); + listeners_new_listener_emited.push(listener); +}); + +function hello(a, b) { + console.log('hello'); + times_hello_emited += 1; + assert.equal('a', a); + assert.equal('b', b); +} +e.on('hello', hello); + +var foo = function() {}; +e.once('foo', foo); + +console.log('start'); + +e.emit('hello', 'a', 'b'); + + +// just make sure that this doesn't throw: +var f = new events.EventEmitter(); +f.setMaxListeners(0); + +assert.deepEqual(['hello', 'foo'], events_new_listener_emited); +assert.deepEqual([hello, foo], listeners_new_listener_emited); +assert.equal(1, times_hello_emited); + diff --git a/node_modules/meteor-node-stubs/node_modules/events/tests/check-listener-leaks.js b/node_modules/meteor-node-stubs/node_modules/events/tests/check-listener-leaks.js new file mode 100644 index 0000000..e07866a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/tests/check-listener-leaks.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var events = require('../'); + +var e = new events.EventEmitter(); + +// default +for (var i = 0; i < 10; i++) { + e.on('default', function() {}); +} +assert.ok(!e._events['default'].hasOwnProperty('warned')); +e.on('default', function() {}); +assert.ok(e._events['default'].warned); + +// specific +e.setMaxListeners(5); +for (var i = 0; i < 5; i++) { + e.on('specific', function() {}); +} +assert.ok(!e._events['specific'].hasOwnProperty('warned')); +e.on('specific', function() {}); +assert.ok(e._events['specific'].warned); + +// only one +e.setMaxListeners(1); +e.on('only one', function() {}); +assert.ok(!e._events['only one'].hasOwnProperty('warned')); +e.on('only one', function() {}); +assert.ok(e._events['only one'].hasOwnProperty('warned')); + +// unlimited +e.setMaxListeners(0); +for (var i = 0; i < 1000; i++) { + e.on('unlimited', function() {}); +} +assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); + +// process-wide +events.EventEmitter.defaultMaxListeners = 42; +e = new events.EventEmitter(); + +for (var i = 0; i < 42; ++i) { + e.on('fortytwo', function() {}); +} +assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); +e.on('fortytwo', function() {}); +assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); +delete e._events['fortytwo'].warned; + +events.EventEmitter.defaultMaxListeners = 44; +e.on('fortytwo', function() {}); +assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); +e.on('fortytwo', function() {}); +assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); + +// but _maxListeners still has precedence over defaultMaxListeners +events.EventEmitter.defaultMaxListeners = 42; +e = new events.EventEmitter(); +e.setMaxListeners(1); +e.on('uno', function() {}); +assert.ok(!e._events['uno'].hasOwnProperty('warned')); +e.on('uno', function() {}); +assert.ok(e._events['uno'].hasOwnProperty('warned')); + +// chainable +assert.strictEqual(e, e.setMaxListeners(1)); diff --git a/node_modules/meteor-node-stubs/node_modules/events/tests/common.js b/node_modules/meteor-node-stubs/node_modules/events/tests/common.js new file mode 100644 index 0000000..66f70a3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/tests/common.js @@ -0,0 +1,42 @@ +var assert = require('assert'); + +var mustCallChecks = []; + +function runCallChecks() { + var failed_count = 0; + for (var i=0 ; i< mustCallChecks.length; ++i) { + var context = mustCallChecks[i]; + if (context.actual === context.expected) { + continue; + } + + failed_count++; + console.log('Mismatched %s function calls. Expected %d, actual %d.', + context.name, + context.expected, + context.actual); + console.log(context.stack.split('\n').slice(2).join('\n')); + } + + assert(failed_count === 0); +} + +after(runCallChecks); + +exports.mustCall = function(fn, expected) { + if (typeof expected !== 'number') expected = 1; + + var context = { + expected: expected, + actual: 0, + stack: (new Error).stack, + name: fn.name || '' + }; + + mustCallChecks.push(context); + + return function() { + context.actual++; + return fn.apply(this, arguments); + }; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/events/tests/index.js b/node_modules/meteor-node-stubs/node_modules/events/tests/index.js new file mode 100644 index 0000000..f144530 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/tests/index.js @@ -0,0 +1,25 @@ + +require('./legacy-compat'); + +// we do this to easily wrap each file in a mocha test +// and also have browserify be able to statically analyze this file +var orig_require = require; +var require = function(file) { + test(file, function() { + orig_require(file); + }); +} + +require('./add-listeners.js'); +require('./check-listener-leaks.js'); +require('./listener-count.js'); +require('./listeners-side-effects.js'); +require('./listeners.js'); +require('./max-listeners.js'); +require('./modify-in-emit.js'); +require('./num-args.js'); +require('./once.js'); +require('./set-max-listeners-side-effects.js'); +require('./subclass.js'); +require('./remove-all-listeners.js'); +require('./remove-listeners.js'); diff --git a/node_modules/meteor-node-stubs/node_modules/events/tests/legacy-compat.js b/node_modules/meteor-node-stubs/node_modules/events/tests/legacy-compat.js new file mode 100644 index 0000000..afbc0ab --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/tests/legacy-compat.js @@ -0,0 +1,18 @@ +// sigh... life is hard +if (!global.console) { + console = {} +} + +var fns = ['log', 'error', 'trace']; +for (var i=0 ; ifoo should not be emitted', '!'); +}; + +e.once('foo', remove); +e.removeListener('foo', remove); +e.emit('foo'); + +var times_recurse_emitted = 0; + +e.once('e', function() { + e.emit('e'); + times_recurse_emitted++; +}); + +e.once('e', function() { + times_recurse_emitted++; +}); + +e.emit('e'); + +assert.equal(1, times_hello_emited); +assert.equal(2, times_recurse_emitted); diff --git a/node_modules/meteor-node-stubs/node_modules/events/tests/remove-all-listeners.js b/node_modules/meteor-node-stubs/node_modules/events/tests/remove-all-listeners.js new file mode 100644 index 0000000..b3dc886 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/events/tests/remove-all-listeners.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('./common'); +var assert = require('assert'); +var events = require('../'); + +var after_checks = []; +after(function() { + for (var i=0 ; i + + xhr + + +
+ + + diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/get/main.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/get/main.js new file mode 100644 index 0000000..3030d2d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/get/main.js @@ -0,0 +1,14 @@ +var http = require('../../'); + +http.get({ path : '/beep' }, function (res) { + var div = document.getElementById('result'); + div.innerHTML += 'GET /beep
'; + + res.on('data', function (buf) { + div.innerHTML += buf; + }); + + res.on('end', function () { + div.innerHTML += '
__END__'; + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/get/server.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/get/server.js new file mode 100644 index 0000000..a048277 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/get/server.js @@ -0,0 +1,12 @@ +var http = require('http'); +var ecstatic = require('ecstatic')(__dirname); +var server = http.createServer(function (req, res) { + if (req.url === '/beep') { + res.setHeader('content-type', 'text/plain'); + res.end('boop'); + } + else ecstatic(req, res); +}); + +console.log('Listening on :8082'); +server.listen(8082); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/index.html b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/index.html new file mode 100644 index 0000000..7001c20 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/index.html @@ -0,0 +1,9 @@ + + + xhr + + +
+ + + diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/main.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/main.js new file mode 100644 index 0000000..247806c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/main.js @@ -0,0 +1,18 @@ +var http = require('../../'); + +var opts = { path : '/beep', method : 'GET' }; +var req = http.request(opts, function (res) { + var div = document.getElementById('result'); + + for (var key in res.headers) { + div.innerHTML += key + ': ' + res.getHeader(key) + '
'; + } + div.innerHTML += '
'; + + res.on('data', function (buf) { + div.innerHTML += buf; + }); +}); + +req.setHeader('bling', 'blong'); +req.end(); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/server.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/server.js new file mode 100644 index 0000000..386e1fa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/headers/server.js @@ -0,0 +1,15 @@ +var http = require('http'); +var ecstatic = require('ecstatic')(__dirname); +var server = http.createServer(function (req, res) { + if (req.url === '/beep') { + res.setHeader('content-type', 'text/plain'); + res.setHeader('foo', 'bar'); + res.setHeader('bling', req.headers.bling + '-blong'); + + res.end('boop'); + } + else ecstatic(req, res); +}); + +console.log('Listening on :8082'); +server.listen(8082); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/index.html b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/index.html new file mode 100644 index 0000000..7001c20 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/index.html @@ -0,0 +1,9 @@ + + + xhr + + +
+ + + diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/main.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/main.js new file mode 100644 index 0000000..dfb6746 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/main.js @@ -0,0 +1,16 @@ +var http = require('../../'); + +var n = 100; +var opts = { path : '/plusone', method : 'post' }; + +var req = http.request(opts, function (res) { + var div = document.getElementById('result'); + div.innerHTML += n.toString() + ' + 1 = '; + + res.on('data', function (buf) { + div.innerHTML += buf; + }); +}); + +req.write(n); +req.end(); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/server.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/server.js new file mode 100644 index 0000000..d16963f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/post/server.js @@ -0,0 +1,19 @@ +var http = require('http'); +var ecstatic = require('ecstatic')(__dirname); +var server = http.createServer(function (req, res) { + if (req.method === 'POST' && req.url === '/plusone') { + res.setHeader('content-type', 'text/plain'); + + var s = ''; + req.on('data', function (buf) { s += buf.toString() }); + + req.on('end', function () { + var n = parseInt(s) + 1; + res.end(n.toString()); + }); + } + else ecstatic(req, res); +}); + +console.log('Listening on :8082'); +server.listen(8082); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/index.html b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/index.html new file mode 100644 index 0000000..7001c20 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/index.html @@ -0,0 +1,9 @@ + + + xhr + + +
+ + + diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/main.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/main.js new file mode 100644 index 0000000..40ee353 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/main.js @@ -0,0 +1,16 @@ +var http = require('../../'); + +http.get({ path : '/doom' }, function (res) { + var div = document.getElementById('result'); + if (!div.style) div.style = {}; + div.style.color = 'rgb(80,80,80)'; + + res.on('data', function (buf) { + div.innerHTML += buf; + }); + + res.on('end', function () { + div.style.color = 'black'; + div.innerHTML += '!'; + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/server.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/server.js new file mode 100644 index 0000000..55c9ede --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/example/streaming/server.js @@ -0,0 +1,21 @@ +var http = require('http'); +var ecstatic = require('ecstatic')(__dirname); +var server = http.createServer(function (req, res) { + if (req.url === '/doom') { + res.setHeader('content-type', 'multipart/octet-stream'); + + res.write('d'); + var i = 0; + var iv = setInterval(function () { + res.write('o'); + if (i++ >= 10) { + clearInterval(iv); + res.end('m'); + } + }, 500); + } + else ecstatic(req, res); +}); + +console.log('Listening on :8082'); +server.listen(8082); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/index.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/index.js new file mode 100644 index 0000000..fedd2a2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/index.js @@ -0,0 +1,145 @@ +var http = module.exports; +var EventEmitter = require('events').EventEmitter; +var Request = require('./lib/request'); +var url = require('url') + +http.request = function (params, cb) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params) params = {}; + if (!params.host && !params.port) { + params.port = parseInt(window.location.port, 10); + } + if (!params.host && params.hostname) { + params.host = params.hostname; + } + + if (!params.protocol) { + if (params.scheme) { + params.protocol = params.scheme + ':'; + } else { + params.protocol = window.location.protocol; + } + } + + if (!params.host) { + params.host = window.location.hostname || window.location.host; + } + if (/:/.test(params.host)) { + if (!params.port) { + params.port = params.host.split(':')[1]; + } + params.host = params.host.split(':')[0]; + } + if (!params.port) params.port = params.protocol == 'https:' ? 443 : 80; + + var req = new Request(new xhrHttp, params); + if (cb) req.on('response', cb); + return req; +}; + +http.get = function (params, cb) { + params.method = 'GET'; + var req = http.request(params, cb); + req.end(); + return req; +}; + +http.Agent = function () {}; +http.Agent.defaultMaxSockets = 4; + +var xhrHttp = (function () { + if (typeof window === 'undefined') { + throw new Error('no window object present'); + } + else if (window.XMLHttpRequest) { + return window.XMLHttpRequest; + } + else if (window.ActiveXObject) { + var axs = [ + 'Msxml2.XMLHTTP.6.0', + 'Msxml2.XMLHTTP.3.0', + 'Microsoft.XMLHTTP' + ]; + for (var i = 0; i < axs.length; i++) { + try { + var ax = new(window.ActiveXObject)(axs[i]); + return function () { + if (ax) { + var ax_ = ax; + ax = null; + return ax_; + } + else { + return new(window.ActiveXObject)(axs[i]); + } + }; + } + catch (e) {} + } + throw new Error('ajax not supported in this browser') + } + else { + throw new Error('ajax not supported in this browser'); + } +})(); + +http.STATUS_CODES = { + 100 : 'Continue', + 101 : 'Switching Protocols', + 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918 + 200 : 'OK', + 201 : 'Created', + 202 : 'Accepted', + 203 : 'Non-Authoritative Information', + 204 : 'No Content', + 205 : 'Reset Content', + 206 : 'Partial Content', + 207 : 'Multi-Status', // RFC 4918 + 300 : 'Multiple Choices', + 301 : 'Moved Permanently', + 302 : 'Moved Temporarily', + 303 : 'See Other', + 304 : 'Not Modified', + 305 : 'Use Proxy', + 307 : 'Temporary Redirect', + 400 : 'Bad Request', + 401 : 'Unauthorized', + 402 : 'Payment Required', + 403 : 'Forbidden', + 404 : 'Not Found', + 405 : 'Method Not Allowed', + 406 : 'Not Acceptable', + 407 : 'Proxy Authentication Required', + 408 : 'Request Time-out', + 409 : 'Conflict', + 410 : 'Gone', + 411 : 'Length Required', + 412 : 'Precondition Failed', + 413 : 'Request Entity Too Large', + 414 : 'Request-URI Too Large', + 415 : 'Unsupported Media Type', + 416 : 'Requested Range Not Satisfiable', + 417 : 'Expectation Failed', + 418 : 'I\'m a teapot', // RFC 2324 + 422 : 'Unprocessable Entity', // RFC 4918 + 423 : 'Locked', // RFC 4918 + 424 : 'Failed Dependency', // RFC 4918 + 425 : 'Unordered Collection', // RFC 4918 + 426 : 'Upgrade Required', // RFC 2817 + 428 : 'Precondition Required', // RFC 6585 + 429 : 'Too Many Requests', // RFC 6585 + 431 : 'Request Header Fields Too Large',// RFC 6585 + 500 : 'Internal Server Error', + 501 : 'Not Implemented', + 502 : 'Bad Gateway', + 503 : 'Service Unavailable', + 504 : 'Gateway Time-out', + 505 : 'HTTP Version Not Supported', + 506 : 'Variant Also Negotiates', // RFC 2295 + 507 : 'Insufficient Storage', // RFC 4918 + 509 : 'Bandwidth Limit Exceeded', + 510 : 'Not Extended', // RFC 2774 + 511 : 'Network Authentication Required' // RFC 6585 +}; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/lib/request.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/lib/request.js new file mode 100644 index 0000000..7b8b733 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/lib/request.js @@ -0,0 +1,209 @@ +var Stream = require('stream'); +var Response = require('./response'); +var Base64 = require('Base64'); +var inherits = require('inherits'); + +var Request = module.exports = function (xhr, params) { + var self = this; + self.writable = true; + self.xhr = xhr; + self.body = []; + + self.uri = (params.protocol || 'http:') + '//' + + params.host + + (params.port ? ':' + params.port : '') + + (params.path || '/') + ; + + if (typeof params.withCredentials === 'undefined') { + params.withCredentials = true; + } + + try { xhr.withCredentials = params.withCredentials } + catch (e) {} + + if (params.responseType) try { xhr.responseType = params.responseType } + catch (e) {} + + xhr.open( + params.method || 'GET', + self.uri, + true + ); + + xhr.onerror = function(event) { + self.emit('error', new Error('Network error')); + }; + + self._headers = {}; + + if (params.headers) { + var keys = objectKeys(params.headers); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (!self.isSafeRequestHeader(key)) continue; + var value = params.headers[key]; + self.setHeader(key, value); + } + } + + if (params.auth) { + //basic auth + this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth)); + } + + var res = new Response; + res.on('close', function () { + self.emit('close'); + }); + + res.on('ready', function () { + self.emit('response', res); + }); + + res.on('error', function (err) { + self.emit('error', err); + }); + + xhr.onreadystatechange = function () { + // Fix for IE9 bug + // SCRIPT575: Could not complete the operation due to error c00c023f + // It happens when a request is aborted, calling the success callback anyway with readyState === 4 + if (xhr.__aborted) return; + res.handle(xhr); + }; +}; + +inherits(Request, Stream); + +Request.prototype.setHeader = function (key, value) { + this._headers[key.toLowerCase()] = value +}; + +Request.prototype.getHeader = function (key) { + return this._headers[key.toLowerCase()] +}; + +Request.prototype.removeHeader = function (key) { + delete this._headers[key.toLowerCase()] +}; + +Request.prototype.write = function (s) { + this.body.push(s); +}; + +Request.prototype.destroy = function (s) { + this.xhr.__aborted = true; + this.xhr.abort(); + this.emit('close'); +}; + +Request.prototype.end = function (s) { + if (s !== undefined) this.body.push(s); + + var keys = objectKeys(this._headers); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = this._headers[key]; + if (isArray(value)) { + for (var j = 0; j < value.length; j++) { + this.xhr.setRequestHeader(key, value[j]); + } + } + else this.xhr.setRequestHeader(key, value) + } + + if (this.body.length === 0) { + this.xhr.send(''); + } + else if (typeof this.body[0] === 'string') { + this.xhr.send(this.body.join('')); + } + else if (isArray(this.body[0])) { + var body = []; + for (var i = 0; i < this.body.length; i++) { + body.push.apply(body, this.body[i]); + } + this.xhr.send(body); + } + else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) { + var len = 0; + for (var i = 0; i < this.body.length; i++) { + len += this.body[i].length; + } + var body = new(this.body[0].constructor)(len); + var k = 0; + + for (var i = 0; i < this.body.length; i++) { + var b = this.body[i]; + for (var j = 0; j < b.length; j++) { + body[k++] = b[j]; + } + } + this.xhr.send(body); + } + else if (isXHR2Compatible(this.body[0])) { + this.xhr.send(this.body[0]); + } + else { + var body = ''; + for (var i = 0; i < this.body.length; i++) { + body += this.body[i].toString(); + } + this.xhr.send(body); + } +}; + +// Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html +Request.unsafeHeaders = [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "cookie2", + "content-transfer-encoding", + "date", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "user-agent", + "via" +]; + +Request.prototype.isSafeRequestHeader = function (headerName) { + if (!headerName) return false; + return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1; +}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +var indexOf = function (xs, x) { + if (xs.indexOf) return xs.indexOf(x); + for (var i = 0; i < xs.length; i++) { + if (xs[i] === x) return i; + } + return -1; +}; + +var isXHR2Compatible = function (obj) { + if (typeof Blob !== 'undefined' && obj instanceof Blob) return true; + if (typeof ArrayBuffer !== 'undefined' && obj instanceof ArrayBuffer) return true; + if (typeof FormData !== 'undefined' && obj instanceof FormData) return true; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/lib/response.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/lib/response.js new file mode 100644 index 0000000..f83d761 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/lib/response.js @@ -0,0 +1,120 @@ +var Stream = require('stream'); +var util = require('util'); + +var Response = module.exports = function (res) { + this.offset = 0; + this.readable = true; +}; + +util.inherits(Response, Stream); + +var capable = { + streaming : true, + status2 : true +}; + +function parseHeaders (res) { + var lines = res.getAllResponseHeaders().split(/\r?\n/); + var headers = {}; + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (line === '') continue; + + var m = line.match(/^([^:]+):\s*(.*)/); + if (m) { + var key = m[1].toLowerCase(), value = m[2]; + + if (headers[key] !== undefined) { + + if (isArray(headers[key])) { + headers[key].push(value); + } + else { + headers[key] = [ headers[key], value ]; + } + } + else { + headers[key] = value; + } + } + else { + headers[line] = true; + } + } + return headers; +} + +Response.prototype.getResponse = function (xhr) { + var respType = String(xhr.responseType).toLowerCase(); + if (respType === 'blob') return xhr.responseBlob || xhr.response; + if (respType === 'arraybuffer') return xhr.response; + return xhr.responseText; +} + +Response.prototype.getHeader = function (key) { + return this.headers[key.toLowerCase()]; +}; + +Response.prototype.handle = function (res) { + if (res.readyState === 2 && capable.status2) { + try { + this.statusCode = res.status; + this.headers = parseHeaders(res); + } + catch (err) { + capable.status2 = false; + } + + if (capable.status2) { + this.emit('ready'); + } + } + else if (capable.streaming && res.readyState === 3) { + try { + if (!this.statusCode) { + this.statusCode = res.status; + this.headers = parseHeaders(res); + this.emit('ready'); + } + } + catch (err) {} + + try { + this._emitData(res); + } + catch (err) { + capable.streaming = false; + } + } + else if (res.readyState === 4) { + if (!this.statusCode) { + this.statusCode = res.status; + this.emit('ready'); + } + this._emitData(res); + + if (res.error) { + this.emit('error', this.getResponse(res)); + } + else this.emit('end'); + + this.emit('close'); + } +}; + +Response.prototype._emitData = function (res) { + var respBody = this.getResponse(res); + if (respBody.toString().match(/ArrayBuffer/)) { + this.emit('data', new Uint8Array(respBody, this.offset)); + this.offset = respBody.byteLength; + return; + } + if (respBody.length > this.offset) { + this.emit('data', respBody.slice(this.offset)); + this.offset = respBody.length; + } +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/.npmignore b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/.npmignore new file mode 100644 index 0000000..cba87a3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/.npmignore @@ -0,0 +1,2 @@ +/coverage/ +/node_modules/ diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/.travis.yml b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/.travis.yml new file mode 100644 index 0000000..fbde051 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" +install: make setup +script: make test diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/LICENSE b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/LICENSE new file mode 100644 index 0000000..4832767 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/LICENSE @@ -0,0 +1,14 @@ + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (c) 2011..2012 David Chambers + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT THE FUCK YOU WANT TO. diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/Makefile b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/Makefile new file mode 100644 index 0000000..5c475df --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/Makefile @@ -0,0 +1,42 @@ +ISTANBUL = node_modules/.bin/istanbul +UGLIFYJS = node_modules/.bin/uglifyjs +XYZ = node_modules/.bin/xyz --message X.Y.Z --tag X.Y.Z + +SRC = base64.js +MIN = $(patsubst %.js,%.min.js,$(SRC)) + + +.PHONY: all +all: $(MIN) + +%.min.js: %.js + $(UGLIFYJS) $< --compress --mangle > $@ + + +.PHONY: bytes +bytes: base64.min.js + gzip --best --stdout $< | wc -c | tr -d ' ' + + +.PHONY: clean +clean: + rm -f -- $(MIN) + + +.PHONY: release-major release-minor release-patch +release-major: + $(XYZ) --increment major +release-minor: + $(XYZ) --increment minor +release-patch: + $(XYZ) --increment patch + + +.PHONY: setup +setup: + npm install + + +.PHONY: test +test: + $(ISTANBUL) cover node_modules/.bin/_mocha -- --compilers coffee:coffee-script/register diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/README.md b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/README.md new file mode 100644 index 0000000..e5dafed --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/README.md @@ -0,0 +1,34 @@ +# Base64.js + +≈ 500 byte* polyfill for browsers which don't provide [`window.btoa`][1] and +[`window.atob`][2]. + +Although the script does no harm in browsers which do provide these functions, +a conditional script loader such as [yepnope][3] can prevent unnecessary HTTP +requests. + +```javascript +yepnope({ + test: window.btoa && window.atob, + nope: 'base64.js', + callback: function () { + // `btoa` and `atob` are now safe to use + } +}) +``` + +Base64.js stems from a [gist][4] by [yahiko][5]. + +### Running the test suite + + make setup + make test + +\* Minified and gzipped. Run `make bytes` to verify. + + +[1]: https://developer.mozilla.org/en/DOM/window.btoa +[2]: https://developer.mozilla.org/en/DOM/window.atob +[3]: http://yepnopejs.com/ +[4]: https://gist.github.com/229984 +[5]: https://github.com/yahiko diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/base64.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/base64.js new file mode 100644 index 0000000..15d3a8a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/base64.js @@ -0,0 +1,60 @@ +;(function () { + + var object = typeof exports != 'undefined' ? exports : this; // #8: web workers + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + + function InvalidCharacterError(message) { + this.message = message; + } + InvalidCharacterError.prototype = new Error; + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + // encoder + // [https://gist.github.com/999166] by [https://github.com/nignag] + object.btoa || ( + object.btoa = function (input) { + for ( + // initialize result and counter + var block, charCode, idx = 0, map = chars, output = ''; + // if the next input index does not exist: + // change the mapping table to "=" + // check if d has no fractional digits + input.charAt(idx | 0) || (map = '=', idx % 1); + // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 + output += map.charAt(63 & block >> 8 - idx % 1 * 8) + ) { + charCode = input.charCodeAt(idx += 3/4); + if (charCode > 0xFF) { + throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); + } + block = block << 8 | charCode; + } + return output; + }); + + // decoder + // [https://gist.github.com/1020396] by [https://github.com/atk] + object.atob || ( + object.atob = function (input) { + input = input.replace(/=+$/, ''); + if (input.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for ( + // initialize result and counters + var bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = input.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output; + }); + +}()); diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/base64.min.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/base64.min.js new file mode 100644 index 0000000..33c7aa4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/base64.min.js @@ -0,0 +1 @@ +!function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=new Error,t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-a%1*8)){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),e.length%4==1)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(-2*a&6)):0)n=r.indexOf(n);return c})}(); \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/package.json b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/package.json new file mode 100644 index 0000000..280eb51 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/package.json @@ -0,0 +1,37 @@ +{ + "name": "Base64", + "version": "0.2.1", + "description": "Base64 encoding and decoding", + "author": { + "name": "David Chambers", + "email": "dc@davidchambers.me" + }, + "main": "./base64.js", + "licenses": [ + { + "type": "WTFPL", + "url": "https://raw.github.com/davidchambers/Base64.js/master/LICENSE" + } + ], + "repository": { + "type": "git", + "url": "git://github.com/davidchambers/Base64.js.git" + }, + "devDependencies": { + "coffee-script": "1.7.x", + "istanbul": "0.2.x", + "mocha": "1.18.x", + "uglify-js": "2.4.x", + "xyz": "0.1.x" + }, + "readme": "# Base64.js\n\n≈ 500 byte* polyfill for browsers which don't provide [`window.btoa`][1] and\n[`window.atob`][2].\n\nAlthough the script does no harm in browsers which do provide these functions,\na conditional script loader such as [yepnope][3] can prevent unnecessary HTTP\nrequests.\n\n```javascript\nyepnope({\n test: window.btoa && window.atob,\n nope: 'base64.js',\n callback: function () {\n // `btoa` and `atob` are now safe to use\n }\n})\n```\n\nBase64.js stems from a [gist][4] by [yahiko][5].\n\n### Running the test suite\n\n make setup\n make test\n\n\\* Minified and gzipped. Run `make bytes` to verify.\n\n\n[1]: https://developer.mozilla.org/en/DOM/window.btoa\n[2]: https://developer.mozilla.org/en/DOM/window.atob\n[3]: http://yepnopejs.com/\n[4]: https://gist.github.com/229984\n[5]: https://github.com/yahiko\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/davidchambers/Base64.js/issues" + }, + "homepage": "https://github.com/davidchambers/Base64.js#readme", + "_id": "Base64@0.2.1", + "_shasum": "ba3a4230708e186705065e66babdd4c35cf60028", + "_resolved": "https://registry.npmjs.org/Base64/-/Base64-0.2.1.tgz", + "_from": "https://registry.npmjs.org/Base64/-/Base64-0.2.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/test/base64.coffee b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/test/base64.coffee new file mode 100644 index 0000000..e25cf5c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/Base64/test/base64.coffee @@ -0,0 +1,52 @@ +assert = require 'assert' + +{btoa, atob} = require '..' + + +describe 'Base64.js', -> + + it 'can encode ASCII input', -> + assert.strictEqual btoa(''), '' + assert.strictEqual btoa('f'), 'Zg==' + assert.strictEqual btoa('fo'), 'Zm8=' + assert.strictEqual btoa('foo'), 'Zm9v' + assert.strictEqual btoa('quux'), 'cXV1eA==' + assert.strictEqual btoa('!"#$%'), 'ISIjJCU=' + assert.strictEqual btoa("&'()*+"), 'JicoKSor' + assert.strictEqual btoa(',-./012'), 'LC0uLzAxMg==' + assert.strictEqual btoa('3456789:'), 'MzQ1Njc4OTo=' + assert.strictEqual btoa(';<=>?@ABC'), 'Ozw9Pj9AQUJD' + assert.strictEqual btoa('DEFGHIJKLM'), 'REVGR0hJSktMTQ==' + assert.strictEqual btoa('NOPQRSTUVWX'), 'Tk9QUVJTVFVWV1g=' + assert.strictEqual btoa('YZ[\\]^_`abc'), 'WVpbXF1eX2BhYmM=' + assert.strictEqual btoa('defghijklmnop'), 'ZGVmZ2hpamtsbW5vcA==' + assert.strictEqual btoa('qrstuvwxyz{|}~'), 'cXJzdHV2d3h5ent8fX4=' + + it 'cannot encode non-ASCII input', -> + assert.throws (-> btoa '✈'), (err) -> + err instanceof Error and + err.name is 'InvalidCharacterError' and + err.message is "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range." + + it 'can decode Base64-encoded input', -> + assert.strictEqual atob(''), '' + assert.strictEqual atob('Zg=='), 'f' + assert.strictEqual atob('Zm8='), 'fo' + assert.strictEqual atob('Zm9v'), 'foo' + assert.strictEqual atob('cXV1eA=='), 'quux' + assert.strictEqual atob('ISIjJCU='), '!"#$%' + assert.strictEqual atob('JicoKSor'), "&'()*+" + assert.strictEqual atob('LC0uLzAxMg=='), ',-./012' + assert.strictEqual atob('MzQ1Njc4OTo='), '3456789:' + assert.strictEqual atob('Ozw9Pj9AQUJD'), ';<=>?@ABC' + assert.strictEqual atob('REVGR0hJSktMTQ=='), 'DEFGHIJKLM' + assert.strictEqual atob('Tk9QUVJTVFVWV1g='), 'NOPQRSTUVWX' + assert.strictEqual atob('WVpbXF1eX2BhYmM='), 'YZ[\\]^_`abc' + assert.strictEqual atob('ZGVmZ2hpamtsbW5vcA=='), 'defghijklmnop' + assert.strictEqual atob('cXJzdHV2d3h5ent8fX4='), 'qrstuvwxyz{|}~' + + it 'cannot decode invalid input', -> + assert.throws (-> atob 'a'), (err) -> + err instanceof Error and + err.name is 'InvalidCharacterError' and + err.message is "'atob' failed: The string to be decoded is not correctly encoded." diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/LICENSE b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/README.md b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/inherits.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/inherits_browser.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/package.json b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/package.json new file mode 100644 index 0000000..bad1183 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/test.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/http-browserify/package.json new file mode 100644 index 0000000..ba969de --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/package.json @@ -0,0 +1,50 @@ +{ + "name": "http-browserify", + "version": "1.7.0", + "description": "http module compatability for browserify", + "main": "index.js", + "browserify": "index.js", + "directories": { + "lib": ".", + "example": "example", + "test": "test" + }, + "scripts": { + "test": "tape test/*.js" + }, + "dependencies": { + "Base64": "~0.2.0", + "inherits": "~2.0.1" + }, + "devDependencies": { + "ecstatic": "~0.1.6", + "tape": "~2.3.2" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/substack/http-browserify.git" + }, + "keywords": [ + "http", + "browserify", + "compatible", + "meatless", + "browser" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT/X11", + "readme": "# http-browserify\n\nThe\n[http](http://nodejs.org/docs/v0.4.10/api/all.html#hTTP) module from node.js,\nbut for browsers.\n\nWhen you `require('http')` in\n[browserify](http://github.com/substack/node-browserify),\nthis module will be loaded.\n\n# example\n\n``` js\nvar http = require('http');\n\nhttp.get({ path : '/beep' }, function (res) {\n var div = document.getElementById('result');\n div.innerHTML += 'GET /beep
';\n \n res.on('data', function (buf) {\n div.innerHTML += buf;\n });\n \n res.on('end', function () {\n div.innerHTML += '
__END__';\n });\n});\n```\n\n# http methods\n\nvar http = require('http');\n\n## var req = http.request(opts, cb)\n\nwhere `opts` are:\n\n* `opts.method='GET'` - http method verb\n* `opts.path` - path string, example: `'/foo/bar?baz=555'`\n* `opts.headers={}` - as an object mapping key names to string or Array values\n* `opts.host=window.location.host` - http host\n* `opts.port=window.location.port` - http port\n* `opts.responseType` - response type to set on the underlying xhr object\n\nThe callback will be called with the response object.\n\n## var req = http.get(options, cb)\n\nA shortcut for\n\n``` js\noptions.method = 'GET';\nvar req = http.request(options, cb);\nreq.end();\n```\n\n# request methods\n\n## req.setHeader(key, value)\n\nSet an http header.\n\n## req.getHeader(key)\n\nGet an http header.\n\n## req.removeHeader(key)\n\nRemove an http header.\n\n## req.write(data)\n\nWrite some data to the request body.\n\nIf only 1 piece of data is written, `data` can be a FormData, Blob, or\nArrayBuffer instance. Otherwise, `data` should be a string or a buffer.\n\n## req.end(data)\n\nClose and send the request body, optionally with additional `data` to append.\n\n# response methods\n\n## res.getHeader(key)\n\nReturn an http header, if set. `key` is case-insensitive.\n\n# response attributes\n\n* res.statusCode, the numeric http response code\n* res.headers, an object with all lowercase keys\n\n# compatibility\n\nThis module has been tested and works with:\n\n* Internet Explorer 5.5, 6, 7, 8, 9\n* Firefox 3.5\n* Chrome 7.0\n* Opera 10.6\n* Safari 5.0\n\nMultipart streaming responses are buffered in all versions of Internet Explorer\nand are somewhat buffered in Opera. In all the other browsers you get a nice\nunbuffered stream of `\"data\"` events when you send down a content-type of\n`multipart/octet-stream` or similar.\n\n# protip\n\nYou can do:\n\n````javascript\nvar bundle = browserify({\n require : { http : 'http-browserify' }\n});\n````\n\nin order to map \"http-browserify\" over `require('http')` in your browserified\nsource.\n\n# install\n\nWith [npm](https://npmjs.org) do:\n\n```\nnpm install http-browserify\n```\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/http-browserify/issues" + }, + "homepage": "https://github.com/substack/http-browserify#readme", + "_id": "http-browserify@1.7.0", + "_shasum": "33795ade72df88acfbfd36773cefeda764735b20", + "_resolved": "https://registry.npmjs.org/http-browserify/-/http-browserify-1.7.0.tgz", + "_from": "https://registry.npmjs.org/http-browserify/-/http-browserify-1.7.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/readme.markdown b/node_modules/meteor-node-stubs/node_modules/http-browserify/readme.markdown new file mode 100644 index 0000000..bd5c14b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/readme.markdown @@ -0,0 +1,131 @@ +# http-browserify + +The +[http](http://nodejs.org/docs/v0.4.10/api/all.html#hTTP) module from node.js, +but for browsers. + +When you `require('http')` in +[browserify](http://github.com/substack/node-browserify), +this module will be loaded. + +# example + +``` js +var http = require('http'); + +http.get({ path : '/beep' }, function (res) { + var div = document.getElementById('result'); + div.innerHTML += 'GET /beep
'; + + res.on('data', function (buf) { + div.innerHTML += buf; + }); + + res.on('end', function () { + div.innerHTML += '
__END__'; + }); +}); +``` + +# http methods + +var http = require('http'); + +## var req = http.request(opts, cb) + +where `opts` are: + +* `opts.method='GET'` - http method verb +* `opts.path` - path string, example: `'/foo/bar?baz=555'` +* `opts.headers={}` - as an object mapping key names to string or Array values +* `opts.host=window.location.host` - http host +* `opts.port=window.location.port` - http port +* `opts.responseType` - response type to set on the underlying xhr object + +The callback will be called with the response object. + +## var req = http.get(options, cb) + +A shortcut for + +``` js +options.method = 'GET'; +var req = http.request(options, cb); +req.end(); +``` + +# request methods + +## req.setHeader(key, value) + +Set an http header. + +## req.getHeader(key) + +Get an http header. + +## req.removeHeader(key) + +Remove an http header. + +## req.write(data) + +Write some data to the request body. + +If only 1 piece of data is written, `data` can be a FormData, Blob, or +ArrayBuffer instance. Otherwise, `data` should be a string or a buffer. + +## req.end(data) + +Close and send the request body, optionally with additional `data` to append. + +# response methods + +## res.getHeader(key) + +Return an http header, if set. `key` is case-insensitive. + +# response attributes + +* res.statusCode, the numeric http response code +* res.headers, an object with all lowercase keys + +# compatibility + +This module has been tested and works with: + +* Internet Explorer 5.5, 6, 7, 8, 9 +* Firefox 3.5 +* Chrome 7.0 +* Opera 10.6 +* Safari 5.0 + +Multipart streaming responses are buffered in all versions of Internet Explorer +and are somewhat buffered in Opera. In all the other browsers you get a nice +unbuffered stream of `"data"` events when you send down a content-type of +`multipart/octet-stream` or similar. + +# protip + +You can do: + +````javascript +var bundle = browserify({ + require : { http : 'http-browserify' } +}); +```` + +in order to map "http-browserify" over `require('http')` in your browserified +source. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install http-browserify +``` + +# license + +MIT diff --git a/node_modules/meteor-node-stubs/node_modules/http-browserify/test/request_url.js b/node_modules/meteor-node-stubs/node_modules/http-browserify/test/request_url.js new file mode 100644 index 0000000..1f58f2d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/http-browserify/test/request_url.js @@ -0,0 +1,114 @@ +global.window = global; +global.location = { + host: 'localhost:8081', + port: 8081, + protocol: 'http:' +}; + +var noop = function() {}; +global.XMLHttpRequest = function() { + this.open = noop; + this.send = noop; +}; + +global.FormData = function () {}; +global.Blob = function () {}; +global.ArrayBuffer = function () {}; + +var test = require('tape').test; +var http = require('../index.js'); + + +test('Test simple url string', function(t) { + var url = { path: '/api/foo' }; + var request = http.get(url, noop); + + t.equal( request.uri, 'http://localhost:8081/api/foo', 'Url should be correct'); + t.end(); + +}); + + +test('Test full url object', function(t) { + var url = { + host: "localhost:8081", + hostname: "localhost", + href: "http://localhost:8081/api/foo?bar=baz", + method: "GET", + path: "/api/foo?bar=baz", + pathname: "/api/foo", + port: "8081", + protocol: "http:", + query: "bar=baz", + search: "?bar=baz", + slashes: true + }; + + var request = http.get(url, noop); + + t.equal( request.uri, 'http://localhost:8081/api/foo?bar=baz', 'Url should be correct'); + t.end(); + +}); + +test('Test alt protocol', function(t) { + var params = { + protocol: "foo:", + hostname: "localhost", + port: "3000", + path: "/bar" + }; + + var request = http.get(params, noop); + + t.equal( request.uri, 'foo://localhost:3000/bar', 'Url should be correct'); + t.end(); + +}); + +test('Test string as parameters', function(t) { + var url = '/api/foo'; + var request = http.get(url, noop); + + t.equal( request.uri, 'http://localhost:8081/api/foo', 'Url should be correct'); + t.end(); + +}); + +test('Test withCredentials param', function(t) { + var url = '/api/foo'; + + var request = http.request({ url: url, withCredentials: false }, noop); + t.equal( request.xhr.withCredentials, false, 'xhr.withCredentials should be false'); + + var request = http.request({ url: url, withCredentials: true }, noop); + t.equal( request.xhr.withCredentials, true, 'xhr.withCredentials should be true'); + + var request = http.request({ url: url }, noop); + t.equal( request.xhr.withCredentials, true, 'xhr.withCredentials should be true'); + + t.end(); +}); + +test('Test POST XHR2 types', function(t) { + t.plan(3); + var url = '/api/foo'; + + var request = http.request({ url: url, method: 'POST' }, noop); + request.xhr.send = function (data) { + t.ok(data instanceof global.ArrayBuffer, 'data should be instanceof ArrayBuffer'); + }; + request.end(new global.ArrayBuffer()); + + request = http.request({ url: url, method: 'POST' }, noop); + request.xhr.send = function (data) { + t.ok(data instanceof global.Blob, 'data should be instanceof Blob'); + }; + request.end(new global.Blob()); + + request = http.request({ url: url, method: 'POST' }, noop); + request.xhr.send = function (data) { + t.ok(data instanceof global.FormData, 'data should be instanceof FormData'); + }; + request.end(new global.FormData()); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/https-browserify/LICENSE b/node_modules/meteor-node-stubs/node_modules/https-browserify/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/https-browserify/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/https-browserify/index.js b/node_modules/meteor-node-stubs/node_modules/https-browserify/index.js new file mode 100644 index 0000000..8535532 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/https-browserify/index.js @@ -0,0 +1,14 @@ +var http = require('http'); + +var https = module.exports; + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key]; +}; + +https.request = function (params, cb) { + if (!params) params = {}; + params.scheme = 'https'; + params.protocol = 'https:'; + return http.request.call(this, params, cb); +} diff --git a/node_modules/meteor-node-stubs/node_modules/https-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/https-browserify/package.json new file mode 100644 index 0000000..ddff8fe --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/https-browserify/package.json @@ -0,0 +1,31 @@ +{ + "name": "https-browserify", + "version": "0.0.1", + "description": "https module compatability for browserify", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/substack/https-browserify.git" + }, + "homepage": "https://github.com/substack/https-browserify", + "keywords": [ + "https", + "browser", + "browserify" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "readme": "# https-browserify\n\nhttps module compatability for browserify\n\n# example\n\n``` js\nvar https = require('https-browserify');\nvar r = https.request('https://github.com');\nr.on('request', function (res) {\n console.log(res);\n});\n```\n\n# methods\n\nThe API is the same as the client portion of the\n[node core https module](http://nodejs.org/docs/latest/api/https.html).\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/https-browserify/issues" + }, + "_id": "https-browserify@0.0.1", + "_shasum": "3f91365cabe60b77ed0ebba24b454e3e09d95a82", + "_resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-0.0.1.tgz", + "_from": "https://registry.npmjs.org/https-browserify/-/https-browserify-0.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/https-browserify/readme.markdown b/node_modules/meteor-node-stubs/node_modules/https-browserify/readme.markdown new file mode 100644 index 0000000..8638614 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/https-browserify/readme.markdown @@ -0,0 +1,22 @@ +# https-browserify + +https module compatability for browserify + +# example + +``` js +var https = require('https-browserify'); +var r = https.request('https://github.com'); +r.on('request', function (res) { + console.log(res); +}); +``` + +# methods + +The API is the same as the client portion of the +[node core https module](http://nodejs.org/docs/latest/api/https.html). + +# license + +MIT diff --git a/node_modules/meteor-node-stubs/node_modules/os-browserify/.npmignore b/node_modules/meteor-node-stubs/node_modules/os-browserify/.npmignore new file mode 100644 index 0000000..f356293 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/os-browserify/.npmignore @@ -0,0 +1,14 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log diff --git a/node_modules/meteor-node-stubs/node_modules/os-browserify/LICENSE b/node_modules/meteor-node-stubs/node_modules/os-browserify/LICENSE new file mode 100644 index 0000000..7f3d479 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/os-browserify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 CoderPuppy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/os-browserify/README.md b/node_modules/meteor-node-stubs/node_modules/os-browserify/README.md new file mode 100644 index 0000000..4dd7d6e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/os-browserify/README.md @@ -0,0 +1,5 @@ +# os-browserify + +The [os](https://nodejs.org/api/os.html) module from node.js, but for browsers. + +When you `require('os')` in [browserify](http://github.com/substack/node-browserify), this module will be loaded. diff --git a/node_modules/meteor-node-stubs/node_modules/os-browserify/browser.js b/node_modules/meteor-node-stubs/node_modules/os-browserify/browser.js new file mode 100644 index 0000000..6a1ecb0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/os-browserify/browser.js @@ -0,0 +1,45 @@ +exports.endianness = function () { return 'LE' }; + +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; + +exports.loadavg = function () { return [] }; + +exports.uptime = function () { return 0 }; + +exports.freemem = function () { + return Number.MAX_VALUE; +}; + +exports.totalmem = function () { + return Number.MAX_VALUE; +}; + +exports.cpus = function () { return [] }; + +exports.type = function () { return 'Browser' }; + +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; + +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; + +exports.arch = function () { return 'javascript' }; + +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; diff --git a/node_modules/meteor-node-stubs/node_modules/os-browserify/main.js b/node_modules/meteor-node-stubs/node_modules/os-browserify/main.js new file mode 100644 index 0000000..5910697 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/os-browserify/main.js @@ -0,0 +1 @@ +module.exports = require('os'); diff --git a/node_modules/meteor-node-stubs/node_modules/os-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/os-browserify/package.json new file mode 100644 index 0000000..89e6489 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/os-browserify/package.json @@ -0,0 +1,34 @@ +{ + "name": "os-browserify", + "version": "0.2.1", + "author": { + "name": "CoderPuppy", + "email": "coderpup@gmail.com" + }, + "license": "MIT", + "main": "main.js", + "browser": "browser.js", + "jspm": { + "map": { + "./main.js": { + "node": "@node/os", + "browser": "./browser.js" + } + } + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/CoderPuppy/os-browserify.git" + }, + "readme": "# os-browserify\n\nThe [os](https://nodejs.org/api/os.html) module from node.js, but for browsers.\n\nWhen you `require('os')` in [browserify](http://github.com/substack/node-browserify), this module will be loaded.\n", + "readmeFilename": "README.md", + "description": "The [os](https://nodejs.org/api/os.html) module from node.js, but for browsers.", + "bugs": { + "url": "https://github.com/CoderPuppy/os-browserify/issues" + }, + "homepage": "https://github.com/CoderPuppy/os-browserify#readme", + "_id": "os-browserify@0.2.1", + "_shasum": "63fc4ccee5d2d7763d26bbf8601078e6c2e0044f", + "_resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.2.1.tgz", + "_from": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.2.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/path-browserify/LICENSE b/node_modules/meteor-node-stubs/node_modules/path-browserify/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/path-browserify/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/path-browserify/index.js b/node_modules/meteor-node-stubs/node_modules/path-browserify/index.js new file mode 100644 index 0000000..285e32d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/path-browserify/index.js @@ -0,0 +1,224 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; diff --git a/node_modules/meteor-node-stubs/node_modules/path-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/path-browserify/package.json new file mode 100644 index 0000000..0cfef2b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/path-browserify/package.json @@ -0,0 +1,38 @@ +{ + "name": "path-browserify", + "version": "0.0.0", + "description": "the path module from node core for browsers", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "~1.0.4" + }, + "scripts": { + "test": "tape test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/path-browserify.git" + }, + "homepage": "https://github.com/substack/path-browserify", + "keywords": [ + "path", + "browser", + "browserify" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "readme": "# path-browserify\n\nthe path module from node core for browsers\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/path-browserify/issues" + }, + "_id": "path-browserify@0.0.0", + "_shasum": "a0b870729aae214005b7d5032ec2cbbb0fb4451a", + "_resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz", + "_from": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/path-browserify/readme.markdown b/node_modules/meteor-node-stubs/node_modules/path-browserify/readme.markdown new file mode 100644 index 0000000..8ae1dd8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/path-browserify/readme.markdown @@ -0,0 +1,3 @@ +# path-browserify + +the path module from node core for browsers diff --git a/node_modules/meteor-node-stubs/node_modules/process/LICENSE b/node_modules/meteor-node-stubs/node_modules/process/LICENSE new file mode 100644 index 0000000..b8c1246 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/process/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 Roman Shtylman + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/process/README.md b/node_modules/meteor-node-stubs/node_modules/process/README.md new file mode 100644 index 0000000..6570729 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/process/README.md @@ -0,0 +1,26 @@ +# process + +```require('process');``` just like any other module. + +Works in node.js and browsers via the browser.js shim provided with the module. + +## browser implementation + +The goal of this module is not to be a full-fledged alternative to the builtin process module. This module mostly exists to provide the nextTick functionality and little more. We keep this module lean because it will often be included by default by tools like browserify when it detects a module has used the `process` global. + +It also exposes a "browser" member (i.e. `process.browser`) which is `true` in this implementation but `undefined` in node. This can be used in isomorphic code that adjusts it's behavior depending on which environment it's running in. + +If you are looking to provide other process methods, I suggest you monkey patch them onto the process global in your app. A list of user created patches is below. + +* [hrtime](https://github.com/kumavis/browser-process-hrtime) +* [stdout](https://github.com/kumavis/browser-stdout) + +## package manager notes + +If you are writing a bundler to package modules for client side use, make sure you use the ```browser``` field hint in package.json. + +See https://gist.github.com/4339901 for details. + +The [browserify](https://github.com/substack/node-browserify) module will properly handle this field when bundling your files. + + diff --git a/node_modules/meteor-node-stubs/node_modules/process/browser.js b/node_modules/meteor-node-stubs/node_modules/process/browser.js new file mode 100644 index 0000000..540fbae --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/process/browser.js @@ -0,0 +1,91 @@ +// shim for using process in browser + +var process = module.exports = {}; +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = setTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + clearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + setTimeout(drainQueue, 0); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; diff --git a/node_modules/meteor-node-stubs/node_modules/process/index.js b/node_modules/meteor-node-stubs/node_modules/process/index.js new file mode 100644 index 0000000..8d8ed7d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/process/index.js @@ -0,0 +1,2 @@ +// for now just expose the builtin process global from node.js +module.exports = global.process; diff --git a/node_modules/meteor-node-stubs/node_modules/process/package.json b/node_modules/meteor-node-stubs/node_modules/process/package.json new file mode 100644 index 0000000..947245d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/process/package.json @@ -0,0 +1,38 @@ +{ + "author": { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + "name": "process", + "description": "process information for node.js and browsers", + "keywords": [ + "process" + ], + "scripts": { + "test": "mocha test.js" + }, + "version": "0.11.2", + "repository": { + "type": "git", + "url": "git://github.com/shtylman/node-process.git" + }, + "license": "MIT", + "browser": "./browser.js", + "main": "./index.js", + "engines": { + "node": ">= 0.6.0" + }, + "devDependencies": { + "mocha": "2.2.1" + }, + "readme": "# process\n\n```require('process');``` just like any other module.\n\nWorks in node.js and browsers via the browser.js shim provided with the module.\n\n## browser implementation\n\nThe goal of this module is not to be a full-fledged alternative to the builtin process module. This module mostly exists to provide the nextTick functionality and little more. We keep this module lean because it will often be included by default by tools like browserify when it detects a module has used the `process` global.\n\nIt also exposes a \"browser\" member (i.e. `process.browser`) which is `true` in this implementation but `undefined` in node. This can be used in isomorphic code that adjusts it's behavior depending on which environment it's running in. \n\nIf you are looking to provide other process methods, I suggest you monkey patch them onto the process global in your app. A list of user created patches is below.\n\n* [hrtime](https://github.com/kumavis/browser-process-hrtime)\n* [stdout](https://github.com/kumavis/browser-stdout)\n\n## package manager notes\n\nIf you are writing a bundler to package modules for client side use, make sure you use the ```browser``` field hint in package.json.\n\nSee https://gist.github.com/4339901 for details.\n\nThe [browserify](https://github.com/substack/node-browserify) module will properly handle this field when bundling your files.\n\n\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/shtylman/node-process/issues" + }, + "homepage": "https://github.com/shtylman/node-process#readme", + "_id": "process@0.11.2", + "_shasum": "8a58d1d12c573f3f890da9848a4fe8e16ca977b2", + "_resolved": "https://registry.npmjs.org/process/-/process-0.11.2.tgz", + "_from": "https://registry.npmjs.org/process/-/process-0.11.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/process/test.js b/node_modules/meteor-node-stubs/node_modules/process/test.js new file mode 100644 index 0000000..9e3e309 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/process/test.js @@ -0,0 +1,66 @@ +var assert = require('assert'); +var ourProcess = require('./browser'); +describe('test against process', function () { + test(process); +}); +if (!process.browser) { + describe('test against our shim', function () { + test(ourProcess); + }); +} +function test (ourProcess) { + describe('test arguments', function (t) { + it ('works', function (done) { + var order = 0; + + + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'first one works'); + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'recursive one is 4th'); + }, 3); + }, 0); + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'second one starts'); + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'this is third'); + ourProcess.nextTick(function (num) { + assert.equal(num, order++, 'this is last'); + done(); + }, 5); + }, 4); + }, 1); + ourProcess.nextTick(function (num) { + + assert.equal(num, order++, '3rd schedualed happens after the error'); + }, 2); + }); + }); + + describe('test errors', function (t) { + it ('works', function (done) { + var order = 0; + process.removeAllListeners('uncaughtException'); + process.once('uncaughtException', function(err) { + assert.equal(2, order++, 'error is third'); + ourProcess.nextTick(function () { + assert.equal(5, order++, 'schedualed in error is last'); + done(); + }); + }); + ourProcess.nextTick(function () { + assert.equal(0, order++, 'first one works'); + ourProcess.nextTick(function () { + assert.equal(4, order++, 'recursive one is 4th'); + }); + }); + ourProcess.nextTick(function () { + assert.equal(1, order++, 'second one starts'); + throw(new Error('an error is thrown')); + }); + ourProcess.nextTick(function () { + assert.equal(3, order++, '3rd schedualed happens after the error'); + }); + }); + }); +} diff --git a/node_modules/meteor-node-stubs/node_modules/punycode/LICENSE-MIT.txt b/node_modules/meteor-node-stubs/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/punycode/README.md b/node_modules/meteor-node-stubs/node_modules/punycode/README.md new file mode 100644 index 0000000..7ad7d1f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/punycode/README.md @@ -0,0 +1,176 @@ +# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) + +A robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms. + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) and [io.js v1.0.0+](https://github.com/iojs/io.js/blob/v1.x/lib/punycode.js). + +## Installation + +Via [npm](https://www.npmjs.com/) (only required for Node.js releases older than v0.6.2): + +```bash +npm install punycode +``` + +Via [Bower](http://bower.io/): + +```bash +bower install punycode +``` + +Via [Component](https://github.com/component/component): + +```bash +component install bestiejs/punycode.js +``` + +In a browser: + +```html + +``` + +In [Node.js](https://nodejs.org/), [io.js](https://iojs.org/), [Narwhal](http://narwhaljs.org/), and [RingoJS](http://ringojs.org/): + +```js +var punycode = require('punycode'); +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('punycode.js'); +``` + +Using an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require( + { + 'paths': { + 'punycode': 'path/to/punycode' + } + }, + ['punycode'], + function(punycode) { + console.log(punycode); + } +); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## Unit tests & code coverage + +After cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. + +Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`. + +To generate the code coverage report, use `grunt cover`. + +Feel free to fork if you see possible improvements! + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## Contributors + +| [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") | +|---| +| [John-David Dalton](http://allyoucanleet.com/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/meteor-node-stubs/node_modules/punycode/package.json b/node_modules/meteor-node-stubs/node_modules/punycode/package.json new file mode 100644 index 0000000..510e5a6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/punycode/package.json @@ -0,0 +1,68 @@ +{ + "name": "punycode", + "version": "1.4.1", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "https://mths.be/punycode", + "main": "punycode.js", + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + { + "name": "John-David Dalton", + "url": "http://allyoucanleet.com/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/bestiejs/punycode.js.git" + }, + "bugs": { + "url": "https://github.com/bestiejs/punycode.js/issues" + }, + "files": [ + "LICENSE-MIT.txt", + "punycode.js" + ], + "scripts": { + "test": "node tests/tests.js" + }, + "devDependencies": { + "coveralls": "^2.11.4", + "grunt": "^0.4.5", + "grunt-contrib-uglify": "^0.11.0", + "grunt-shell": "^1.1.2", + "istanbul": "^0.4.1", + "qunit-extras": "^1.4.4", + "qunitjs": "~1.11.0", + "requirejs": "^2.1.22" + }, + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + }, + "readme": "# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js)\n\nA robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms.\n\nThis JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm:\n\n* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C)\n* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c)\n* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c)\n* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287)\n* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072))\n\nThis project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) and [io.js v1.0.0+](https://github.com/iojs/io.js/blob/v1.x/lib/punycode.js).\n\n## Installation\n\nVia [npm](https://www.npmjs.com/) (only required for Node.js releases older than v0.6.2):\n\n```bash\nnpm install punycode\n```\n\nVia [Bower](http://bower.io/):\n\n```bash\nbower install punycode\n```\n\nVia [Component](https://github.com/component/component):\n\n```bash\ncomponent install bestiejs/punycode.js\n```\n\nIn a browser:\n\n```html\n\n```\n\nIn [Node.js](https://nodejs.org/), [io.js](https://iojs.org/), [Narwhal](http://narwhaljs.org/), and [RingoJS](http://ringojs.org/):\n\n```js\nvar punycode = require('punycode');\n```\n\nIn [Rhino](http://www.mozilla.org/rhino/):\n\n```js\nload('punycode.js');\n```\n\nUsing an AMD loader like [RequireJS](http://requirejs.org/):\n\n```js\nrequire(\n {\n 'paths': {\n 'punycode': 'path/to/punycode'\n }\n },\n ['punycode'],\n function(punycode) {\n console.log(punycode);\n }\n);\n```\n\n## API\n\n### `punycode.decode(string)`\n\nConverts a Punycode string of ASCII symbols to a string of Unicode symbols.\n\n```js\n// decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'\n```\n\n### `punycode.encode(string)`\n\nConverts a string of Unicode symbols to a Punycode string of ASCII symbols.\n\n```js\n// encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'\n```\n\n### `punycode.toUnicode(input)`\n\nConverts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode.\n\n```js\n// decode domain names\npunycode.toUnicode('xn--maana-pta.com');\n// → 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com');\n// → '☃-⌘.com'\n\n// decode email addresses\npunycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq');\n// → 'джумла@джpумлатест.bрфa'\n```\n\n### `punycode.toASCII(input)`\n\nConverts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII.\n\n```js\n// encode domain names\npunycode.toASCII('mañana.com');\n// → 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com');\n// → 'xn----dqo34k.com'\n\n// encode email addresses\npunycode.toASCII('джумла@джpумлатест.bрфa');\n// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'\n```\n\n### `punycode.ucs2`\n\n#### `punycode.ucs2.decode(string)`\n\nCreates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.\n\n```js\npunycode.ucs2.decode('abc');\n// → [0x61, 0x62, 0x63]\n// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE:\npunycode.ucs2.decode('\\uD834\\uDF06');\n// → [0x1D306]\n```\n\n#### `punycode.ucs2.encode(codePoints)`\n\nCreates a string based on an array of numeric code point values.\n\n```js\npunycode.ucs2.encode([0x61, 0x62, 0x63]);\n// → 'abc'\npunycode.ucs2.encode([0x1D306]);\n// → '\\uD834\\uDF06'\n```\n\n### `punycode.version`\n\nA string representing the current Punycode.js version number.\n\n## Unit tests & code coverage\n\nAfter cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`.\n\nOnce that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`.\n\nTo generate the code coverage report, use `grunt cover`.\n\nFeel free to fork if you see possible improvements!\n\n## Author\n\n| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias \"Follow @mathias on Twitter\") |\n|---|\n| [Mathias Bynens](https://mathiasbynens.be/) |\n\n## Contributors\n\n| [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton \"Follow @jdalton on Twitter\") |\n|---|\n| [John-David Dalton](http://allyoucanleet.com/) |\n\n## License\n\nPunycode.js is available under the [MIT](https://mths.be/mit) license.\n", + "readmeFilename": "README.md", + "_id": "punycode@1.4.1", + "_shasum": "c0d5a63b2718800ad8e1eb0fa5269c84dd41845e", + "_resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "_from": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/punycode/punycode.js b/node_modules/meteor-node-stubs/node_modules/punycode/punycode.js new file mode 100644 index 0000000..2c87f6c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/punycode/punycode.js @@ -0,0 +1,533 @@ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/.travis.yml b/node_modules/meteor-node-stubs/node_modules/querystring-es3/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/History.md b/node_modules/meteor-node-stubs/node_modules/querystring-es3/History.md new file mode 100644 index 0000000..4fddbaf --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/History.md @@ -0,0 +1,20 @@ +# 0.2.0 / 2013-02-21 + + - Refactor into function per-module idiomatic style. + - Improved test coverage. + +# 0.1.0 / 2011-12-13 + + - Minor project reorganization + +# 0.0.3 / 2011-04-16 + - Support for AMD module loaders + +# 0.0.2 / 2011-04-16 + + - Ported unit tests + - Removed functionality that depended on Buffers + +# 0.0.1 / 2011-04-15 + + - Initial release diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/License.md b/node_modules/meteor-node-stubs/node_modules/querystring-es3/License.md new file mode 100644 index 0000000..fc80e85 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/License.md @@ -0,0 +1,19 @@ + +Copyright 2012 Irakli Gozalishvili. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/Readme.md b/node_modules/meteor-node-stubs/node_modules/querystring-es3/Readme.md new file mode 100644 index 0000000..be1668d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/Readme.md @@ -0,0 +1,15 @@ +# querystring + +[![Build Status](https://secure.travis-ci.org/mike-spainhower/querystring.png)](http://travis-ci.org/mike-spainhower/querystring) + + +[![Browser support](http://ci.testling.com/mike-spainhower/querystring.png)](http://ci.testling.com/mike-spainhower/querystring) + + + +Node's querystring module for all engines. + +## Install ## + + npm install querystring + diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/decode.js b/node_modules/meteor-node-stubs/node_modules/querystring-es3/decode.js new file mode 100644 index 0000000..b5825c0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/decode.js @@ -0,0 +1,84 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/encode.js b/node_modules/meteor-node-stubs/node_modules/querystring-es3/encode.js new file mode 100644 index 0000000..76e4cfb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/encode.js @@ -0,0 +1,85 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/index.js b/node_modules/meteor-node-stubs/node_modules/querystring-es3/index.js new file mode 100644 index 0000000..99826ea --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/index.js @@ -0,0 +1,4 @@ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/package.json b/node_modules/meteor-node-stubs/node_modules/querystring-es3/package.json new file mode 100644 index 0000000..c78d61d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/package.json @@ -0,0 +1,81 @@ +{ + "name": "querystring-es3", + "id": "querystring-es3", + "version": "0.2.1", + "description": "Node's querystring module for all engines. (ES3 compat fork)", + "keywords": [ + "commonjs", + "query", + "querystring" + ], + "author": { + "name": "Irakli Gozalishvili", + "email": "rfobic@gmail.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/mike-spainhower/querystring.git", + "web": "https://github.com/mike-spainhower/querystring" + }, + "bugs": { + "url": "http://github.com/mike-spainhower/querystring/issues/" + }, + "devDependencies": { + "test": "~0.x.0", + "phantomify": "~0.x.0", + "retape": "~0.x.0", + "tape": "~0.1.5" + }, + "engines": { + "node": ">=0.4.x" + }, + "scripts": { + "test": "npm run test-node && npm run test-browser && npm run test-tap", + "test-browser": "node ./node_modules/phantomify/bin/cmd.js ./test/common-index.js", + "test-node": "node ./test/common-index.js", + "test-tap": "node ./test/tap-index.js" + }, + "testling": { + "files": "test/tap-index.js", + "browsers": { + "iexplore": [ + 9, + 10 + ], + "chrome": [ + 16, + 20, + 25, + "canary" + ], + "firefox": [ + 10, + 15, + 16, + 17, + 18, + "nightly" + ], + "safari": [ + 5, + 6 + ], + "opera": [ + 12 + ] + } + }, + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/Gozala/enchain/License.md" + } + ], + "readme": "# querystring\n\n[![Build Status](https://secure.travis-ci.org/mike-spainhower/querystring.png)](http://travis-ci.org/mike-spainhower/querystring)\n\n\n[![Browser support](http://ci.testling.com/mike-spainhower/querystring.png)](http://ci.testling.com/mike-spainhower/querystring)\n\n\n\nNode's querystring module for all engines.\n\n## Install ##\n\n npm install querystring\n\n", + "readmeFilename": "Readme.md", + "homepage": "https://github.com/mike-spainhower/querystring#readme", + "_id": "querystring-es3@0.2.1", + "_shasum": "9ec61f79049875707d69414596fd907a4d711e73", + "_resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", + "_from": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/common-index.js b/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/common-index.js new file mode 100644 index 0000000..f356f98 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/common-index.js @@ -0,0 +1,3 @@ +"use strict"; + +require("test").run(require("./index")) \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/index.js b/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/index.js new file mode 100644 index 0000000..62eb2ac --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/index.js @@ -0,0 +1,210 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +"use strict"; + +// test using assert +var qs = require('../'); + +// folding block, commented to pass gjslint +// {{{ +// [ wonkyQS, canonicalQS, obj ] +var qsTestCases = [ + ['foo=918854443121279438895193', + 'foo=918854443121279438895193', + {'foo': '918854443121279438895193'}], + ['foo=bar', 'foo=bar', {'foo': 'bar'}], + ['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}], + ['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}], + ['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F', + 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', + {'my weird field': 'q1!2"\'w$5&7/z8)?' }], + ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}], + ['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}], + ['str=foo&arr=1&arr=2&arr=3&somenull=&undef=', + 'str=foo&arr=1&arr=2&arr=3&somenull=&undef=', + { 'str': 'foo', + 'arr': ['1', '2', '3'], + 'somenull': '', + 'undef': ''}], + [' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}], + // disable test that fails ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}], + ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], + // See: https://github.com/joyent/node/issues/1707 + ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + { hasOwnProperty: 'x', + toString: 'foo', + valueOf: 'bar', + __defineGetter__: 'baz' }], + // See: https://github.com/joyent/node/issues/3058 + ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }] +]; + +// [ wonkyQS, canonicalQS, obj ] +var qsColonTestCases = [ + ['foo:bar', 'foo:bar', {'foo': 'bar'}], + ['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], + ['foo:1&bar:2;baz:quux', + 'foo:1%26bar%3A2;baz:quux', + {'foo': '1&bar:2', 'baz': 'quux'}], + ['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}], + ['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}] +]; + +// [wonkyObj, qs, canonicalObj] +var extendedFunction = function() {}; +extendedFunction.prototype = {a: 'b'}; +var qsWeirdObjects = [ + [{regexp: /./g}, 'regexp=', {'regexp': ''}], + [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], + [{fn: function() {}}, 'fn=', {'fn': ''}], + [{fn: new Function('')}, 'fn=', {'fn': ''}], + [{math: Math}, 'math=', {'math': ''}], + [{e: extendedFunction}, 'e=', {'e': ''}], + [{d: new Date()}, 'd=', {'d': ''}], + [{d: Date}, 'd=', {'d': ''}], + [{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], + [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], + [{n: null}, 'n=', {'n': ''}], + [{nan: NaN}, 'nan=', {'nan': ''}], + [{inf: Infinity}, 'inf=', {'inf': ''}] +]; +// }}} + +var qsNoMungeTestCases = [ + ['', {}], + ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], + ['blah=burp', {'blah': 'burp'}], + ['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], + ['frappucino=muffin&goat%5B%5D=scone&pond=moose', + {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], + ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] +]; + +exports['test basic'] = function(assert) { + assert.strictEqual('918854443121279438895193', + qs.parse('id=918854443121279438895193').id, + 'prase id=918854443121279438895193'); +}; + +exports['test that the canonical qs is parsed properly'] = function(assert) { + qsTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[0]), + 'parse ' + testCase[0]); + }); +}; + + +exports['test that the colon test cases can do the same'] = function(assert) { + qsColonTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[0], ';', ':'), + 'parse ' + testCase[0] + ' -> ; :'); + }); +}; + +exports['test the weird objects, that they get parsed properly'] = function(assert) { + qsWeirdObjects.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[1]), + 'parse ' + testCase[1]); + }); +}; + +exports['test non munge test cases'] = function(assert) { + qsNoMungeTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=', false), + 'stringify ' + JSON.stringify(testCase[1]) + ' -> & ='); + }); +}; + +exports['test the nested qs-in-qs case'] = function(assert) { + var f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); + f.q = qs.parse(f.q); + assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }, + 'parse a=b&q=x%3Dy%26y%3Dz'); +}; + +exports['test nested in colon'] = function(assert) { + var f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); + f.q = qs.parse(f.q, ';', ':'); + assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }, + 'parse a:b;q:x%3Ay%3By%3Az -> ; :'); +}; + +exports['test stringifying'] = function(assert) { + qsTestCases.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[2]), + 'stringify ' + JSON.stringify(testCase[2])); + }); + + qsColonTestCases.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':'), + 'stringify ' + JSON.stringify(testCase[2]) + ' -> ; :'); + }); + + qsWeirdObjects.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[0]), + 'stringify ' + JSON.stringify(testCase[0])); + }); +}; + +exports['test stringifying nested'] = function(assert) { + var f = qs.stringify({ + a: 'b', + q: qs.stringify({ + x: 'y', + y: 'z' + }) + }); + assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz', + JSON.stringify({ + a: 'b', + 'qs.stringify -> q': { + x: 'y', + y: 'z' + } + })); + + var threw = false; + try { qs.parse(undefined); } catch(error) { threw = true; } + assert.ok(!threw, "does not throws on undefined"); +}; + +exports['test nested in colon'] = function(assert) { + var f = qs.stringify({ + a: 'b', + q: qs.stringify({ + x: 'y', + y: 'z' + }, ';', ':') + }, ';', ':'); + assert.equal(f, 'a:b;q:x%3Ay%3By%3Az', + 'stringify ' + JSON.stringify({ + a: 'b', + 'qs.stringify -> q': { + x: 'y', + y: 'z' + } + }) + ' -> ; : '); + + + assert.deepEqual({}, qs.parse(), 'parse undefined'); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/tap-index.js b/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/tap-index.js new file mode 100644 index 0000000..70679b3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/querystring-es3/test/tap-index.js @@ -0,0 +1,3 @@ +"use strict"; + +require("retape")(require("./index")) \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/.npmignore b/node_modules/meteor-node-stubs/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/.travis.yml b/node_modules/meteor-node-stubs/node_modules/readable-stream/.travis.yml new file mode 100644 index 0000000..1b82118 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/.travis.yml @@ -0,0 +1,52 @@ +sudo: false +language: node_js +before_install: + - npm install -g npm@2 + - npm install -g npm +notifications: + email: false +matrix: + fast_finish: true + allow_failures: + - env: TASK=browser BROWSER_NAME=ipad BROWSER_VERSION="6.0..latest" + - env: TASK=browser BROWSER_NAME=iphone BROWSER_VERSION="6.0..latest" + include: + - node_js: '0.8' + env: TASK=test + - node_js: '0.10' + env: TASK=test + - node_js: '0.11' + env: TASK=test + - node_js: '0.12' + env: TASK=test + - node_js: 1 + env: TASK=test + - node_js: 2 + env: TASK=test + - node_js: 3 + env: TASK=test + - node_js: 4 + env: TASK=test + - node_js: 5 + env: TASK=test + - node_js: 5 + env: TASK=browser BROWSER_NAME=android BROWSER_VERSION="4.0..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=ie BROWSER_VERSION="9..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=opera BROWSER_VERSION="11..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=chrome BROWSER_VERSION="-3..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=firefox BROWSER_VERSION="-3..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=ipad BROWSER_VERSION="6.0..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=iphone BROWSER_VERSION="6.0..latest" + - node_js: 5 + env: TASK=browser BROWSER_NAME=safari BROWSER_VERSION="5..latest" +script: "npm run $TASK" +env: + global: + - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc= + - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI= diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/readable-stream/.zuul.yml new file mode 100644 index 0000000..96d9cfb --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/.zuul.yml @@ -0,0 +1 @@ +ui: tape diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/LICENSE b/node_modules/meteor-node-stubs/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/README.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/README.md new file mode 100644 index 0000000..86b95a3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/README.md @@ -0,0 +1,36 @@ +# readable-stream + +***Node-core v5.8.0 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) + +```bash +npm install --save readable-stream +``` + +***Node-core streams for userland*** + +This package is a mirror of the Streams2 and Streams3 implementations in +Node-core, including [documentation](doc/stream.markdown). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +# Streams WG Team Members + +* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) <christopher.s.dickinson@gmail.com> + - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org> + - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D +* **Sam Newman** ([@sonewman](https://github.com/sonewman)) <newmansam@outlook.com> +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me> diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/doc/stream.markdown b/node_modules/meteor-node-stubs/node_modules/readable-stream/doc/stream.markdown new file mode 100644 index 0000000..0bc3819 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/doc/stream.markdown @@ -0,0 +1,1760 @@ +# Stream + + Stability: 2 - Stable + +A stream is an abstract interface implemented by various objects in +Node.js. For example a [request to an HTTP server][http-incoming-message] is a +stream, as is [`process.stdout`][]. Streams are readable, writable, or both. All +streams are instances of [`EventEmitter`][]. + +You can load the Stream base classes by doing `require('stream')`. +There are base classes provided for [Readable][] streams, [Writable][] +streams, [Duplex][] streams, and [Transform][] streams. + +This document is split up into 3 sections: + +1. The first section explains the parts of the API that you need to be + aware of to use streams in your programs. +2. The second section explains the parts of the API that you need to + use if you implement your own custom streams yourself. The API is designed to + make this easy for you to do. +3. The third section goes into more depth about how streams work, + including some of the internal mechanisms and functions that you + should probably not modify unless you definitely know what you are + doing. + + +## API for Stream Consumers + + + +Streams can be either [Readable][], [Writable][], or both ([Duplex][]). + +All streams are EventEmitters, but they also have other custom methods +and properties depending on whether they are Readable, Writable, or +Duplex. + +If a stream is both Readable and Writable, then it implements all of +the methods and events. So, a [Duplex][] or [Transform][] stream is +fully described by this API, though their implementation may be +somewhat different. + +It is not necessary to implement Stream interfaces in order to consume +streams in your programs. If you **are** implementing streaming +interfaces in your own program, please also refer to +[API for Stream Implementors][]. + +Almost all Node.js programs, no matter how simple, use Streams in some +way. Here is an example of using Streams in an Node.js program: + +```js +const http = require('http'); + +var server = http.createServer( (req, res) => { + // req is an http.IncomingMessage, which is a Readable Stream + // res is an http.ServerResponse, which is a Writable Stream + + var body = ''; + // we want to get the data as utf8 strings + // If you don't set an encoding, then you'll get Buffer objects + req.setEncoding('utf8'); + + // Readable streams emit 'data' events once a listener is added + req.on('data', (chunk) => { + body += chunk; + }); + + // the end event tells you that you have entire body + req.on('end', () => { + try { + var data = JSON.parse(body); + } catch (er) { + // uh oh! bad json! + res.statusCode = 400; + return res.end(`error: ${er.message}`); + } + + // write back something interesting to the user: + res.write(typeof data); + res.end(); + }); +}); + +server.listen(1337); + +// $ curl localhost:1337 -d '{}' +// object +// $ curl localhost:1337 -d '"foo"' +// string +// $ curl localhost:1337 -d 'not json' +// error: Unexpected token o +``` + +### Class: stream.Duplex + +Duplex streams are streams that implement both the [Readable][] and +[Writable][] interfaces. + +Examples of Duplex streams include: + +* [TCP sockets][] +* [zlib streams][zlib] +* [crypto streams][crypto] + +### Class: stream.Readable + + + +The Readable stream interface is the abstraction for a *source* of +data that you are reading from. In other words, data comes *out* of a +Readable stream. + +A Readable stream will not start emitting data until you indicate that +you are ready to receive it. + +Readable streams have two "modes": a **flowing mode** and a **paused +mode**. When in flowing mode, data is read from the underlying system +and provided to your program as fast as possible. In paused mode, you +must explicitly call [`stream.read()`][stream-read] to get chunks of data out. +Streams start out in paused mode. + +**Note**: If no data event handlers are attached, and there are no +[`stream.pipe()`][] destinations, and the stream is switched into flowing +mode, then data will be lost. + +You can switch to flowing mode by doing any of the following: + +* Adding a [`'data'`][] event handler to listen for data. +* Calling the [`stream.resume()`][stream-resume] method to explicitly open the + flow. +* Calling the [`stream.pipe()`][] method to send the data to a [Writable][]. + +You can switch back to paused mode by doing either of the following: + +* If there are no pipe destinations, by calling the + [`stream.pause()`][stream-pause] method. +* If there are pipe destinations, by removing any [`'data'`][] event + handlers, and removing all pipe destinations by calling the + [`stream.unpipe()`][] method. + +Note that, for backwards compatibility reasons, removing [`'data'`][] +event handlers will **not** automatically pause the stream. Also, if +there are piped destinations, then calling [`stream.pause()`][stream-pause] will +not guarantee that the stream will *remain* paused once those +destinations drain and ask for more data. + +Examples of readable streams include: + +* [HTTP responses, on the client][http-incoming-message] +* [HTTP requests, on the server][http-incoming-message] +* [fs read streams][] +* [zlib streams][zlib] +* [crypto streams][crypto] +* [TCP sockets][] +* [child process stdout and stderr][] +* [`process.stdin`][] + +#### Event: 'close' + +Emitted when the stream and any of its underlying resources (a file +descriptor, for example) have been closed. The event indicates that +no more events will be emitted, and no further computation will occur. + +Not all streams will emit the `'close'` event. + +#### Event: 'data' + +* `chunk` {Buffer|String} The chunk of data. + +Attaching a `'data'` event listener to a stream that has not been +explicitly paused will switch the stream into flowing mode. Data will +then be passed as soon as it is available. + +If you just want to get all the data out of the stream as fast as +possible, this is the best way to do so. + +```js +var readable = getReadableStreamSomehow(); +readable.on('data', (chunk) => { + console.log('got %d bytes of data', chunk.length); +}); +``` + +#### Event: 'end' + +This event fires when there will be no more data to read. + +Note that the `'end'` event **will not fire** unless the data is +completely consumed. This can be done by switching into flowing mode, +or by calling [`stream.read()`][stream-read] repeatedly until you get to the +end. + +```js +var readable = getReadableStreamSomehow(); +readable.on('data', (chunk) => { + console.log('got %d bytes of data', chunk.length); +}); +readable.on('end', () => { + console.log('there will be no more data.'); +}); +``` + +#### Event: 'error' + +* {Error Object} + +Emitted if there was an error receiving data. + +#### Event: 'readable' + +When a chunk of data can be read from the stream, it will emit a +`'readable'` event. + +In some cases, listening for a `'readable'` event will cause some data +to be read into the internal buffer from the underlying system, if it +hadn't already. + +```javascript +var readable = getReadableStreamSomehow(); +readable.on('readable', () => { + // there is some data to read now +}); +``` + +Once the internal buffer is drained, a `'readable'` event will fire +again when more data is available. + +The `'readable'` event is not emitted in the "flowing" mode with the +sole exception of the last one, on end-of-stream. + +The `'readable'` event indicates that the stream has new information: +either new data is available or the end of the stream has been reached. +In the former case, [`stream.read()`][stream-read] will return that data. In the +latter case, [`stream.read()`][stream-read] will return null. For instance, in +the following example, `foo.txt` is an empty file: + +```js +const fs = require('fs'); +var rr = fs.createReadStream('foo.txt'); +rr.on('readable', () => { + console.log('readable:', rr.read()); +}); +rr.on('end', () => { + console.log('end'); +}); +``` + +The output of running this script is: + +``` +$ node test.js +readable: null +end +``` + +#### readable.isPaused() + +* Return: {Boolean} + +This method returns whether or not the `readable` has been **explicitly** +paused by client code (using [`stream.pause()`][stream-pause] without a +corresponding [`stream.resume()`][stream-resume]). + +```js +var readable = new stream.Readable + +readable.isPaused() // === false +readable.pause() +readable.isPaused() // === true +readable.resume() +readable.isPaused() // === false +``` + +#### readable.pause() + +* Return: `this` + +This method will cause a stream in flowing mode to stop emitting +[`'data'`][] events, switching out of flowing mode. Any data that becomes +available will remain in the internal buffer. + +```js +var readable = getReadableStreamSomehow(); +readable.on('data', (chunk) => { + console.log('got %d bytes of data', chunk.length); + readable.pause(); + console.log('there will be no more data for 1 second'); + setTimeout(() => { + console.log('now data will start flowing again'); + readable.resume(); + }, 1000); +}); +``` + +#### readable.pipe(destination[, options]) + +* `destination` {stream.Writable} The destination for writing data +* `options` {Object} Pipe options + * `end` {Boolean} End the writer when the reader ends. Default = `true` + +This method pulls all the data out of a readable stream, and writes it +to the supplied destination, automatically managing the flow so that +the destination is not overwhelmed by a fast readable stream. + +Multiple destinations can be piped to safely. + +```js +var readable = getReadableStreamSomehow(); +var writable = fs.createWriteStream('file.txt'); +// All the data from readable goes into 'file.txt' +readable.pipe(writable); +``` + +This function returns the destination stream, so you can set up pipe +chains like so: + +```js +var r = fs.createReadStream('file.txt'); +var z = zlib.createGzip(); +var w = fs.createWriteStream('file.txt.gz'); +r.pipe(z).pipe(w); +``` + +For example, emulating the Unix `cat` command: + +```js +process.stdin.pipe(process.stdout); +``` + +By default [`stream.end()`][stream-end] is called on the destination when the +source stream emits [`'end'`][], so that `destination` is no longer writable. +Pass `{ end: false }` as `options` to keep the destination stream open. + +This keeps `writer` open so that "Goodbye" can be written at the +end. + +```js +reader.pipe(writer, { end: false }); +reader.on('end', () => { + writer.end('Goodbye\n'); +}); +``` + +Note that [`process.stderr`][] and [`process.stdout`][] are never closed until +the process exits, regardless of the specified options. + +#### readable.read([size]) + +* `size` {Number} Optional argument to specify how much data to read. +* Return {String|Buffer|Null} + +The `read()` method pulls some data out of the internal buffer and +returns it. If there is no data available, then it will return +`null`. + +If you pass in a `size` argument, then it will return that many +bytes. If `size` bytes are not available, then it will return `null`, +unless we've ended, in which case it will return the data remaining +in the buffer. + +If you do not specify a `size` argument, then it will return all the +data in the internal buffer. + +This method should only be called in paused mode. In flowing mode, +this method is called automatically until the internal buffer is +drained. + +```js +var readable = getReadableStreamSomehow(); +readable.on('readable', () => { + var chunk; + while (null !== (chunk = readable.read())) { + console.log('got %d bytes of data', chunk.length); + } +}); +``` + +If this method returns a data chunk, then it will also trigger the +emission of a [`'data'`][] event. + +Note that calling [`stream.read([size])`][stream-read] after the [`'end'`][] +event has been triggered will return `null`. No runtime error will be raised. + +#### readable.resume() + +* Return: `this` + +This method will cause the readable stream to resume emitting [`'data'`][] +events. + +This method will switch the stream into flowing mode. If you do *not* +want to consume the data from a stream, but you *do* want to get to +its [`'end'`][] event, you can call [`stream.resume()`][stream-resume] to open +the flow of data. + +```js +var readable = getReadableStreamSomehow(); +readable.resume(); +readable.on('end', () => { + console.log('got to the end, but did not read anything'); +}); +``` + +#### readable.setEncoding(encoding) + +* `encoding` {String} The encoding to use. +* Return: `this` + +Call this function to cause the stream to return strings of the specified +encoding instead of Buffer objects. For example, if you do +`readable.setEncoding('utf8')`, then the output data will be interpreted as +UTF-8 data, and returned as strings. If you do `readable.setEncoding('hex')`, +then the data will be encoded in hexadecimal string format. + +This properly handles multi-byte characters that would otherwise be +potentially mangled if you simply pulled the Buffers directly and +called [`buf.toString(encoding)`][] on them. If you want to read the data +as strings, always use this method. + +Also you can disable any encoding at all with `readable.setEncoding(null)`. +This approach is very useful if you deal with binary data or with large +multi-byte strings spread out over multiple chunks. + +```js +var readable = getReadableStreamSomehow(); +readable.setEncoding('utf8'); +readable.on('data', (chunk) => { + assert.equal(typeof chunk, 'string'); + console.log('got %d characters of string data', chunk.length); +}); +``` + +#### readable.unpipe([destination]) + +* `destination` {stream.Writable} Optional specific stream to unpipe + +This method will remove the hooks set up for a previous [`stream.pipe()`][] +call. + +If the destination is not specified, then all pipes are removed. + +If the destination is specified, but no pipe is set up for it, then +this is a no-op. + +```js +var readable = getReadableStreamSomehow(); +var writable = fs.createWriteStream('file.txt'); +// All the data from readable goes into 'file.txt', +// but only for the first second +readable.pipe(writable); +setTimeout(() => { + console.log('stop writing to file.txt'); + readable.unpipe(writable); + console.log('manually close the file stream'); + writable.end(); +}, 1000); +``` + +#### readable.unshift(chunk) + +* `chunk` {Buffer|String} Chunk of data to unshift onto the read queue + +This is useful in certain cases where a stream is being consumed by a +parser, which needs to "un-consume" some data that it has +optimistically pulled out of the source, so that the stream can be +passed on to some other party. + +Note that `stream.unshift(chunk)` cannot be called after the [`'end'`][] event +has been triggered; a runtime error will be raised. + +If you find that you must often call `stream.unshift(chunk)` in your +programs, consider implementing a [Transform][] stream instead. (See [API +for Stream Implementors][].) + +```js +// Pull off a header delimited by \n\n +// use unshift() if we get too much +// Call the callback with (error, header, stream) +const StringDecoder = require('string_decoder').StringDecoder; +function parseHeader(stream, callback) { + stream.on('error', callback); + stream.on('readable', onReadable); + var decoder = new StringDecoder('utf8'); + var header = ''; + function onReadable() { + var chunk; + while (null !== (chunk = stream.read())) { + var str = decoder.write(chunk); + if (str.match(/\n\n/)) { + // found the header boundary + var split = str.split(/\n\n/); + header += split.shift(); + var remaining = split.join('\n\n'); + var buf = new Buffer(remaining, 'utf8'); + if (buf.length) + stream.unshift(buf); + stream.removeListener('error', callback); + stream.removeListener('readable', onReadable); + // now the body of the message can be read from the stream. + callback(null, header, stream); + } else { + // still reading the header. + header += str; + } + } + } +} +``` + +Note that, unlike [`stream.push(chunk)`][stream-push], `stream.unshift(chunk)` +will not end the reading process by resetting the internal reading state of the +stream. This can cause unexpected results if `unshift()` is called during a +read (i.e. from within a [`stream._read()`][stream-_read] implementation on a +custom stream). Following the call to `unshift()` with an immediate +[`stream.push('')`][stream-push] will reset the reading state appropriately, +however it is best to simply avoid calling `unshift()` while in the process of +performing a read. + +#### readable.wrap(stream) + +* `stream` {Stream} An "old style" readable stream + +Versions of Node.js prior to v0.10 had streams that did not implement the +entire Streams API as it is today. (See [Compatibility][] for +more information.) + +If you are using an older Node.js library that emits [`'data'`][] events and +has a [`stream.pause()`][stream-pause] method that is advisory only, then you +can use the `wrap()` method to create a [Readable][] stream that uses the old +stream as its data source. + +You will very rarely ever need to call this function, but it exists +as a convenience for interacting with old Node.js programs and libraries. + +For example: + +```js +const OldReader = require('./old-api-module.js').OldReader; +const Readable = require('stream').Readable; +const oreader = new OldReader; +const myReader = new Readable().wrap(oreader); + +myReader.on('readable', () => { + myReader.read(); // etc. +}); +``` + +### Class: stream.Transform + +Transform streams are [Duplex][] streams where the output is in some way +computed from the input. They implement both the [Readable][] and +[Writable][] interfaces. + +Examples of Transform streams include: + +* [zlib streams][zlib] +* [crypto streams][crypto] + +### Class: stream.Writable + + + +The Writable stream interface is an abstraction for a *destination* +that you are writing data *to*. + +Examples of writable streams include: + +* [HTTP requests, on the client][] +* [HTTP responses, on the server][] +* [fs write streams][] +* [zlib streams][zlib] +* [crypto streams][crypto] +* [TCP sockets][] +* [child process stdin][] +* [`process.stdout`][], [`process.stderr`][] + +#### Event: 'drain' + +If a [`stream.write(chunk)`][stream-write] call returns `false`, then the +`'drain'` event will indicate when it is appropriate to begin writing more data +to the stream. + +```js +// Write the data to the supplied writable stream one million times. +// Be attentive to back-pressure. +function writeOneMillionTimes(writer, data, encoding, callback) { + var i = 1000000; + write(); + function write() { + var ok = true; + do { + i -= 1; + if (i === 0) { + // last time! + writer.write(data, encoding, callback); + } else { + // see if we should continue, or wait + // don't pass the callback, because we're not done yet. + ok = writer.write(data, encoding); + } + } while (i > 0 && ok); + if (i > 0) { + // had to stop early! + // write some more once it drains + writer.once('drain', write); + } + } +} +``` + +#### Event: 'error' + +* {Error} + +Emitted if there was an error when writing or piping data. + +#### Event: 'finish' + +When the [`stream.end()`][stream-end] method has been called, and all data has +been flushed to the underlying system, this event is emitted. + +```javascript +var writer = getWritableStreamSomehow(); +for (var i = 0; i < 100; i ++) { + writer.write('hello, #${i}!\n'); +} +writer.end('this is the end\n'); +writer.on('finish', () => { + console.error('all writes are now complete.'); +}); +``` + +#### Event: 'pipe' + +* `src` {stream.Readable} source stream that is piping to this writable + +This is emitted whenever the [`stream.pipe()`][] method is called on a readable +stream, adding this writable to its set of destinations. + +```js +var writer = getWritableStreamSomehow(); +var reader = getReadableStreamSomehow(); +writer.on('pipe', (src) => { + console.error('something is piping into the writer'); + assert.equal(src, reader); +}); +reader.pipe(writer); +``` + +#### Event: 'unpipe' + +* `src` {[Readable][] Stream} The source stream that + [unpiped][`stream.unpipe()`] this writable + +This is emitted whenever the [`stream.unpipe()`][] method is called on a +readable stream, removing this writable from its set of destinations. + +```js +var writer = getWritableStreamSomehow(); +var reader = getReadableStreamSomehow(); +writer.on('unpipe', (src) => { + console.error('something has stopped piping into the writer'); + assert.equal(src, reader); +}); +reader.pipe(writer); +reader.unpipe(writer); +``` + +#### writable.cork() + +Forces buffering of all writes. + +Buffered data will be flushed either at [`stream.uncork()`][] or at +[`stream.end()`][stream-end] call. + +#### writable.end([chunk][, encoding][, callback]) + +* `chunk` {String|Buffer} Optional data to write +* `encoding` {String} The encoding, if `chunk` is a String +* `callback` {Function} Optional callback for when the stream is finished + +Call this method when no more data will be written to the stream. If supplied, +the callback is attached as a listener on the [`'finish'`][] event. + +Calling [`stream.write()`][stream-write] after calling +[`stream.end()`][stream-end] will raise an error. + +```js +// write 'hello, ' and then end with 'world!' +var file = fs.createWriteStream('example.txt'); +file.write('hello, '); +file.end('world!'); +// writing more now is not allowed! +``` + +#### writable.setDefaultEncoding(encoding) + +* `encoding` {String} The new default encoding + +Sets the default encoding for a writable stream. + +#### writable.uncork() + +Flush all data, buffered since [`stream.cork()`][] call. + +#### writable.write(chunk[, encoding][, callback]) + +* `chunk` {String|Buffer} The data to write +* `encoding` {String} The encoding, if `chunk` is a String +* `callback` {Function} Callback for when this chunk of data is flushed +* Returns: {Boolean} `true` if the data was handled completely. + +This method writes some data to the underlying system, and calls the +supplied callback once the data has been fully handled. + +The return value indicates if you should continue writing right now. +If the data had to be buffered internally, then it will return +`false`. Otherwise, it will return `true`. + +This return value is strictly advisory. You MAY continue to write, +even if it returns `false`. However, writes will be buffered in +memory, so it is best not to do this excessively. Instead, wait for +the [`'drain'`][] event before writing more data. + + +## API for Stream Implementors + + + +To implement any sort of stream, the pattern is the same: + +1. Extend the appropriate parent class in your own subclass. (The + [`util.inherits()`][] method is particularly helpful for this.) +2. Call the appropriate parent class constructor in your constructor, + to be sure that the internal mechanisms are set up properly. +3. Implement one or more specific methods, as detailed below. + +The class to extend and the method(s) to implement depend on the sort +of stream class you are writing: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Use-case

+
+

Class

+
+

Method(s) to implement

+
+

Reading only

+
+

[Readable](#stream_class_stream_readable_1)

+
+

[_read][stream-_read]

+
+

Writing only

+
+

[Writable](#stream_class_stream_writable_1)

+
+

[_write][stream-_write], [_writev][stream-_writev]

+
+

Reading and writing

+
+

[Duplex](#stream_class_stream_duplex_1)

+
+

[_read][stream-_read], [_write][stream-_write], [_writev][stream-_writev]

+
+

Operate on written data, then read the result

+
+

[Transform](#stream_class_stream_transform_1)

+
+

[_transform][stream-_transform], [_flush][stream-_flush]

+
+ +In your implementation code, it is very important to never call the methods +described in [API for Stream Consumers][]. Otherwise, you can potentially cause +adverse side effects in programs that consume your streaming interfaces. + +### Class: stream.Duplex + + + +A "duplex" stream is one that is both Readable and Writable, such as a TCP +socket connection. + +Note that `stream.Duplex` is an abstract class designed to be extended +with an underlying implementation of the [`stream._read(size)`][stream-_read] +and [`stream._write(chunk, encoding, callback)`][stream-_write] methods as you +would with a Readable or Writable stream class. + +Since JavaScript doesn't have multiple prototypal inheritance, this class +prototypally inherits from Readable, and then parasitically from Writable. It is +thus up to the user to implement both the low-level +[`stream._read(n)`][stream-_read] method as well as the low-level +[`stream._write(chunk, encoding, callback)`][stream-_write] method on extension +duplex classes. + +#### new stream.Duplex(options) + +* `options` {Object} Passed to both Writable and Readable + constructors. Also has the following fields: + * `allowHalfOpen` {Boolean} Default = `true`. If set to `false`, then + the stream will automatically end the readable side when the + writable side ends and vice versa. + * `readableObjectMode` {Boolean} Default = `false`. Sets `objectMode` + for readable side of the stream. Has no effect if `objectMode` + is `true`. + * `writableObjectMode` {Boolean} Default = `false`. Sets `objectMode` + for writable side of the stream. Has no effect if `objectMode` + is `true`. + +In classes that extend the Duplex class, make sure to call the +constructor so that the buffering settings can be properly +initialized. + +### Class: stream.PassThrough + +This is a trivial implementation of a [Transform][] stream that simply +passes the input bytes across to the output. Its purpose is mainly +for examples and testing, but there are occasionally use cases where +it can come in handy as a building block for novel sorts of streams. + +### Class: stream.Readable + + + +`stream.Readable` is an abstract class designed to be extended with an +underlying implementation of the [`stream._read(size)`][stream-_read] method. + +Please see [API for Stream Consumers][] for how to consume +streams in your programs. What follows is an explanation of how to +implement Readable streams in your programs. + +#### new stream.Readable([options]) + +* `options` {Object} + * `highWaterMark` {Number} The maximum number of bytes to store in + the internal buffer before ceasing to read from the underlying + resource. Default = `16384` (16kb), or `16` for `objectMode` streams + * `encoding` {String} If specified, then buffers will be decoded to + strings using the specified encoding. Default = `null` + * `objectMode` {Boolean} Whether this stream should behave + as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns + a single value instead of a Buffer of size n. Default = `false` + * `read` {Function} Implementation for the [`stream._read()`][stream-_read] + method. + +In classes that extend the Readable class, make sure to call the +Readable constructor so that the buffering settings can be properly +initialized. + +#### readable.\_read(size) + +* `size` {Number} Number of bytes to read asynchronously + +Note: **Implement this method, but do NOT call it directly.** + +This method is prefixed with an underscore because it is internal to the +class that defines it and should only be called by the internal Readable +class methods. All Readable stream implementations must provide a \_read +method to fetch data from the underlying resource. + +When `_read()` is called, if data is available from the resource, the `_read()` +implementation should start pushing that data into the read queue by calling +[`this.push(dataChunk)`][stream-push]. `_read()` should continue reading from +the resource and pushing data until push returns `false`, at which point it +should stop reading from the resource. Only when `_read()` is called again after +it has stopped should it start reading more data from the resource and pushing +that data onto the queue. + +Note: once the `_read()` method is called, it will not be called again until +the [`stream.push()`][stream-push] method is called. + +The `size` argument is advisory. Implementations where a "read" is a +single call that returns data can use this to know how much data to +fetch. Implementations where that is not relevant, such as TCP or +TLS, may ignore this argument, and simply provide data whenever it +becomes available. There is no need, for example to "wait" until +`size` bytes are available before calling [`stream.push(chunk)`][stream-push]. + +#### readable.push(chunk[, encoding]) + + +* `chunk` {Buffer|Null|String} Chunk of data to push into the read queue +* `encoding` {String} Encoding of String chunks. Must be a valid + Buffer encoding, such as `'utf8'` or `'ascii'` +* return {Boolean} Whether or not more pushes should be performed + +Note: **This method should be called by Readable implementors, NOT +by consumers of Readable streams.** + +If a value other than null is passed, The `push()` method adds a chunk of data +into the queue for subsequent stream processors to consume. If `null` is +passed, it signals the end of the stream (EOF), after which no more data +can be written. + +The data added with `push()` can be pulled out by calling the +[`stream.read()`][stream-read] method when the [`'readable'`][] event fires. + +This API is designed to be as flexible as possible. For example, +you may be wrapping a lower-level source which has some sort of +pause/resume mechanism, and a data callback. In those cases, you +could wrap the low-level source object by doing something like this: + +```js +// source is an object with readStop() and readStart() methods, +// and an `ondata` member that gets called when it has data, and +// an `onend` member that gets called when the data is over. + +util.inherits(SourceWrapper, Readable); + +function SourceWrapper(options) { + Readable.call(this, options); + + this._source = getLowlevelSourceObject(); + + // Every time there's data, we push it into the internal buffer. + this._source.ondata = (chunk) => { + // if push() returns false, then we need to stop reading from source + if (!this.push(chunk)) + this._source.readStop(); + }; + + // When the source ends, we push the EOF-signaling `null` chunk + this._source.onend = () => { + this.push(null); + }; +} + +// _read will be called when the stream wants to pull more data in +// the advisory size argument is ignored in this case. +SourceWrapper.prototype._read = function(size) { + this._source.readStart(); +}; +``` + +#### Example: A Counting Stream + + + +This is a basic example of a Readable stream. It emits the numerals +from 1 to 1,000,000 in ascending order, and then ends. + +```js +const Readable = require('stream').Readable; +const util = require('util'); +util.inherits(Counter, Readable); + +function Counter(opt) { + Readable.call(this, opt); + this._max = 1000000; + this._index = 1; +} + +Counter.prototype._read = function() { + var i = this._index++; + if (i > this._max) + this.push(null); + else { + var str = '' + i; + var buf = new Buffer(str, 'ascii'); + this.push(buf); + } +}; +``` + +#### Example: SimpleProtocol v1 (Sub-optimal) + +This is similar to the `parseHeader` function described +[here](#stream_readable_unshift_chunk), but implemented as a custom stream. +Also, note that this implementation does not convert the incoming data to a +string. + +However, this would be better implemented as a [Transform][] stream. See +[SimpleProtocol v2][] for a better implementation. + +```js +// A parser for a simple data protocol. +// The "header" is a JSON object, followed by 2 \n characters, and +// then a message body. +// +// NOTE: This can be done more simply as a Transform stream! +// Using Readable directly for this is sub-optimal. See the +// alternative example below under the Transform section. + +const Readable = require('stream').Readable; +const util = require('util'); + +util.inherits(SimpleProtocol, Readable); + +function SimpleProtocol(source, options) { + if (!(this instanceof SimpleProtocol)) + return new SimpleProtocol(source, options); + + Readable.call(this, options); + this._inBody = false; + this._sawFirstCr = false; + + // source is a readable stream, such as a socket or file + this._source = source; + + var self = this; + source.on('end', () => { + self.push(null); + }); + + // give it a kick whenever the source is readable + // read(0) will not consume any bytes + source.on('readable', () => { + self.read(0); + }); + + this._rawHeader = []; + this.header = null; +} + +SimpleProtocol.prototype._read = function(n) { + if (!this._inBody) { + var chunk = this._source.read(); + + // if the source doesn't have data, we don't have data yet. + if (chunk === null) + return this.push(''); + + // check if the chunk has a \n\n + var split = -1; + for (var i = 0; i < chunk.length; i++) { + if (chunk[i] === 10) { // '\n' + if (this._sawFirstCr) { + split = i; + break; + } else { + this._sawFirstCr = true; + } + } else { + this._sawFirstCr = false; + } + } + + if (split === -1) { + // still waiting for the \n\n + // stash the chunk, and try again. + this._rawHeader.push(chunk); + this.push(''); + } else { + this._inBody = true; + var h = chunk.slice(0, split); + this._rawHeader.push(h); + var header = Buffer.concat(this._rawHeader).toString(); + try { + this.header = JSON.parse(header); + } catch (er) { + this.emit('error', new Error('invalid simple protocol data')); + return; + } + // now, because we got some extra data, unshift the rest + // back into the read queue so that our consumer will see it. + var b = chunk.slice(split); + this.unshift(b); + // calling unshift by itself does not reset the reading state + // of the stream; since we're inside _read, doing an additional + // push('') will reset the state appropriately. + this.push(''); + + // and let them know that we are done parsing the header. + this.emit('header', this.header); + } + } else { + // from there on, just provide the data to our consumer. + // careful not to push(null), since that would indicate EOF. + var chunk = this._source.read(); + if (chunk) this.push(chunk); + } +}; + +// Usage: +// var parser = new SimpleProtocol(source); +// Now parser is a readable stream that will emit 'header' +// with the parsed header data. +``` + +### Class: stream.Transform + +A "transform" stream is a duplex stream where the output is causally +connected in some way to the input, such as a [zlib][] stream or a +[crypto][] stream. + +There is no requirement that the output be the same size as the input, +the same number of chunks, or arrive at the same time. For example, a +Hash stream will only ever have a single chunk of output which is +provided when the input is ended. A zlib stream will produce output +that is either much smaller or much larger than its input. + +Rather than implement the [`stream._read()`][stream-_read] and +[`stream._write()`][stream-_write] methods, Transform classes must implement the +[`stream._transform()`][stream-_transform] method, and may optionally +also implement the [`stream._flush()`][stream-_flush] method. (See below.) + +#### new stream.Transform([options]) + +* `options` {Object} Passed to both Writable and Readable + constructors. Also has the following fields: + * `transform` {Function} Implementation for the + [`stream._transform()`][stream-_transform] method. + * `flush` {Function} Implementation for the [`stream._flush()`][stream-_flush] + method. + +In classes that extend the Transform class, make sure to call the +constructor so that the buffering settings can be properly +initialized. + +#### Events: 'finish' and 'end' + +The [`'finish'`][] and [`'end'`][] events are from the parent Writable +and Readable classes respectively. The `'finish'` event is fired after +[`stream.end()`][stream-end] is called and all chunks have been processed by +[`stream._transform()`][stream-_transform], `'end'` is fired after all data has +been output which is after the callback in [`stream._flush()`][stream-_flush] +has been called. + +#### transform.\_flush(callback) + +* `callback` {Function} Call this function (optionally with an error + argument) when you are done flushing any remaining data. + +Note: **This function MUST NOT be called directly.** It MAY be implemented +by child classes, and if so, will be called by the internal Transform +class methods only. + +In some cases, your transform operation may need to emit a bit more +data at the end of the stream. For example, a `Zlib` compression +stream will store up some internal state so that it can optimally +compress the output. At the end, however, it needs to do the best it +can with what is left, so that the data will be complete. + +In those cases, you can implement a `_flush()` method, which will be +called at the very end, after all the written data is consumed, but +before emitting [`'end'`][] to signal the end of the readable side. Just +like with [`stream._transform()`][stream-_transform], call +`transform.push(chunk)` zero or more times, as appropriate, and call `callback` +when the flush operation is complete. + +This method is prefixed with an underscore because it is internal to +the class that defines it, and should not be called directly by user +programs. However, you **are** expected to override this method in +your own extension classes. + +#### transform.\_transform(chunk, encoding, callback) + +* `chunk` {Buffer|String} The chunk to be transformed. Will **always** + be a buffer unless the `decodeStrings` option was set to `false`. +* `encoding` {String} If the chunk is a string, then this is the + encoding type. If chunk is a buffer, then this is the special + value - 'buffer', ignore it in this case. +* `callback` {Function} Call this function (optionally with an error + argument and data) when you are done processing the supplied chunk. + +Note: **This function MUST NOT be called directly.** It should be +implemented by child classes, and called by the internal Transform +class methods only. + +All Transform stream implementations must provide a `_transform()` +method to accept input and produce output. + +`_transform()` should do whatever has to be done in this specific +Transform class, to handle the bytes being written, and pass them off +to the readable portion of the interface. Do asynchronous I/O, +process things, and so on. + +Call `transform.push(outputChunk)` 0 or more times to generate output +from this input chunk, depending on how much data you want to output +as a result of this chunk. + +Call the callback function only when the current chunk is completely +consumed. Note that there may or may not be output as a result of any +particular input chunk. If you supply a second argument to the callback +it will be passed to the push method. In other words the following are +equivalent: + +```js +transform.prototype._transform = function (data, encoding, callback) { + this.push(data); + callback(); +}; + +transform.prototype._transform = function (data, encoding, callback) { + callback(null, data); +}; +``` + +This method is prefixed with an underscore because it is internal to +the class that defines it, and should not be called directly by user +programs. However, you **are** expected to override this method in +your own extension classes. + +#### Example: `SimpleProtocol` parser v2 + +The example [here](#stream_example_simpleprotocol_v1_sub_optimal) of a simple +protocol parser can be implemented simply by using the higher level +[Transform][] stream class, similar to the `parseHeader` and `SimpleProtocol +v1` examples. + +In this example, rather than providing the input as an argument, it +would be piped into the parser, which is a more idiomatic Node.js stream +approach. + +```javascript +const util = require('util'); +const Transform = require('stream').Transform; +util.inherits(SimpleProtocol, Transform); + +function SimpleProtocol(options) { + if (!(this instanceof SimpleProtocol)) + return new SimpleProtocol(options); + + Transform.call(this, options); + this._inBody = false; + this._sawFirstCr = false; + this._rawHeader = []; + this.header = null; +} + +SimpleProtocol.prototype._transform = function(chunk, encoding, done) { + if (!this._inBody) { + // check if the chunk has a \n\n + var split = -1; + for (var i = 0; i < chunk.length; i++) { + if (chunk[i] === 10) { // '\n' + if (this._sawFirstCr) { + split = i; + break; + } else { + this._sawFirstCr = true; + } + } else { + this._sawFirstCr = false; + } + } + + if (split === -1) { + // still waiting for the \n\n + // stash the chunk, and try again. + this._rawHeader.push(chunk); + } else { + this._inBody = true; + var h = chunk.slice(0, split); + this._rawHeader.push(h); + var header = Buffer.concat(this._rawHeader).toString(); + try { + this.header = JSON.parse(header); + } catch (er) { + this.emit('error', new Error('invalid simple protocol data')); + return; + } + // and let them know that we are done parsing the header. + this.emit('header', this.header); + + // now, because we got some extra data, emit this first. + this.push(chunk.slice(split)); + } + } else { + // from there on, just provide the data to our consumer as-is. + this.push(chunk); + } + done(); +}; + +// Usage: +// var parser = new SimpleProtocol(); +// source.pipe(parser) +// Now parser is a readable stream that will emit 'header' +// with the parsed header data. +``` + +### Class: stream.Writable + + + +`stream.Writable` is an abstract class designed to be extended with an +underlying implementation of the +[`stream._write(chunk, encoding, callback)`][stream-_write] method. + +Please see [API for Stream Consumers][] for how to consume +writable streams in your programs. What follows is an explanation of +how to implement Writable streams in your programs. + +#### new stream.Writable([options]) + +* `options` {Object} + * `highWaterMark` {Number} Buffer level when + [`stream.write()`][stream-write] starts returning `false`. Default = `16384` + (16kb), or `16` for `objectMode` streams. + * `decodeStrings` {Boolean} Whether or not to decode strings into + Buffers before passing them to [`stream._write()`][stream-_write]. + Default = `true` + * `objectMode` {Boolean} Whether or not the + [`stream.write(anyObj)`][stream-write] is a valid operation. If set you can + write arbitrary data instead of only `Buffer` / `String` data. + Default = `false` + * `write` {Function} Implementation for the + [`stream._write()`][stream-_write] method. + * `writev` {Function} Implementation for the + [`stream._writev()`][stream-_writev] method. + +In classes that extend the Writable class, make sure to call the +constructor so that the buffering settings can be properly +initialized. + +#### writable.\_write(chunk, encoding, callback) + +* `chunk` {Buffer|String} The chunk to be written. Will **always** + be a buffer unless the `decodeStrings` option was set to `false`. +* `encoding` {String} If the chunk is a string, then this is the + encoding type. If chunk is a buffer, then this is the special + value - 'buffer', ignore it in this case. +* `callback` {Function} Call this function (optionally with an error + argument) when you are done processing the supplied chunk. + +All Writable stream implementations must provide a +[`stream._write()`][stream-_write] method to send data to the underlying +resource. + +Note: **This function MUST NOT be called directly.** It should be +implemented by child classes, and called by the internal Writable +class methods only. + +Call the callback using the standard `callback(error)` pattern to +signal that the write completed successfully or with an error. + +If the `decodeStrings` flag is set in the constructor options, then +`chunk` may be a string rather than a Buffer, and `encoding` will +indicate the sort of string that it is. This is to support +implementations that have an optimized handling for certain string +data encodings. If you do not explicitly set the `decodeStrings` +option to `false`, then you can safely ignore the `encoding` argument, +and assume that `chunk` will always be a Buffer. + +This method is prefixed with an underscore because it is internal to +the class that defines it, and should not be called directly by user +programs. However, you **are** expected to override this method in +your own extension classes. + +#### writable.\_writev(chunks, callback) + +* `chunks` {Array} The chunks to be written. Each chunk has following + format: `{ chunk: ..., encoding: ... }`. +* `callback` {Function} Call this function (optionally with an error + argument) when you are done processing the supplied chunks. + +Note: **This function MUST NOT be called directly.** It may be +implemented by child classes, and called by the internal Writable +class methods only. + +This function is completely optional to implement. In most cases it is +unnecessary. If implemented, it will be called with all the chunks +that are buffered in the write queue. + + +## Simplified Constructor API + + + +In simple cases there is now the added benefit of being able to construct a +stream without inheritance. + +This can be done by passing the appropriate methods as constructor options: + +Examples: + +### Duplex + +```js +var duplex = new stream.Duplex({ + read: function(n) { + // sets this._read under the hood + + // push data onto the read queue, passing null + // will signal the end of the stream (EOF) + this.push(chunk); + }, + write: function(chunk, encoding, next) { + // sets this._write under the hood + + // An optional error can be passed as the first argument + next() + } +}); + +// or + +var duplex = new stream.Duplex({ + read: function(n) { + // sets this._read under the hood + + // push data onto the read queue, passing null + // will signal the end of the stream (EOF) + this.push(chunk); + }, + writev: function(chunks, next) { + // sets this._writev under the hood + + // An optional error can be passed as the first argument + next() + } +}); +``` + +### Readable + +```js +var readable = new stream.Readable({ + read: function(n) { + // sets this._read under the hood + + // push data onto the read queue, passing null + // will signal the end of the stream (EOF) + this.push(chunk); + } +}); +``` + +### Transform + +```js +var transform = new stream.Transform({ + transform: function(chunk, encoding, next) { + // sets this._transform under the hood + + // generate output as many times as needed + // this.push(chunk); + + // call when the current chunk is consumed + next(); + }, + flush: function(done) { + // sets this._flush under the hood + + // generate output as many times as needed + // this.push(chunk); + + done(); + } +}); +``` + +### Writable + +```js +var writable = new stream.Writable({ + write: function(chunk, encoding, next) { + // sets this._write under the hood + + // An optional error can be passed as the first argument + next() + } +}); + +// or + +var writable = new stream.Writable({ + writev: function(chunks, next) { + // sets this._writev under the hood + + // An optional error can be passed as the first argument + next() + } +}); +``` + +## Streams: Under the Hood + + + +### Buffering + + + +Both Writable and Readable streams will buffer data on an internal +object which can be retrieved from `_writableState.getBuffer()` or +`_readableState.buffer`, respectively. + +The amount of data that will potentially be buffered depends on the +`highWaterMark` option which is passed into the constructor. + +Buffering in Readable streams happens when the implementation calls +[`stream.push(chunk)`][stream-push]. If the consumer of the Stream does not +call [`stream.read()`][stream-read], then the data will sit in the internal +queue until it is consumed. + +Buffering in Writable streams happens when the user calls +[`stream.write(chunk)`][stream-write] repeatedly, even when it returns `false`. + +The purpose of streams, especially with the [`stream.pipe()`][] method, is to +limit the buffering of data to acceptable levels, so that sources and +destinations of varying speed will not overwhelm the available memory. + +### Compatibility with Older Node.js Versions + + + +In versions of Node.js prior to v0.10, the Readable stream interface was +simpler, but also less powerful and less useful. + +* Rather than waiting for you to call the [`stream.read()`][stream-read] method, + [`'data'`][] events would start emitting immediately. If you needed to do + some I/O to decide how to handle data, then you had to store the chunks + in some kind of buffer so that they would not be lost. +* The [`stream.pause()`][stream-pause] method was advisory, rather than + guaranteed. This meant that you still had to be prepared to receive + [`'data'`][] events even when the stream was in a paused state. + +In Node.js v0.10, the [Readable][] class was added. +For backwards compatibility with older Node.js programs, Readable streams +switch into "flowing mode" when a [`'data'`][] event handler is added, or +when the [`stream.resume()`][stream-resume] method is called. The effect is +that, even if you are not using the new [`stream.read()`][stream-read] method +and [`'readable'`][] event, you no longer have to worry about losing +[`'data'`][] chunks. + +Most programs will continue to function normally. However, this +introduces an edge case in the following conditions: + +* No [`'data'`][] event handler is added. +* The [`stream.resume()`][stream-resume] method is never called. +* The stream is not piped to any writable destination. + +For example, consider the following code: + +```js +// WARNING! BROKEN! +net.createServer((socket) => { + + // we add an 'end' method, but never consume the data + socket.on('end', () => { + // It will never get here. + socket.end('I got your message (but didnt read it)\n'); + }); + +}).listen(1337); +``` + +In versions of Node.js prior to v0.10, the incoming message data would be +simply discarded. However, in Node.js v0.10 and beyond, +the socket will remain paused forever. + +The workaround in this situation is to call the +[`stream.resume()`][stream-resume] method to start the flow of data: + +```js +// Workaround +net.createServer((socket) => { + + socket.on('end', () => { + socket.end('I got your message (but didnt read it)\n'); + }); + + // start the flow of data, discarding it. + socket.resume(); + +}).listen(1337); +``` + +In addition to new Readable streams switching into flowing mode, +pre-v0.10 style streams can be wrapped in a Readable class using the +[`stream.wrap()`][] method. + + +### Object Mode + + + +Normally, Streams operate on Strings and Buffers exclusively. + +Streams that are in **object mode** can emit generic JavaScript values +other than Buffers and Strings. + +A Readable stream in object mode will always return a single item from +a call to [`stream.read(size)`][stream-read], regardless of what the size +argument is. + +A Writable stream in object mode will always ignore the `encoding` +argument to [`stream.write(data, encoding)`][stream-write]. + +The special value `null` still retains its special value for object +mode streams. That is, for object mode readable streams, `null` as a +return value from [`stream.read()`][stream-read] indicates that there is no more +data, and [`stream.push(null)`][stream-push] will signal the end of stream data +(`EOF`). + +No streams in Node.js core are object mode streams. This pattern is only +used by userland streaming libraries. + +You should set `objectMode` in your stream child class constructor on +the options object. Setting `objectMode` mid-stream is not safe. + +For Duplex streams `objectMode` can be set exclusively for readable or +writable side with `readableObjectMode` and `writableObjectMode` +respectively. These options can be used to implement parsers and +serializers with Transform streams. + +```js +const util = require('util'); +const StringDecoder = require('string_decoder').StringDecoder; +const Transform = require('stream').Transform; +util.inherits(JSONParseStream, Transform); + +// Gets \n-delimited JSON string data, and emits the parsed objects +function JSONParseStream() { + if (!(this instanceof JSONParseStream)) + return new JSONParseStream(); + + Transform.call(this, { readableObjectMode : true }); + + this._buffer = ''; + this._decoder = new StringDecoder('utf8'); +} + +JSONParseStream.prototype._transform = function(chunk, encoding, cb) { + this._buffer += this._decoder.write(chunk); + // split on newlines + var lines = this._buffer.split(/\r?\n/); + // keep the last partial line buffered + this._buffer = lines.pop(); + for (var l = 0; l < lines.length; l++) { + var line = lines[l]; + try { + var obj = JSON.parse(line); + } catch (er) { + this.emit('error', er); + return; + } + // push the parsed object out to the readable consumer + this.push(obj); + } + cb(); +}; + +JSONParseStream.prototype._flush = function(cb) { + // Just handle any leftover + var rem = this._buffer.trim(); + if (rem) { + try { + var obj = JSON.parse(rem); + } catch (er) { + this.emit('error', er); + return; + } + // push the parsed object out to the readable consumer + this.push(obj); + } + cb(); +}; +``` + +### `stream.read(0)` + +There are some cases where you want to trigger a refresh of the +underlying readable stream mechanisms, without actually consuming any +data. In that case, you can call `stream.read(0)`, which will always +return null. + +If the internal read buffer is below the `highWaterMark`, and the +stream is not currently reading, then calling `stream.read(0)` will trigger +a low-level [`stream._read()`][stream-_read] call. + +There is almost never a need to do this. However, you will see some +cases in Node.js's internals where this is done, particularly in the +Readable stream class internals. + +### `stream.push('')` + +Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an +interesting side effect. Because it *is* a call to +[`stream.push()`][stream-push], it will end the `reading` process. However, it +does *not* add any data to the readable buffer, so there's nothing for +a user to consume. + +Very rarely, there are cases where you have no data to provide now, +but the consumer of your stream (or, perhaps, another bit of your own +code) will know when to check again, by calling [`stream.read(0)`][stream-read]. +In those cases, you *may* call `stream.push('')`. + +So far, the only use case for this functionality is in the +[`tls.CryptoStream`][] class, which is deprecated in Node.js/io.js v1.0. If you +find that you have to use `stream.push('')`, please consider another +approach, because it almost certainly indicates that something is +horribly wrong. + +[`'data'`]: #stream_event_data +[`'drain'`]: #stream_event_drain +[`'end'`]: #stream_event_end +[`'finish'`]: #stream_event_finish +[`'readable'`]: #stream_event_readable +[`buf.toString(encoding)`]: https://nodejs.org/docs/v5.8.0/api/buffer.html#buffer_buf_tostring_encoding_start_end +[`EventEmitter`]: https://nodejs.org/docs/v5.8.0/api/events.html#events_class_eventemitter +[`process.stderr`]: https://nodejs.org/docs/v5.8.0/api/process.html#process_process_stderr +[`process.stdin`]: https://nodejs.org/docs/v5.8.0/api/process.html#process_process_stdin +[`process.stdout`]: https://nodejs.org/docs/v5.8.0/api/process.html#process_process_stdout +[`stream.cork()`]: #stream_writable_cork +[`stream.pipe()`]: #stream_readable_pipe_destination_options +[`stream.uncork()`]: #stream_writable_uncork +[`stream.unpipe()`]: #stream_readable_unpipe_destination +[`stream.wrap()`]: #stream_readable_wrap_stream +[`tls.CryptoStream`]: https://nodejs.org/docs/v5.8.0/api/tls.html#tls_class_cryptostream +[`util.inherits()`]: https://nodejs.org/docs/v5.8.0/api/util.html#util_util_inherits_constructor_superconstructor +[API for Stream Consumers]: #stream_api_for_stream_consumers +[API for Stream Implementors]: #stream_api_for_stream_implementors +[child process stdin]: https://nodejs.org/docs/v5.8.0/api/child_process.html#child_process_child_stdin +[child process stdout and stderr]: https://nodejs.org/docs/v5.8.0/api/child_process.html#child_process_child_stdout +[Compatibility]: #stream_compatibility_with_older_node_js_versions +[crypto]: crypto.html +[Duplex]: #stream_class_stream_duplex +[fs read streams]: https://nodejs.org/docs/v5.8.0/api/fs.html#fs_class_fs_readstream +[fs write streams]: https://nodejs.org/docs/v5.8.0/api/fs.html#fs_class_fs_writestream +[HTTP requests, on the client]: https://nodejs.org/docs/v5.8.0/api/http.html#http_class_http_clientrequest +[HTTP responses, on the server]: https://nodejs.org/docs/v5.8.0/api/http.html#http_class_http_serverresponse +[http-incoming-message]: https://nodejs.org/docs/v5.8.0/api/http.html#http_class_http_incomingmessage +[Object mode]: #stream_object_mode +[Readable]: #stream_class_stream_readable +[SimpleProtocol v2]: #stream_example_simpleprotocol_parser_v2 +[stream-_flush]: #stream_transform_flush_callback +[stream-_read]: #stream_readable_read_size_1 +[stream-_transform]: #stream_transform_transform_chunk_encoding_callback +[stream-_write]: #stream_writable_write_chunk_encoding_callback_1 +[stream-_writev]: #stream_writable_writev_chunks_callback +[stream-end]: #stream_writable_end_chunk_encoding_callback +[stream-pause]: #stream_readable_pause +[stream-push]: #stream_readable_push_chunk_encoding +[stream-read]: #stream_readable_read_size +[stream-resume]: #stream_readable_resume +[stream-write]: #stream_writable_write_chunk_encoding_callback +[TCP sockets]: https://nodejs.org/docs/v5.8.0/api/net.html#net_class_net_socket +[Transform]: #stream_class_stream_transform +[Writable]: #stream_class_stream_writable +[zlib]: zlib.html diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md new file mode 100644 index 0000000..83275f1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md @@ -0,0 +1,60 @@ +# streams WG Meeting 2015-01-30 + +## Links + +* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg +* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106 +* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/ + +## Agenda + +Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting. + +* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105) +* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101) +* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102) +* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99) + +## Minutes + +### adopt a charter + +* group: +1's all around + +### What versioning scheme should be adopted? +* group: +1’s 3.0.0 +* domenic+group: pulling in patches from other sources where appropriate +* mikeal: version independently, suggesting versions for io.js +* mikeal+domenic: work with TC to notify in advance of changes +simpler stream creation + +### streamline creation of streams +* sam: streamline creation of streams +* domenic: nice simple solution posted + but, we lose the opportunity to change the model + may not be backwards incompatible (double check keys) + + **action item:** domenic will check + +### remove implicit flowing of streams on(‘data’) +* add isFlowing / isPaused +* mikeal: worrying that we’re documenting polyfill methods – confuses users +* domenic: more reflective API is probably good, with warning labels for users +* new section for mad scientists (reflective stream access) +* calvin: name the “third state” +* mikeal: maybe borrow the name from whatwg? +* domenic: we’re missing the “third state” +* consensus: kind of difficult to name the third state +* mikeal: figure out differences in states / compat +* mathias: always flow on data – eliminates third state + * explore what it breaks + +**action items:** +* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream) +* ask rod/build for infrastructure +* **chris**: explore the “flow on data” approach +* add isPaused/isFlowing +* add new docs section +* move isPaused to that section + + diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/duplex.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..736693b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,75 @@ +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..d06f71f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,26 @@ +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..54a9d5c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,880 @@ +'use strict'; + +module.exports = Readable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var isArray = require('isarray'); +/**/ + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events'); + +/**/ +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = undefined; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +var Duplex; +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +var Duplex; +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) return 0; + + if (state.objectMode) return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) return state.buffer[0].length;else return state.length; + } + + if (n <= 0) return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else { + return state.length; + } + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + var state = this._readableState; + var nOrig = n; + + if (typeof n !== 'number' || n > 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } + + if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (doRead && !state.reading) n = howMuchToRead(nOrig, state); + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended && state.length === 0) endReadable(this); + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + if (false === ret) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + if (state.pipesCount === 1 && state.pipes[0] === dest && src.listenerCount('data') === 1 && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) dest.on('error', onerror);else if (isArray(dest._events.error)) dest._events.error.unshift(onerror);else dest._events.error = [onerror, dest._events.error]; + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + // If listening to data, and it has not explicitly been paused, + // then call resume to start the flow of data on the next tick. + if (ev === 'data' && false !== this._readableState.flowing) { + this.resume(); + } + + if (ev === 'readable' && !this._readableState.endEmitted) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + if (state.flowing) { + do { + var chunk = stream.read(); + } while (null !== chunk && state.flowing); + } +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) return null; + + if (length === 0) ret = null;else if (objectMode) ret = list.shift();else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) ret = list.join('');else if (list.length === 1) ret = list[0];else ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) ret = '';else ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) ret += buf.slice(0, cpy);else buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) list[0] = buf.slice(cpy);else list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..625cdc1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,180 @@ +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..95916c9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,516 @@ +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/**/ + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; + +util.inherits(Writable, Stream); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +var Duplex; +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // create the two objects needed to store the corked requests + // they are not a linked list, as no new elements are inserted in there + this.corkedRequestsFree = new CorkedRequest(this); + this.corkedRequestsFree.next = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + } catch (_) {} +})(); + +var Duplex; +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/LICENSE b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/LICENSE new file mode 100644 index 0000000..d8d7f94 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/README.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/float.patch b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..ff4c851 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/package.json b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..f4ea518 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,43 @@ +{ + "name": "core-util-is", + "version": "1.0.2", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "scripts": { + "test": "tap test.js" + }, + "devDependencies": { + "tap": "^2.3.0" + }, + "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "_id": "core-util-is@1.0.2", + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "_from": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/test.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/test.js new file mode 100644 index 0000000..1a490c6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/core-util-is/test.js @@ -0,0 +1,68 @@ +var assert = require('tap'); + +var t = require('./lib/util'); + +assert.equal(t.isArray([]), true); +assert.equal(t.isArray({}), false); + +assert.equal(t.isBoolean(null), false); +assert.equal(t.isBoolean(true), true); +assert.equal(t.isBoolean(false), true); + +assert.equal(t.isNull(null), true); +assert.equal(t.isNull(undefined), false); +assert.equal(t.isNull(false), false); +assert.equal(t.isNull(), false); + +assert.equal(t.isNullOrUndefined(null), true); +assert.equal(t.isNullOrUndefined(undefined), true); +assert.equal(t.isNullOrUndefined(false), false); +assert.equal(t.isNullOrUndefined(), true); + +assert.equal(t.isNumber(null), false); +assert.equal(t.isNumber('1'), false); +assert.equal(t.isNumber(1), true); + +assert.equal(t.isString(null), false); +assert.equal(t.isString('1'), true); +assert.equal(t.isString(1), false); + +assert.equal(t.isSymbol(null), false); +assert.equal(t.isSymbol('1'), false); +assert.equal(t.isSymbol(1), false); +assert.equal(t.isSymbol(Symbol()), true); + +assert.equal(t.isUndefined(null), false); +assert.equal(t.isUndefined(undefined), true); +assert.equal(t.isUndefined(false), false); +assert.equal(t.isUndefined(), true); + +assert.equal(t.isRegExp(null), false); +assert.equal(t.isRegExp('1'), false); +assert.equal(t.isRegExp(new RegExp()), true); + +assert.equal(t.isObject({}), true); +assert.equal(t.isObject([]), true); +assert.equal(t.isObject(new RegExp()), true); +assert.equal(t.isObject(new Date()), true); + +assert.equal(t.isDate(null), false); +assert.equal(t.isDate('1'), false); +assert.equal(t.isDate(new Date()), true); + +assert.equal(t.isError(null), false); +assert.equal(t.isError({ err: true }), false); +assert.equal(t.isError(new Error()), true); + +assert.equal(t.isFunction(null), false); +assert.equal(t.isFunction({ }), false); +assert.equal(t.isFunction(function() {}), true); + +assert.equal(t.isPrimitive(null), true); +assert.equal(t.isPrimitive(''), true); +assert.equal(t.isPrimitive(0), true); +assert.equal(t.isPrimitive(new Date()), false); + +assert.equal(t.isBuffer(null), false); +assert.equal(t.isBuffer({}), false); +assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/LICENSE b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/README.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/inherits.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/package.json b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..bad1183 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/test.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/.npmignore b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/.travis.yml b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/Makefile b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/Makefile new file mode 100644 index 0000000..787d56e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test.js + +.PHONY: test + diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/README.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..16d2c59 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,60 @@ + +# isarray + +`Array#isArray` for older browsers. + +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) + +[![browser support](https://ci.testling.com/juliangruber/isarray.png) +](https://ci.testling.com/juliangruber/isarray) + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS 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. diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/component.json b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/index.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..a57f634 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,5 @@ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/package.json b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..3c39d55 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,54 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.4" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "scripts": { + "test": "tape test.js" + }, + "readme": "\n# isarray\n\n`Array#isArray` for older browsers.\n\n[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)\n[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)\n\n[![browser support](https://ci.testling.com/juliangruber/isarray.png)\n](https://ci.testling.com/juliangruber/isarray)\n\n## Usage\n\n```js\nvar isArray = require('isarray');\n\nconsole.log(isArray([])); // => true\nconsole.log(isArray({})); // => false\n```\n\n## Installation\n\nWith [npm](http://npmjs.org) do\n\n```bash\n$ npm install isarray\n```\n\nThen bundle for the browser with\n[browserify](https://github.com/substack/browserify).\n\nWith [component](http://component.io) do\n\n```bash\n$ component install juliangruber/isarray\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "_id": "isarray@1.0.0", + "_shasum": "bb935d48582cba168c06834957a54a3e07124f11", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "_from": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/test.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/test.js new file mode 100644 index 0000000..e0c3444 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/isarray/test.js @@ -0,0 +1,20 @@ +var isArray = require('./'); +var test = require('tape'); + +test('is array', function(t){ + t.ok(isArray([])); + t.notOk(isArray({})); + t.notOk(isArray(null)); + t.notOk(isArray(false)); + + var obj = {}; + obj[0] = true; + t.notOk(isArray(obj)); + + var arr = []; + arr.foo = 'bar'; + t.ok(isArray(arr)); + + t.end(); +}); + diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/.travis.yml b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/.travis.yml new file mode 100644 index 0000000..36201b1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/.travis.yml @@ -0,0 +1,12 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" + - "0.12" + - "1.7.1" + - 1 + - 2 + - 3 + - 4 + - 5 diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/index.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/index.js new file mode 100644 index 0000000..571c276 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/index.js @@ -0,0 +1,20 @@ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} + +function nextTick(fn) { + var args = new Array(arguments.length - 1); + var i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + process.nextTick(function afterTick() { + fn.apply(null, args); + }); +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/license.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/license.md new file mode 100644 index 0000000..c67e353 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/license.md @@ -0,0 +1,19 @@ +# Copyright (c) 2015 Calvin Metcalf + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.** diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/package.json b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/package.json new file mode 100644 index 0000000..9ca913c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/package.json @@ -0,0 +1,28 @@ +{ + "name": "process-nextick-args", + "version": "1.0.6", + "description": "process.nextTick but always with args", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/calvinmetcalf/process-nextick-args.git" + }, + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/calvinmetcalf/process-nextick-args/issues" + }, + "homepage": "https://github.com/calvinmetcalf/process-nextick-args", + "devDependencies": { + "tap": "~0.2.6" + }, + "readme": "process-nextick-args\n=====\n\n[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args)\n\n```bash\nnpm install --save process-nextick-args\n```\n\nAlways be able to pass arguments to process.nextTick, no matter the platform\n\n```js\nvar nextTick = require('process-nextick-args');\n\nnextTick(function (a, b, c) {\n console.log(a, b, c);\n}, 'step', 3, 'profit');\n```\n", + "readmeFilename": "readme.md", + "_id": "process-nextick-args@1.0.6", + "_shasum": "0f96b001cea90b12592ce566edb97ec11e69bd05", + "_resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.6.tgz", + "_from": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.6.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/readme.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/readme.md new file mode 100644 index 0000000..78e7cfa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/readme.md @@ -0,0 +1,18 @@ +process-nextick-args +===== + +[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args) + +```bash +npm install --save process-nextick-args +``` + +Always be able to pass arguments to process.nextTick, no matter the platform + +```js +var nextTick = require('process-nextick-args'); + +nextTick(function (a, b, c) { + console.log(a, b, c); +}, 'step', 3, 'profit'); +``` diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/test.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/test.js new file mode 100644 index 0000000..ef15721 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/process-nextick-args/test.js @@ -0,0 +1,24 @@ +var test = require("tap").test; +var nextTick = require('./'); + +test('should work', function (t) { + t.plan(5); + nextTick(function (a) { + t.ok(a); + nextTick(function (thing) { + t.equals(thing, 7); + }, 7); + }, true); + nextTick(function (a, b, c) { + t.equals(a, 'step'); + t.equals(b, 3); + t.equals(c, 'profit'); + }, 'step', 3, 'profit'); +}); + +test('correct number of arguments', function (t) { + t.plan(1); + nextTick(function () { + t.equals(2, arguments.length, 'correct number'); + }, 1, 2); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/History.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/History.md new file mode 100644 index 0000000..acc8675 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/LICENSE b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000..6a60e8c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/README.md b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/README.md new file mode 100644 index 0000000..75622fa --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/browser.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000..549ae2f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/node.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/node.js new file mode 100644 index 0000000..5e6fcff --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/package.json b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/package.json new file mode 100644 index 0000000..a9f2c5e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/node_modules/util-deprecate/package.json @@ -0,0 +1,37 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate", + "readme": "util-deprecate\n==============\n### The Node.js `util.deprecate()` function with browser support\n\nIn Node.js, this module simply re-exports the `util.deprecate()` function.\n\nIn the web browser (i.e. via browserify), a browser-specific implementation\nof the `util.deprecate()` function is used.\n\n\n## API\n\nA `deprecate()` function is the only thing exposed by this module.\n\n``` javascript\n// setup:\nexports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead');\n\n\n// users see:\nfoo();\n// foo() is deprecated, use bar() instead\nfoo();\nfoo();\n```\n\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2014 Nathan Rajlich \n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n", + "readmeFilename": "README.md", + "_id": "util-deprecate@1.0.2", + "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf", + "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "_from": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/package.json b/node_modules/meteor-node-stubs/node_modules/readable-stream/package.json new file mode 100644 index 0000000..b130074 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/package.json @@ -0,0 +1,47 @@ +{ + "name": "readable-stream", + "version": "2.0.6", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~0.10.x", + "util-deprecate": "~1.0.1" + }, + "devDependencies": { + "tap": "~0.2.6", + "tape": "~4.5.1", + "zuul": "~3.9.0" + }, + "scripts": { + "test": "tap test/parallel/*.js test/ours/*.js", + "browser": "npm run write-zuul && zuul -- test/browser.js", + "write-zuul": "printf \"ui: tape\nbrowsers:\n - name: $BROWSER_NAME\n version: $BROWSER_VERSION\n\">.zuul.yml" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "license": "MIT", + "readme": "# readable-stream\n\n***Node-core v5.8.0 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream)\n\n\n[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)\n[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)\n\n\n[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream)\n\n```bash\nnpm install --save readable-stream\n```\n\n***Node-core streams for userland***\n\nThis package is a mirror of the Streams2 and Streams3 implementations in\nNode-core, including [documentation](doc/stream.markdown).\n\nIf you want to guarantee a stable streams base, regardless of what version of\nNode you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *\"stream\"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).\n\nAs of version 2.0.0 **readable-stream** uses semantic versioning. \n\n# Streams WG Team Members\n\n* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) <christopher.s.dickinson@gmail.com>\n - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B\n* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com>\n - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242\n* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org>\n - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D\n* **Sam Newman** ([@sonewman](https://github.com/sonewman)) <newmansam@outlook.com>\n* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com>\n* **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me>\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/nodejs/readable-stream/issues" + }, + "homepage": "https://github.com/nodejs/readable-stream#readme", + "_id": "readable-stream@2.0.6", + "_shasum": "8f90341e68a53ccc928788dacfcd11b36eb9b78e", + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.0.6.tgz", + "_from": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.0.6.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/passthrough.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/readable.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..6222a57 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/readable.js @@ -0,0 +1,12 @@ +var Stream = (function (){ + try { + return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify + } catch(_){} +}()); +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream || exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/transform.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/meteor-node-stubs/node_modules/readable-stream/writable.js b/node_modules/meteor-node-stubs/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/.npmignore b/node_modules/meteor-node-stubs/node_modules/stream-browserify/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/.travis.yml b/node_modules/meteor-node-stubs/node_modules/stream-browserify/.travis.yml new file mode 100644 index 0000000..ccde138 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/.travis.yml @@ -0,0 +1,9 @@ +sudo: false +language: node_js +node_js: + - 'iojs' + - '0.12' + - '0.10' + - '0.8' +before_install: + - npm install -g npm diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/LICENSE b/node_modules/meteor-node-stubs/node_modules/stream-browserify/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/index.js b/node_modules/meteor-node-stubs/node_modules/stream-browserify/index.js new file mode 100644 index 0000000..8d6a13a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/index.js @@ -0,0 +1,127 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/LICENSE b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/README.md b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/inherits.js b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/inherits_browser.js b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/package.json b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/package.json new file mode 100644 index 0000000..bad1183 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/test.js b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/stream-browserify/package.json new file mode 100644 index 0000000..f4bae5f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/package.json @@ -0,0 +1,60 @@ +{ + "name": "stream-browserify", + "version": "2.0.1", + "description": "the stream module from node core for browsers", + "main": "index.js", + "dependencies": { + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" + }, + "devDependencies": { + "typedarray": "~0.0.6", + "tape": "^4.2.0" + }, + "scripts": { + "test": "tape test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/stream-browserify.git" + }, + "homepage": "https://github.com/substack/stream-browserify", + "keywords": [ + "stream", + "browser", + "browserify" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/3.5", + "firefox/10", + "firefox/nightly", + "chrome/10", + "chrome/latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "readme": "# stream-browserify\n\nthe stream module from node core, for browsers!\n\n[![build status](https://secure.travis-ci.org/substack/stream-browserify.svg)](http://travis-ci.org/substack/stream-browserify)\n\n# methods\n\nConsult the node core\n[documentation on streams](http://nodejs.org/docs/latest/api/stream.html).\n\n# install\n\nWith [npm](https://npmjs.org) do:\n\n```\nnpm install stream-browserify\n```\n\nbut if you are using browserify you will get this module automatically when you\ndo `require('stream')`.\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/stream-browserify/issues" + }, + "_id": "stream-browserify@2.0.1", + "_shasum": "66266ee5f9bdb9940a4e4514cafb43bb71e5c9db", + "_resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.1.tgz", + "_from": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/readme.markdown b/node_modules/meteor-node-stubs/node_modules/stream-browserify/readme.markdown new file mode 100644 index 0000000..c0c1b2f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/readme.markdown @@ -0,0 +1,25 @@ +# stream-browserify + +the stream module from node core, for browsers! + +[![build status](https://secure.travis-ci.org/substack/stream-browserify.svg)](http://travis-ci.org/substack/stream-browserify) + +# methods + +Consult the node core +[documentation on streams](http://nodejs.org/docs/latest/api/stream.html). + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install stream-browserify +``` + +but if you are using browserify you will get this module automatically when you +do `require('stream')`. + +# license + +MIT diff --git a/node_modules/meteor-node-stubs/node_modules/stream-browserify/test/buf.js b/node_modules/meteor-node-stubs/node_modules/stream-browserify/test/buf.js new file mode 100644 index 0000000..8217819 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/stream-browserify/test/buf.js @@ -0,0 +1,32 @@ +var path = require('path'); +var test = require('tape'); + +var Writable = require('../').Writable; +var inherits = require('inherits'); + +inherits(TestWritable, Writable); + +function TestWritable(opt) { + if (!(this instanceof TestWritable)) + return new TestWritable(opt); + Writable.call(this, opt); + this._written = []; +} + +TestWritable.prototype._write = function(chunk, encoding, cb) { + this._written.push(chunk); + cb(); +}; + +var buf = Buffer([ 88 ]); + +test('.writable writing ArrayBuffer', function(t) { + var writable = new TestWritable(); + + writable.write(buf); + writable.end(); + + t.equal(writable._written.length, 1); + t.equal(writable._written[0].toString(), 'X') + t.end() +}); diff --git a/node_modules/meteor-node-stubs/node_modules/string_decoder/.npmignore b/node_modules/meteor-node-stubs/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/node_modules/meteor-node-stubs/node_modules/string_decoder/LICENSE b/node_modules/meteor-node-stubs/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/string_decoder/README.md b/node_modules/meteor-node-stubs/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/string_decoder/index.js b/node_modules/meteor-node-stubs/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} diff --git a/node_modules/meteor-node-stubs/node_modules/string_decoder/package.json b/node_modules/meteor-node-stubs/node_modules/string_decoder/package.json new file mode 100644 index 0000000..593645b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "0.10.31", + "description": "The string_decoder module from Node core", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "readme": "**string_decoder.js** (`require('string_decoder')`) from Node.js core\n\nCopyright Joyent, Inc. and other Node contributors. See LICENCE file for details.\n\nVersion numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.**\n\nThe *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version.", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "_from": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/.npmignore b/node_modules/meteor-node-stubs/node_modules/timers-browserify/.npmignore new file mode 100644 index 0000000..03e05e4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/.npmignore @@ -0,0 +1,2 @@ +.DS_Store +/node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/CHANGELOG.md b/node_modules/meteor-node-stubs/node_modules/timers-browserify/CHANGELOG.md new file mode 100644 index 0000000..a7cd8bc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/CHANGELOG.md @@ -0,0 +1,58 @@ +# Change Log +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +## 1.4.0 - 2015-02-23 + +### Added +* Link to `timers-browserify-full`, which offers a larger, but much more exact, + version of Node's `timers` library + +### Changed +* `setTimeout` and `setInterval` return objects with the same API as the Node + implementation, instead of just IDs + +### Fixed +* `active` implementation actually has an effect, as in Node +* Replaced usages of `apply` that break in IE 8 + +## 1.3.0 - 2015-02-04 + +### Changed +* Prefer native versions of `setImmediate` and `clearImmediate` if they exist + +## 1.2.0 - 2015-01-02 + +### Changed +* Update `process` dependency + +## 1.1.0 - 2014-08-26 + +### Added +* `clearImmediate` available to undo `setImmediate` + +## 1.0.3 - 2014-06-30 + +### Fixed +* Resume returning opaque IDs from `setTimeout` and `setInterval` + +## 1.0.2 - 2014-06-30 + +### Fixed +* Pass `window` explicitly to `setTimeout` and others to resolve an error in + Chrome + +## 1.0.1 - 2013-12-28 + +### Changed +* Replaced `setimmediate` dependency with `process` for the `nextTick` shim + +## 1.0.0 - 2013-12-10 + +### Added +* Guard against undefined globals like `setTimeout` in some environments + +## 0.0.0 - 2012-05-30 + +### Added +* Basic functionality for initial release diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/LICENSE.md b/node_modules/meteor-node-stubs/node_modules/timers-browserify/LICENSE.md new file mode 100644 index 0000000..940ec90 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/LICENSE.md @@ -0,0 +1,46 @@ +# timers-browserify + +This project uses the [MIT](http://jryans.mit-license.org/) license: + + Copyright © 2012 J. Ryan Stinnett + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the “Software”), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +# lib/node + +The `lib/node` directory borrows files from joyent/node which uses the following license: + + Copyright Joyent, Inc. and other Node contributors. All rights reserved. + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/README.md b/node_modules/meteor-node-stubs/node_modules/timers-browserify/README.md new file mode 100644 index 0000000..c7efa19 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/README.md @@ -0,0 +1,40 @@ +# Overview + +Adds support for the `timers` module to browserify. + +## Wait, isn't it already supported in the browser? + +The public methods of the `timers` module are: + +* `setTimeout(callback, delay, [arg], [...])` +* `clearTimeout(timeoutId)` +* `setInterval(callback, delay, [arg], [...])` +* `clearInterval(intervalId)` + +and indeed, browsers support these already. + +## So, why does this exist? + +The `timers` module also includes some private methods used in other built-in +Node.js modules: + +* `enroll(item, delay)` +* `unenroll(item)` +* `active(item)` + +These are used to efficiently support a large quantity of timers with the same +timeouts by creating only a few timers under the covers. + +Node.js also offers the `immediate` APIs, which aren't yet available cross-browser, so we polyfill those: + +* `setImmediate(callback, [arg], [...])` +* `clearImmediate(immediateId)` + +## I need lots of timers and want to use linked list timers as Node.js does. + +Linked lists are efficient when you have thousands (millions?) of timers with the same delay. +Take a look at [timers-browserify-full](https://www.npmjs.com/package/timers-browserify-full) in this case. + +# License + +[MIT](http://jryans.mit-license.org/) diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/build.sh b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/build.sh new file mode 100644 index 0000000..d276735 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/build.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +browserify --debug -o js/browserify.js js/main.js diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/index.html b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/index.html new file mode 100644 index 0000000..9cc1140 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/index.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/js/browserify.js b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/js/browserify.js new file mode 100644 index 0000000..c2d0821 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/js/browserify.js @@ -0,0 +1,233 @@ +var require = function (file, cwd) { + var resolved = require.resolve(file, cwd || '/'); + var mod = require.modules[resolved]; + if (!mod) throw new Error( + 'Failed to resolve module ' + file + ', tried ' + resolved + ); + var res = mod._cached ? mod._cached : mod(); + return res; +} + +require.paths = []; +require.modules = {}; +require.extensions = [".js",".coffee"]; + +require._core = { + 'assert': true, + 'events': true, + 'fs': true, + 'path': true, + 'vm': true +}; + +require.resolve = (function () { + return function (x, cwd) { + if (!cwd) cwd = '/'; + + if (require._core[x]) return x; + var path = require.modules.path(); + cwd = path.resolve('/', cwd); + var y = cwd || '/'; + + if (x.match(/^(?:\.\.?\/|\/)/)) { + var m = loadAsFileSync(path.resolve(y, x)) + || loadAsDirectorySync(path.resolve(y, x)); + if (m) return m; + } + + var n = loadNodeModulesSync(x, y); + if (n) return n; + + throw new Error("Cannot find module '" + x + "'"); + + function loadAsFileSync (x) { + if (require.modules[x]) { + return x; + } + + for (var i = 0; i < require.extensions.length; i++) { + var ext = require.extensions[i]; + if (require.modules[x + ext]) return x + ext; + } + } + + function loadAsDirectorySync (x) { + x = x.replace(/\/+$/, ''); + var pkgfile = x + '/package.json'; + if (require.modules[pkgfile]) { + var pkg = require.modules[pkgfile](); + var b = pkg.browserify; + if (typeof b === 'object' && b.main) { + var m = loadAsFileSync(path.resolve(x, b.main)); + if (m) return m; + } + else if (typeof b === 'string') { + var m = loadAsFileSync(path.resolve(x, b)); + if (m) return m; + } + else if (pkg.main) { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + } + } + + return loadAsFileSync(x + '/index'); + } + + function loadNodeModulesSync (x, start) { + var dirs = nodeModulesPathsSync(start); + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + var m = loadAsFileSync(dir + '/' + x); + if (m) return m; + var n = loadAsDirectorySync(dir + '/' + x); + if (n) return n; + } + + var m = loadAsFileSync(x); + if (m) return m; + } + + function nodeModulesPathsSync (start) { + var parts; + if (start === '/') parts = [ '' ]; + else parts = path.normalize(start).split('/'); + + var dirs = []; + for (var i = parts.length - 1; i >= 0; i--) { + if (parts[i] === 'node_modules') continue; + var dir = parts.slice(0, i + 1).join('/') + '/node_modules'; + dirs.push(dir); + } + + return dirs; + } + }; +})(); + +require.alias = function (from, to) { + var path = require.modules.path(); + var res = null; + try { + res = require.resolve(from + '/package.json', '/'); + } + catch (err) { + res = require.resolve(from, '/'); + } + var basedir = path.dirname(res); + + var keys = (Object.keys || function (obj) { + var res = []; + for (var key in obj) res.push(key) + return res; + })(require.modules); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key.slice(0, basedir.length + 1) === basedir + '/') { + var f = key.slice(basedir.length); + require.modules[to + f] = require.modules[basedir + f]; + } + else if (key === basedir) { + require.modules[to] = require.modules[basedir]; + } + } +}; + +require.define = function (filename, fn) { + var dirname = require._core[filename] + ? '' + : require.modules.path().dirname(filename) + ; + + var require_ = function (file) { + return require(file, dirname) + }; + require_.resolve = function (name) { + return require.resolve(name, dirname); + }; + require_.modules = require.modules; + require_.define = require.define; + var module_ = { exports : {} }; + + require.modules[filename] = function () { + require.modules[filename]._cached = module_.exports; + fn.call( + module_.exports, + require_, + module_, + module_.exports, + dirname, + filename + ); + require.modules[filename]._cached = module_.exports; + return module_.exports; + }; +}; + +if (typeof process === 'undefined') process = {}; + +if (!process.nextTick) process.nextTick = (function () { + var queue = []; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; + + if (canPost) { + window.addEventListener('message', function (ev) { + if (ev.source === window && ev.data === 'browserify-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); + } + + return function (fn) { + if (canPost) { + queue.push(fn); + window.postMessage('browserify-tick', '*'); + } + else setTimeout(fn, 0); + }; +})(); + +if (!process.title) process.title = 'browser'; + +if (!process.binding) process.binding = function (name) { + if (name === 'evals') return require('vm') + else throw new Error('No such module') +}; + +if (!process.cwd) process.cwd = function () { return '.' }; + +if (!process.env) process.env = {}; +if (!process.argv) process.argv = []; + +require.define("path", Function( + [ 'require', 'module', 'exports', '__dirname', '__filename' ], + "function filter (xs, fn) {\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n if (fn(xs[i], i, xs)) res.push(xs[i]);\n }\n return res;\n}\n\n// resolves . and .. elements in a path array with directory names there\n// must be no slashes, empty elements, or device names (c:\\) in the array\n// (so also no leading and trailing slashes - it does not distinguish\n// relative and absolute paths)\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = parts.length; i >= 0; i--) {\n var last = parts[i];\n if (last == '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Regex to split a filename into [*, dir, basename, ext]\n// posix version\nvar splitPathRe = /^(.+\\/(?!$)|\\/)?((?:.+?)?(\\.[^.]*)?)$/;\n\n// path.resolve([from ...], to)\n// posix version\nexports.resolve = function() {\nvar resolvedPath = '',\n resolvedAbsolute = false;\n\nfor (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0)\n ? arguments[i]\n : process.cwd();\n\n // Skip empty and invalid entries\n if (typeof path !== 'string' || !path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n}\n\n// At this point the path should be resolved to a full absolute path, but\n// handle relative paths to be safe (might happen when process.cwd() fails)\n\n// Normalize the path\nresolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n};\n\n// path.normalize(path)\n// posix version\nexports.normalize = function(path) {\nvar isAbsolute = path.charAt(0) === '/',\n trailingSlash = path.slice(-1) === '/';\n\n// Normalize the path\npath = normalizeArray(filter(path.split('/'), function(p) {\n return !!p;\n }), !isAbsolute).join('/');\n\n if (!path && !isAbsolute) {\n path = '.';\n }\n if (path && trailingSlash) {\n path += '/';\n }\n \n return (isAbsolute ? '/' : '') + path;\n};\n\n\n// posix version\nexports.join = function() {\n var paths = Array.prototype.slice.call(arguments, 0);\n return exports.normalize(filter(paths, function(p, index) {\n return p && typeof p === 'string';\n }).join('/'));\n};\n\n\nexports.dirname = function(path) {\n var dir = splitPathRe.exec(path)[1] || '';\n var isWindows = false;\n if (!dir) {\n // No dirname\n return '.';\n } else if (dir.length === 1 ||\n (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) {\n // It is just a slash or a drive letter with a slash\n return dir;\n } else {\n // It is a full dirname, strip trailing slash\n return dir.substring(0, dir.length - 1);\n }\n};\n\n\nexports.basename = function(path, ext) {\n var f = splitPathRe.exec(path)[2] || '';\n // TODO: make this comparison case-insensitive on windows?\n if (ext && f.substr(-1 * ext.length) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n};\n\n\nexports.extname = function(path) {\n return splitPathRe.exec(path)[3] || '';\n};\n\n//@ sourceURL=path" +)); + +require.define("timers", Function( + [ 'require', 'module', 'exports', '__dirname', '__filename' ], + "module.exports = require(\"timers-browserify\")\n//@ sourceURL=timers" +)); + +require.define("/node_modules/timers-browserify/package.json", Function( + [ 'require', 'module', 'exports', '__dirname', '__filename' ], + "module.exports = {\"main\":\"main.js\"}\n//@ sourceURL=/node_modules/timers-browserify/package.json" +)); + +require.define("/node_modules/timers-browserify/main.js", Function( + [ 'require', 'module', 'exports', '__dirname', '__filename' ], + "// DOM APIs, for completeness\n\nexports.setTimeout = setTimeout;\nexports.clearTimeout = clearTimeout;\nexports.setInterval = setInterval;\nexports.clearInterval = clearInterval;\n\n// TODO: Change to more effiecient list approach used in Node.js\n// For now, we just implement the APIs using the primitives above.\n\nexports.enroll = function(item, delay) {\n item._timeoutID = setTimeout(item._onTimeout, delay);\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._timeoutID);\n};\n\nexports.active = function(item) {\n // our naive impl doesn't care (correctness is still preserved)\n};\n\n//@ sourceURL=/node_modules/timers-browserify/main.js" +)); + +require.define("/main.js", Function( + [ 'require', 'module', 'exports', '__dirname', '__filename' ], + "var timers = require('timers');\n\nvar obj = {\n _onTimeout: function() {\n console.log('Timer ran for: ' + (new Date().getTime() - obj.now) + ' ms');\n },\n start: function() {\n console.log('Timer should run for 100 ms');\n this.now = new Date().getTime();\n timers.enroll(this, 100);\n }\n};\n\nobj.start();\n\n//@ sourceURL=/main.js" +)); +require("/main.js"); diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/js/main.js b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/js/main.js new file mode 100644 index 0000000..0007df8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/js/main.js @@ -0,0 +1,14 @@ +var timers = require('timers'); + +var obj = { + _onTimeout: function() { + console.log('Timer ran for: ' + (new Date().getTime() - obj.now) + ' ms'); + }, + start: function() { + console.log('Timer should run for 100 ms'); + this.now = new Date().getTime(); + timers.enroll(this, 100); + } +}; + +obj.start(); diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/server.js b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/server.js new file mode 100644 index 0000000..37b1a0a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/example/enroll/server.js @@ -0,0 +1,11 @@ +var connect = require('connect'); +var server = connect.createServer(); +server.use(connect.static(__dirname)); + +var browserify = require('browserify'); +var bundle = browserify(__dirname + '/js/main.js', { mount: '/js/browserify.js' }); +server.use(bundle); + +var port = parseInt(process.argv[2] || 8080, 10); +server.listen(port); +console.log('Listening on :' + port); diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/main.js b/node_modules/meteor-node-stubs/node_modules/timers-browserify/main.js new file mode 100644 index 0000000..38c058f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/main.js @@ -0,0 +1,76 @@ +var nextTick = require('process/browser.js').nextTick; +var apply = Function.prototype.apply; +var slice = Array.prototype.slice; +var immediateIds = {}; +var nextImmediateId = 0; + +// DOM APIs, for completeness + +exports.setTimeout = function() { + return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); +}; +exports.setInterval = function() { + return new Timeout(apply.call(setInterval, window, arguments), clearInterval); +}; +exports.clearTimeout = +exports.clearInterval = function(timeout) { timeout.close(); }; + +function Timeout(id, clearFn) { + this._id = id; + this._clearFn = clearFn; +} +Timeout.prototype.unref = Timeout.prototype.ref = function() {}; +Timeout.prototype.close = function() { + this._clearFn.call(window, this._id); +}; + +// Does not start the time, just sets up the members needed. +exports.enroll = function(item, msecs) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = msecs; +}; + +exports.unenroll = function(item) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = -1; +}; + +exports._unrefActive = exports.active = function(item) { + clearTimeout(item._idleTimeoutId); + + var msecs = item._idleTimeout; + if (msecs >= 0) { + item._idleTimeoutId = setTimeout(function onTimeout() { + if (item._onTimeout) + item._onTimeout(); + }, msecs); + } +}; + +// That's not how node.js implements it but the exposed api is the same. +exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { + var id = nextImmediateId++; + var args = arguments.length < 2 ? false : slice.call(arguments, 1); + + immediateIds[id] = true; + + nextTick(function onNextTick() { + if (immediateIds[id]) { + // fn.call() is faster so we optimize for the common use-case + // @see http://jsperf.com/call-apply-segu + if (args) { + fn.apply(null, args); + } else { + fn.call(null); + } + // Prevent ids from leaking + exports.clearImmediate(id); + } + }); + + return id; +}; + +exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { + delete immediateIds[id]; +}; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/timers-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/timers-browserify/package.json new file mode 100644 index 0000000..d0cd81a --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/timers-browserify/package.json @@ -0,0 +1,84 @@ +{ + "author": { + "name": "J. Ryan Stinnett", + "email": "jryans@gmail.com", + "url": "http://convolv.es/" + }, + "name": "timers-browserify", + "description": "timers module for browserify", + "version": "1.4.2", + "homepage": "https://github.com/jryans/timers-browserify", + "bugs": { + "url": "https://github.com/jryans/timers-browserify/issues" + }, + "repository": { + "type": "git", + "url": "git://github.com/jryans/timers-browserify.git" + }, + "contributors": [ + { + "name": "Guy Bedford", + "email": "guybedford@gmail.com" + }, + { + "name": "Ionut-Cristian Florescu", + "email": "ionut.florescu@gmail.com" + }, + { + "name": "James Halliday", + "email": "mail@substack.net" + }, + { + "name": "Jan Schär", + "email": "jscissr@gmail.com" + }, + { + "name": "Johannes Ewald", + "email": "johannes.ewald@peerigon.com" + }, + { + "name": "Jonathan Prins", + "email": "jon@blip.tv" + }, + { + "name": "Matt Esch", + "email": "matt@mattesch.info" + } + ], + "main": "main.js", + "dependencies": { + "process": "~0.11.0" + }, + "devDependencies": { + "connect": "~2.3.0", + "browserify": "~1.10.16" + }, + "optionalDependencies": {}, + "engines": { + "node": ">=0.6.0" + }, + "keywords": [ + "timers", + "browserify", + "browser" + ], + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/jryans/timers-browserify/blob/master/LICENSE.md" + } + ], + "jspm": { + "map": { + "./main.js": { + "node": "@node/timers" + } + } + }, + "readme": "# Overview\n\nAdds support for the `timers` module to browserify.\n\n## Wait, isn't it already supported in the browser?\n\nThe public methods of the `timers` module are:\n\n* `setTimeout(callback, delay, [arg], [...])`\n* `clearTimeout(timeoutId)`\n* `setInterval(callback, delay, [arg], [...])`\n* `clearInterval(intervalId)`\n\nand indeed, browsers support these already.\n\n## So, why does this exist?\n\nThe `timers` module also includes some private methods used in other built-in\nNode.js modules:\n\n* `enroll(item, delay)`\n* `unenroll(item)`\n* `active(item)`\n\nThese are used to efficiently support a large quantity of timers with the same\ntimeouts by creating only a few timers under the covers.\n\nNode.js also offers the `immediate` APIs, which aren't yet available cross-browser, so we polyfill those:\n\n* `setImmediate(callback, [arg], [...])`\n* `clearImmediate(immediateId)`\n\n## I need lots of timers and want to use linked list timers as Node.js does.\n\nLinked lists are efficient when you have thousands (millions?) of timers with the same delay.\nTake a look at [timers-browserify-full](https://www.npmjs.com/package/timers-browserify-full) in this case.\n\n# License\n\n[MIT](http://jryans.mit-license.org/)\n", + "readmeFilename": "README.md", + "_id": "timers-browserify@1.4.2", + "_shasum": "c9c58b575be8407375cb5e2462dacee74359f41d", + "_resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-1.4.2.tgz", + "_from": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-1.4.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/tty-browserify/LICENSE b/node_modules/meteor-node-stubs/node_modules/tty-browserify/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/tty-browserify/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/tty-browserify/index.js b/node_modules/meteor-node-stubs/node_modules/tty-browserify/index.js new file mode 100644 index 0000000..2b5f04c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/tty-browserify/index.js @@ -0,0 +1,11 @@ +exports.isatty = function () { return false; }; + +function ReadStream() { + throw new Error('tty.ReadStream is not implemented'); +} +exports.ReadStream = ReadStream; + +function WriteStream() { + throw new Error('tty.ReadStream is not implemented'); +} +exports.WriteStream = WriteStream; diff --git a/node_modules/meteor-node-stubs/node_modules/tty-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/tty-browserify/package.json new file mode 100644 index 0000000..844a9d0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/tty-browserify/package.json @@ -0,0 +1,38 @@ +{ + "name": "tty-browserify", + "version": "0.0.0", + "description": "the tty module from node core for browsers", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "~1.0.4" + }, + "scripts": { + "test": "tape test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/tty-browserify.git" + }, + "homepage": "https://github.com/substack/tty-browserify", + "keywords": [ + "tty", + "browser", + "browserify" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "readme": "# tty-browserify\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/tty-browserify/issues" + }, + "_id": "tty-browserify@0.0.0", + "_shasum": "a157ba402da24e9bf957f9aa69d524eed42901a6", + "_resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "_from": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/tty-browserify/readme.markdown b/node_modules/meteor-node-stubs/node_modules/tty-browserify/readme.markdown new file mode 100644 index 0000000..91a2051 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/tty-browserify/readme.markdown @@ -0,0 +1 @@ +# tty-browserify diff --git a/node_modules/meteor-node-stubs/node_modules/url/.npmignore b/node_modules/meteor-node-stubs/node_modules/url/.npmignore new file mode 100644 index 0000000..ba11471 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/.npmignore @@ -0,0 +1 @@ +test-url.js diff --git a/node_modules/meteor-node-stubs/node_modules/url/.travis.yml b/node_modules/meteor-node-stubs/node_modules/url/.travis.yml new file mode 100644 index 0000000..16ed301 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "0.10" +env: + global: + - secure: OgPRLCzHFh5WbjHEKlghHFW1oOreSF2JVUr3CMaFDi03ngTS2WONSw8mRn8SA6FTldiGGBx1n8orDzUw6cdkB7+tkU3G5B0M0V3vl823NaUFKgxsCM3UGDYfJb3yfAG5cj72rVZoX/ABd1fVuG4vBIlDLxsSlKQFMzUCFoyttr8= + - secure: AiZP8GHbyx83ZBhOvOxxtpNcgNHoP+vo5G1a1OYU78EHCgHg8NRyHKyCdrBnPvw6mV2BI/8frZaXAEicsHMtHMofBYn7nibNlaajBPI8AkHtYfNSc+zO+71Kwv7VOTOKKnkMEIkqhHlc6njFoH3QaBNHsgNlzzplPxaIt8vdUVk= diff --git a/node_modules/meteor-node-stubs/node_modules/url/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/url/.zuul.yml new file mode 100644 index 0000000..feea8b6 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/.zuul.yml @@ -0,0 +1,16 @@ +ui: mocha-tdd +browsers: + - name: chrome + version: latest + - name: firefox + version: 24..latest + - name: safari + version: latest + - name: ie + version: 9..latest + - name: iphone + version: oldest..latest + - name: ipad + version: oldest..latest + - name: android + version: oldest..latest diff --git a/node_modules/meteor-node-stubs/node_modules/url/LICENSE b/node_modules/meteor-node-stubs/node_modules/url/LICENSE new file mode 100644 index 0000000..f45bc11 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/url/README.md b/node_modules/meteor-node-stubs/node_modules/url/README.md new file mode 100644 index 0000000..8b35460 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/README.md @@ -0,0 +1,108 @@ +# node-url + +[![Build Status](https://travis-ci.org/defunctzombie/node-url.svg?branch=master)](https://travis-ci.org/defunctzombie/node-url) + +This module has utilities for URL resolution and parsing meant to have feature parity with node.js core [url](http://nodejs.org/api/url.html) module. + +```js +var url = require('url'); +``` + +## api + +Parsed URL objects have some or all of the following fields, depending on +whether or not they exist in the URL string. Any parts that are not in the URL +string will not be in the parsed object. Examples are shown for the URL + +`'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'` + +* `href`: The full URL that was originally parsed. Both the protocol and host are lowercased. + + Example: `'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'` + +* `protocol`: The request protocol, lowercased. + + Example: `'http:'` + +* `host`: The full lowercased host portion of the URL, including port + information. + + Example: `'host.com:8080'` + +* `auth`: The authentication information portion of a URL. + + Example: `'user:pass'` + +* `hostname`: Just the lowercased hostname portion of the host. + + Example: `'host.com'` + +* `port`: The port number portion of the host. + + Example: `'8080'` + +* `pathname`: The path section of the URL, that comes after the host and + before the query, including the initial slash if present. + + Example: `'/p/a/t/h'` + +* `search`: The 'query string' portion of the URL, including the leading + question mark. + + Example: `'?query=string'` + +* `path`: Concatenation of `pathname` and `search`. + + Example: `'/p/a/t/h?query=string'` + +* `query`: Either the 'params' portion of the query string, or a + querystring-parsed object. + + Example: `'query=string'` or `{'query':'string'}` + +* `hash`: The 'fragment' portion of the URL including the pound-sign. + + Example: `'#hash'` + +The following methods are provided by the URL module: + +### url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) + +Take a URL string, and return an object. + +Pass `true` as the second argument to also parse +the query string using the `querystring` module. +Defaults to `false`. + +Pass `true` as the third argument to treat `//foo/bar` as +`{ host: 'foo', pathname: '/bar' }` rather than +`{ pathname: '//foo/bar' }`. Defaults to `false`. + +### url.format(urlObj) + +Take a parsed URL object, and return a formatted URL string. + +* `href` will be ignored. +* `protocol` is treated the same with or without the trailing `:` (colon). + * The protocols `http`, `https`, `ftp`, `gopher`, `file` will be + postfixed with `://` (colon-slash-slash). + * All other protocols `mailto`, `xmpp`, `aim`, `sftp`, `foo`, etc will + be postfixed with `:` (colon) +* `auth` will be used if present. +* `hostname` will only be used if `host` is absent. +* `port` will only be used if `host` is absent. +* `host` will be used in place of `hostname` and `port` +* `pathname` is treated the same with or without the leading `/` (slash) +* `search` will be used in place of `query` +* `query` (object; see `querystring`) will only be used if `search` is absent. +* `search` is treated the same with or without the leading `?` (question mark) +* `hash` is treated the same with or without the leading `#` (pound sign, anchor) + +### url.resolve(from, to) + +Take a base URL, and a href URL, and resolve them as a browser would for +an anchor tag. Examples: + + url.resolve('/one/two/three', 'four') // '/one/two/four' + url.resolve('http://example.com/', '/one') // 'http://example.com/one' + url.resolve('http://example.com/one', '/two') // 'http://example.com/two' diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/LICENSE-MIT.txt b/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/README.md b/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/README.md new file mode 100644 index 0000000..831e637 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/README.md @@ -0,0 +1,176 @@ +# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) + +A robust Punycode converter that fully complies to [RFC 3492](http://tools.ietf.org/html/rfc3492) and [RFC 5891](http://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms. + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](http://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc). + +## Installation + +Via [npm](http://npmjs.org/) (only required for Node.js releases older than v0.6.2): + +```bash +npm install punycode +``` + +Via [Bower](http://bower.io/): + +```bash +bower install punycode +``` + +Via [Component](https://github.com/component/component): + +```bash +component install bestiejs/punycode.js +``` + +In a browser: + +```html + +``` + +In [Narwhal](http://narwhaljs.org/), [Node.js](http://nodejs.org/), and [RingoJS](http://ringojs.org/): + +```js +var punycode = require('punycode'); +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('punycode.js'); +``` + +Using an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require( + { + 'paths': { + 'punycode': 'path/to/punycode' + } + }, + ['punycode'], + function(punycode) { + console.log(punycode); + } +); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that's already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## Unit tests & code coverage + +After cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. + +Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`. + +To generate the code coverage report, use `grunt cover`. + +Feel free to fork if you see possible improvements! + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## Contributors + +| [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") | +|---| +| [John-David Dalton](http://allyoucanleet.com/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/package.json b/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/package.json new file mode 100644 index 0000000..855ee46 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/package.json @@ -0,0 +1,61 @@ +{ + "name": "punycode", + "version": "1.3.2", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "https://mths.be/punycode", + "main": "punycode.js", + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + { + "name": "John-David Dalton", + "url": "http://allyoucanleet.com/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/bestiejs/punycode.js.git" + }, + "bugs": { + "url": "https://github.com/bestiejs/punycode.js/issues" + }, + "files": [ + "LICENSE-MIT.txt", + "punycode.js" + ], + "scripts": { + "test": "node tests/tests.js" + }, + "devDependencies": { + "coveralls": "^2.10.1", + "grunt": "^0.4.5", + "grunt-contrib-uglify": "^0.5.0", + "grunt-shell": "^0.7.0", + "istanbul": "^0.2.13", + "qunit-extras": "^1.2.0", + "qunitjs": "~1.11.0", + "requirejs": "^2.1.14" + }, + "readme": "# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js)\n\nA robust Punycode converter that fully complies to [RFC 3492](http://tools.ietf.org/html/rfc3492) and [RFC 5891](http://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms.\n\nThis JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm:\n\n* [The C example code from RFC 3492](http://tools.ietf.org/html/rfc3492#appendix-C)\n* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c)\n* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c)\n* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287)\n* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072))\n\nThis project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc).\n\n## Installation\n\nVia [npm](http://npmjs.org/) (only required for Node.js releases older than v0.6.2):\n\n```bash\nnpm install punycode\n```\n\nVia [Bower](http://bower.io/):\n\n```bash\nbower install punycode\n```\n\nVia [Component](https://github.com/component/component):\n\n```bash\ncomponent install bestiejs/punycode.js\n```\n\nIn a browser:\n\n```html\n\n```\n\nIn [Narwhal](http://narwhaljs.org/), [Node.js](http://nodejs.org/), and [RingoJS](http://ringojs.org/):\n\n```js\nvar punycode = require('punycode');\n```\n\nIn [Rhino](http://www.mozilla.org/rhino/):\n\n```js\nload('punycode.js');\n```\n\nUsing an AMD loader like [RequireJS](http://requirejs.org/):\n\n```js\nrequire(\n {\n 'paths': {\n 'punycode': 'path/to/punycode'\n }\n },\n ['punycode'],\n function(punycode) {\n console.log(punycode);\n }\n);\n```\n\n## API\n\n### `punycode.decode(string)`\n\nConverts a Punycode string of ASCII symbols to a string of Unicode symbols.\n\n```js\n// decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'\n```\n\n### `punycode.encode(string)`\n\nConverts a string of Unicode symbols to a Punycode string of ASCII symbols.\n\n```js\n// encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'\n```\n\n### `punycode.toUnicode(input)`\n\nConverts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode.\n\n```js\n// decode domain names\npunycode.toUnicode('xn--maana-pta.com');\n// → 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com');\n// → '☃-⌘.com'\n\n// decode email addresses\npunycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq');\n// → 'джумла@джpумлатест.bрфa'\n```\n\n### `punycode.toASCII(input)`\n\nConverts a Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that's already in ASCII.\n\n```js\n// encode domain names\npunycode.toASCII('mañana.com');\n// → 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com');\n// → 'xn----dqo34k.com'\n\n// encode email addresses\npunycode.toASCII('джумла@джpумлатест.bрфa');\n// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'\n```\n\n### `punycode.ucs2`\n\n#### `punycode.ucs2.decode(string)`\n\nCreates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.\n\n```js\npunycode.ucs2.decode('abc');\n// → [0x61, 0x62, 0x63]\n// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE:\npunycode.ucs2.decode('\\uD834\\uDF06');\n// → [0x1D306]\n```\n\n#### `punycode.ucs2.encode(codePoints)`\n\nCreates a string based on an array of numeric code point values.\n\n```js\npunycode.ucs2.encode([0x61, 0x62, 0x63]);\n// → 'abc'\npunycode.ucs2.encode([0x1D306]);\n// → '\\uD834\\uDF06'\n```\n\n### `punycode.version`\n\nA string representing the current Punycode.js version number.\n\n## Unit tests & code coverage\n\nAfter cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`.\n\nOnce that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`.\n\nTo generate the code coverage report, use `grunt cover`.\n\nFeel free to fork if you see possible improvements!\n\n## Author\n\n| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias \"Follow @mathias on Twitter\") |\n|---|\n| [Mathias Bynens](https://mathiasbynens.be/) |\n\n## Contributors\n\n| [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton \"Follow @jdalton on Twitter\") |\n|---|\n| [John-David Dalton](http://allyoucanleet.com/) |\n\n## License\n\nPunycode.js is available under the [MIT](https://mths.be/mit) license.\n", + "readmeFilename": "README.md", + "_id": "punycode@1.3.2", + "_shasum": "9653a036fb7c1ee42342f2325cceefea3926c48d", + "_resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "_from": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/punycode.js b/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/punycode.js new file mode 100644 index 0000000..ac68597 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/punycode/punycode.js @@ -0,0 +1,530 @@ +/*! https://mths.be/punycode v1.3.2 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.History.md.un~ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.History.md.un~ new file mode 100644 index 0000000..c96a7dd Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.History.md.un~ differ diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.Readme.md.un~ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.Readme.md.un~ new file mode 100644 index 0000000..71613b5 Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.Readme.md.un~ differ diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.package.json.un~ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.package.json.un~ new file mode 100644 index 0000000..d86fe31 Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.package.json.un~ differ diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.travis.yml b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/History.md b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/History.md new file mode 100644 index 0000000..4fddbaf --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/History.md @@ -0,0 +1,20 @@ +# 0.2.0 / 2013-02-21 + + - Refactor into function per-module idiomatic style. + - Improved test coverage. + +# 0.1.0 / 2011-12-13 + + - Minor project reorganization + +# 0.0.3 / 2011-04-16 + - Support for AMD module loaders + +# 0.0.2 / 2011-04-16 + + - Ported unit tests + - Removed functionality that depended on Buffers + +# 0.0.1 / 2011-04-15 + + - Initial release diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/License.md b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/License.md new file mode 100644 index 0000000..fc80e85 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/License.md @@ -0,0 +1,19 @@ + +Copyright 2012 Irakli Gozalishvili. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/Readme.md b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/Readme.md new file mode 100644 index 0000000..a4fe252 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/Readme.md @@ -0,0 +1,15 @@ +# querystring + +[![Build Status](https://secure.travis-ci.org/Gozala/querystring.png)](http://travis-ci.org/Gozala/querystring) + + +[![Browser support](http://ci.testling.com/Gozala/querystring.png)](http://ci.testling.com/Gozala/querystring) + + + +Node's querystring module for all engines. + +## Install ## + + npm install querystring + diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/decode.js b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/decode.js new file mode 100644 index 0000000..a6518b8 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/decode.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/encode.js b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/encode.js new file mode 100644 index 0000000..4f2b561 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/encode.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/index.js b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/index.js new file mode 100644 index 0000000..99826ea --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/index.js @@ -0,0 +1,4 @@ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/package.json b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/package.json new file mode 100644 index 0000000..9369a6f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/package.json @@ -0,0 +1,81 @@ +{ + "name": "querystring", + "id": "querystring", + "version": "0.2.0", + "description": "Node's querystring module for all engines.", + "keywords": [ + "commonjs", + "query", + "querystring" + ], + "author": { + "name": "Irakli Gozalishvili", + "email": "rfobic@gmail.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Gozala/querystring.git", + "web": "https://github.com/Gozala/querystring" + }, + "bugs": { + "url": "http://github.com/Gozala/querystring/issues/" + }, + "devDependencies": { + "test": "~0.x.0", + "phantomify": "~0.x.0", + "retape": "~0.x.0", + "tape": "~0.1.5" + }, + "engines": { + "node": ">=0.4.x" + }, + "scripts": { + "test": "npm run test-node && npm run test-browser && npm run test-tap", + "test-browser": "node ./node_modules/phantomify/bin/cmd.js ./test/common-index.js", + "test-node": "node ./test/common-index.js", + "test-tap": "node ./test/tap-index.js" + }, + "testling": { + "files": "test/tap-index.js", + "browsers": { + "iexplore": [ + 9, + 10 + ], + "chrome": [ + 16, + 20, + 25, + "canary" + ], + "firefox": [ + 10, + 15, + 16, + 17, + 18, + "nightly" + ], + "safari": [ + 5, + 6 + ], + "opera": [ + 12 + ] + } + }, + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/Gozala/enchain/License.md" + } + ], + "readme": "# querystring\n\n[![Build Status](https://secure.travis-ci.org/Gozala/querystring.png)](http://travis-ci.org/Gozala/querystring)\n\n\n[![Browser support](http://ci.testling.com/Gozala/querystring.png)](http://ci.testling.com/Gozala/querystring)\n\n\n\nNode's querystring module for all engines.\n\n## Install ##\n\n npm install querystring\n\n", + "readmeFilename": "Readme.md", + "homepage": "https://github.com/Gozala/querystring#readme", + "_id": "querystring@0.2.0", + "_shasum": "b209849203bb25df820da756e747005878521620", + "_resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", + "_from": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/.index.js.un~ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/.index.js.un~ new file mode 100644 index 0000000..898eced Binary files /dev/null and b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/.index.js.un~ differ diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/common-index.js b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/common-index.js new file mode 100644 index 0000000..f356f98 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/common-index.js @@ -0,0 +1,3 @@ +"use strict"; + +require("test").run(require("./index")) \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/index.js b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/index.js new file mode 100644 index 0000000..62eb2ac --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/index.js @@ -0,0 +1,210 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +"use strict"; + +// test using assert +var qs = require('../'); + +// folding block, commented to pass gjslint +// {{{ +// [ wonkyQS, canonicalQS, obj ] +var qsTestCases = [ + ['foo=918854443121279438895193', + 'foo=918854443121279438895193', + {'foo': '918854443121279438895193'}], + ['foo=bar', 'foo=bar', {'foo': 'bar'}], + ['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}], + ['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}], + ['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F', + 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', + {'my weird field': 'q1!2"\'w$5&7/z8)?' }], + ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}], + ['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}], + ['str=foo&arr=1&arr=2&arr=3&somenull=&undef=', + 'str=foo&arr=1&arr=2&arr=3&somenull=&undef=', + { 'str': 'foo', + 'arr': ['1', '2', '3'], + 'somenull': '', + 'undef': ''}], + [' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}], + // disable test that fails ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}], + ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], + // See: https://github.com/joyent/node/issues/1707 + ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + { hasOwnProperty: 'x', + toString: 'foo', + valueOf: 'bar', + __defineGetter__: 'baz' }], + // See: https://github.com/joyent/node/issues/3058 + ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }] +]; + +// [ wonkyQS, canonicalQS, obj ] +var qsColonTestCases = [ + ['foo:bar', 'foo:bar', {'foo': 'bar'}], + ['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], + ['foo:1&bar:2;baz:quux', + 'foo:1%26bar%3A2;baz:quux', + {'foo': '1&bar:2', 'baz': 'quux'}], + ['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}], + ['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}] +]; + +// [wonkyObj, qs, canonicalObj] +var extendedFunction = function() {}; +extendedFunction.prototype = {a: 'b'}; +var qsWeirdObjects = [ + [{regexp: /./g}, 'regexp=', {'regexp': ''}], + [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], + [{fn: function() {}}, 'fn=', {'fn': ''}], + [{fn: new Function('')}, 'fn=', {'fn': ''}], + [{math: Math}, 'math=', {'math': ''}], + [{e: extendedFunction}, 'e=', {'e': ''}], + [{d: new Date()}, 'd=', {'d': ''}], + [{d: Date}, 'd=', {'d': ''}], + [{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], + [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], + [{n: null}, 'n=', {'n': ''}], + [{nan: NaN}, 'nan=', {'nan': ''}], + [{inf: Infinity}, 'inf=', {'inf': ''}] +]; +// }}} + +var qsNoMungeTestCases = [ + ['', {}], + ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], + ['blah=burp', {'blah': 'burp'}], + ['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], + ['frappucino=muffin&goat%5B%5D=scone&pond=moose', + {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], + ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] +]; + +exports['test basic'] = function(assert) { + assert.strictEqual('918854443121279438895193', + qs.parse('id=918854443121279438895193').id, + 'prase id=918854443121279438895193'); +}; + +exports['test that the canonical qs is parsed properly'] = function(assert) { + qsTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[0]), + 'parse ' + testCase[0]); + }); +}; + + +exports['test that the colon test cases can do the same'] = function(assert) { + qsColonTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[0], ';', ':'), + 'parse ' + testCase[0] + ' -> ; :'); + }); +}; + +exports['test the weird objects, that they get parsed properly'] = function(assert) { + qsWeirdObjects.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[1]), + 'parse ' + testCase[1]); + }); +}; + +exports['test non munge test cases'] = function(assert) { + qsNoMungeTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=', false), + 'stringify ' + JSON.stringify(testCase[1]) + ' -> & ='); + }); +}; + +exports['test the nested qs-in-qs case'] = function(assert) { + var f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); + f.q = qs.parse(f.q); + assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }, + 'parse a=b&q=x%3Dy%26y%3Dz'); +}; + +exports['test nested in colon'] = function(assert) { + var f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); + f.q = qs.parse(f.q, ';', ':'); + assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }, + 'parse a:b;q:x%3Ay%3By%3Az -> ; :'); +}; + +exports['test stringifying'] = function(assert) { + qsTestCases.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[2]), + 'stringify ' + JSON.stringify(testCase[2])); + }); + + qsColonTestCases.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':'), + 'stringify ' + JSON.stringify(testCase[2]) + ' -> ; :'); + }); + + qsWeirdObjects.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[0]), + 'stringify ' + JSON.stringify(testCase[0])); + }); +}; + +exports['test stringifying nested'] = function(assert) { + var f = qs.stringify({ + a: 'b', + q: qs.stringify({ + x: 'y', + y: 'z' + }) + }); + assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz', + JSON.stringify({ + a: 'b', + 'qs.stringify -> q': { + x: 'y', + y: 'z' + } + })); + + var threw = false; + try { qs.parse(undefined); } catch(error) { threw = true; } + assert.ok(!threw, "does not throws on undefined"); +}; + +exports['test nested in colon'] = function(assert) { + var f = qs.stringify({ + a: 'b', + q: qs.stringify({ + x: 'y', + y: 'z' + }, ';', ':') + }, ';', ':'); + assert.equal(f, 'a:b;q:x%3Ay%3By%3Az', + 'stringify ' + JSON.stringify({ + a: 'b', + 'qs.stringify -> q': { + x: 'y', + y: 'z' + } + }) + ' -> ; : '); + + + assert.deepEqual({}, qs.parse(), 'parse undefined'); +}; diff --git a/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/tap-index.js b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/tap-index.js new file mode 100644 index 0000000..70679b3 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/node_modules/querystring/test/tap-index.js @@ -0,0 +1,3 @@ +"use strict"; + +require("retape")(require("./index")) \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/url/package.json b/node_modules/meteor-node-stubs/node_modules/url/package.json new file mode 100644 index 0000000..8219c5d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/package.json @@ -0,0 +1,34 @@ +{ + "name": "url", + "description": "The core `url` packaged standalone for use with Browserify.", + "version": "0.11.0", + "dependencies": { + "punycode": "1.3.2", + "querystring": "0.2.0" + }, + "main": "./url.js", + "devDependencies": { + "assert": "1.1.1", + "mocha": "1.18.2", + "zuul": "3.3.0" + }, + "scripts": { + "test": "mocha --ui qunit test.js && zuul -- test.js", + "test-local": "zuul --local -- test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/defunctzombie/node-url.git" + }, + "license": "MIT", + "readme": "# node-url\n\n[![Build Status](https://travis-ci.org/defunctzombie/node-url.svg?branch=master)](https://travis-ci.org/defunctzombie/node-url)\n\nThis module has utilities for URL resolution and parsing meant to have feature parity with node.js core [url](http://nodejs.org/api/url.html) module.\n\n```js\nvar url = require('url');\n```\n\n## api\n\nParsed URL objects have some or all of the following fields, depending on\nwhether or not they exist in the URL string. Any parts that are not in the URL\nstring will not be in the parsed object. Examples are shown for the URL\n\n`'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'`\n\n* `href`: The full URL that was originally parsed. Both the protocol and host are lowercased.\n\n Example: `'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'`\n\n* `protocol`: The request protocol, lowercased.\n\n Example: `'http:'`\n\n* `host`: The full lowercased host portion of the URL, including port\n information.\n\n Example: `'host.com:8080'`\n\n* `auth`: The authentication information portion of a URL.\n\n Example: `'user:pass'`\n\n* `hostname`: Just the lowercased hostname portion of the host.\n\n Example: `'host.com'`\n\n* `port`: The port number portion of the host.\n\n Example: `'8080'`\n\n* `pathname`: The path section of the URL, that comes after the host and\n before the query, including the initial slash if present.\n\n Example: `'/p/a/t/h'`\n\n* `search`: The 'query string' portion of the URL, including the leading\n question mark.\n\n Example: `'?query=string'`\n\n* `path`: Concatenation of `pathname` and `search`.\n\n Example: `'/p/a/t/h?query=string'`\n\n* `query`: Either the 'params' portion of the query string, or a\n querystring-parsed object.\n\n Example: `'query=string'` or `{'query':'string'}`\n\n* `hash`: The 'fragment' portion of the URL including the pound-sign.\n\n Example: `'#hash'`\n\nThe following methods are provided by the URL module:\n\n### url.parse(urlStr, [parseQueryString], [slashesDenoteHost])\n\nTake a URL string, and return an object.\n\nPass `true` as the second argument to also parse\nthe query string using the `querystring` module.\nDefaults to `false`.\n\nPass `true` as the third argument to treat `//foo/bar` as\n`{ host: 'foo', pathname: '/bar' }` rather than\n`{ pathname: '//foo/bar' }`. Defaults to `false`.\n\n### url.format(urlObj)\n\nTake a parsed URL object, and return a formatted URL string.\n\n* `href` will be ignored.\n* `protocol` is treated the same with or without the trailing `:` (colon).\n * The protocols `http`, `https`, `ftp`, `gopher`, `file` will be\n postfixed with `://` (colon-slash-slash).\n * All other protocols `mailto`, `xmpp`, `aim`, `sftp`, `foo`, etc will\n be postfixed with `:` (colon)\n* `auth` will be used if present.\n* `hostname` will only be used if `host` is absent.\n* `port` will only be used if `host` is absent.\n* `host` will be used in place of `hostname` and `port`\n* `pathname` is treated the same with or without the leading `/` (slash)\n* `search` will be used in place of `query`\n* `query` (object; see `querystring`) will only be used if `search` is absent.\n* `search` is treated the same with or without the leading `?` (question mark)\n* `hash` is treated the same with or without the leading `#` (pound sign, anchor)\n\n### url.resolve(from, to)\n\nTake a base URL, and a href URL, and resolve them as a browser would for\nan anchor tag. Examples:\n\n url.resolve('/one/two/three', 'four') // '/one/two/four'\n url.resolve('http://example.com/', '/one') // 'http://example.com/one'\n url.resolve('http://example.com/one', '/two') // 'http://example.com/two'\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/defunctzombie/node-url/issues" + }, + "homepage": "https://github.com/defunctzombie/node-url#readme", + "_id": "url@0.11.0", + "_shasum": "3838e97cfc60521eb73c525a8e55bfdd9e2e28f1", + "_resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "_from": "https://registry.npmjs.org/url/-/url-0.11.0.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/url/test.js b/node_modules/meteor-node-stubs/node_modules/url/test.js new file mode 100644 index 0000000..3b7d335 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/test.js @@ -0,0 +1,1599 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); + +var url = require('./url'); + +// URLs to parse, and expected data +// { url : parsed } +var parseTests = { + '//some_path' : { + 'href': '//some_path', + 'pathname': '//some_path', + 'path': '//some_path' + }, + + 'http:\\\\evil-phisher\\foo.html#h\\a\\s\\h': { + protocol: 'http:', + slashes: true, + host: 'evil-phisher', + hostname: 'evil-phisher', + pathname: '/foo.html', + path: '/foo.html', + hash: '#h%5Ca%5Cs%5Ch', + href: 'http://evil-phisher/foo.html#h%5Ca%5Cs%5Ch' + }, + + 'http:\\\\evil-phisher\\foo.html?json="\\"foo\\""#h\\a\\s\\h': { + protocol: 'http:', + slashes: true, + host: 'evil-phisher', + hostname: 'evil-phisher', + pathname: '/foo.html', + search: '?json=%22%5C%22foo%5C%22%22', + query: 'json=%22%5C%22foo%5C%22%22', + path: '/foo.html?json=%22%5C%22foo%5C%22%22', + hash: '#h%5Ca%5Cs%5Ch', + href: 'http://evil-phisher/foo.html?json=%22%5C%22foo%5C%22%22#h%5Ca%5Cs%5Ch' + }, + + 'http:\\\\evil-phisher\\foo.html#h\\a\\s\\h?blarg': { + protocol: 'http:', + slashes: true, + host: 'evil-phisher', + hostname: 'evil-phisher', + pathname: '/foo.html', + path: '/foo.html', + hash: '#h%5Ca%5Cs%5Ch?blarg', + href: 'http://evil-phisher/foo.html#h%5Ca%5Cs%5Ch?blarg' + }, + + + 'http:\\\\evil-phisher\\foo.html': { + protocol: 'http:', + slashes: true, + host: 'evil-phisher', + hostname: 'evil-phisher', + pathname: '/foo.html', + path: '/foo.html', + href: 'http://evil-phisher/foo.html' + }, + + 'HTTP://www.example.com/' : { + 'href': 'http://www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'HTTP://www.example.com' : { + 'href': 'http://www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.ExAmPlE.com/' : { + 'href': 'http://www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user:pw@www.ExAmPlE.com/' : { + 'href': 'http://user:pw@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pw', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://USER:PW@www.ExAmPlE.com/' : { + 'href': 'http://USER:PW@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'USER:PW', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user@www.example.com/' : { + 'href': 'http://user@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user%3Apw@www.example.com/' : { + 'href': 'http://user:pw@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pw', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://x.com/path?that\'s#all, folks' : { + 'href': 'http://x.com/path?that%27s#all,%20folks', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.com', + 'hostname': 'x.com', + 'search': '?that%27s', + 'query': 'that%27s', + 'pathname': '/path', + 'hash': '#all,%20folks', + 'path': '/path?that%27s' + }, + + 'HTTP://X.COM/Y' : { + 'href': 'http://x.com/Y', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.com', + 'hostname': 'x.com', + 'pathname': '/Y', + 'path': '/Y' + }, + + // + not an invalid host character + // per https://url.spec.whatwg.org/#host-parsing + 'http://x.y.com+a/b/c' : { + 'href': 'http://x.y.com+a/b/c', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.y.com+a', + 'hostname': 'x.y.com+a', + 'pathname': '/b/c', + 'path': '/b/c' + }, + + // an unexpected invalid char in the hostname. + 'HtTp://x.y.cOm;a/b/c?d=e#f gi' : { + 'href': 'http://x.y.com/;a/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.y.com', + 'hostname': 'x.y.com', + 'pathname': ';a/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': ';a/b/c?d=e' + }, + + // make sure that we don't accidentally lcast the path parts. + 'HtTp://x.y.cOm;A/b/c?d=e#f gi' : { + 'href': 'http://x.y.com/;A/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.y.com', + 'hostname': 'x.y.com', + 'pathname': ';A/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': ';A/b/c?d=e' + }, + + 'http://x...y...#p': { + 'href': 'http://x...y.../#p', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x...y...', + 'hostname': 'x...y...', + 'hash': '#p', + 'pathname': '/', + 'path': '/' + }, + + 'http://x/p/"quoted"': { + 'href': 'http://x/p/%22quoted%22', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x', + 'hostname': 'x', + 'pathname': '/p/%22quoted%22', + 'path': '/p/%22quoted%22' + }, + + ' Is a URL!': { + 'href': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', + 'pathname': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', + 'path': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!' + }, + + 'http://www.narwhaljs.org/blog/categories?id=news' : { + 'href': 'http://www.narwhaljs.org/blog/categories?id=news', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.narwhaljs.org', + 'hostname': 'www.narwhaljs.org', + 'search': '?id=news', + 'query': 'id=news', + 'pathname': '/blog/categories', + 'path': '/blog/categories?id=news' + }, + + 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' : { + 'href': 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'hostname': 'mt0.google.com', + 'pathname': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', + 'path': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' : { + 'href': 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api' + + '&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'hostname': 'mt0.google.com', + 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', + 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', + 'pathname': '/vt/lyrs=m@114', + 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'http://user:pass@mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=': + { + 'href': 'http://user:pass@mt0.google.com/vt/lyrs=m@114???' + + '&hl=en&src=api&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'auth': 'user:pass', + 'hostname': 'mt0.google.com', + 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', + 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', + 'pathname': '/vt/lyrs=m@114', + 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'file:///etc/passwd' : { + 'href': 'file:///etc/passwd', + 'slashes': true, + 'protocol': 'file:', + 'pathname': '/etc/passwd', + 'hostname': '', + 'host': '', + 'path': '/etc/passwd' + }, + + 'file://localhost/etc/passwd' : { + 'href': 'file://localhost/etc/passwd', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/passwd', + 'hostname': 'localhost', + 'host': 'localhost', + 'path': '/etc/passwd' + }, + + 'file://foo/etc/passwd' : { + 'href': 'file://foo/etc/passwd', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/passwd', + 'hostname': 'foo', + 'host': 'foo', + 'path': '/etc/passwd' + }, + + 'file:///etc/node/' : { + 'href': 'file:///etc/node/', + 'slashes': true, + 'protocol': 'file:', + 'pathname': '/etc/node/', + 'hostname': '', + 'host': '', + 'path': '/etc/node/' + }, + + 'file://localhost/etc/node/' : { + 'href': 'file://localhost/etc/node/', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/node/', + 'hostname': 'localhost', + 'host': 'localhost', + 'path': '/etc/node/' + }, + + 'file://foo/etc/node/' : { + 'href': 'file://foo/etc/node/', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/node/', + 'hostname': 'foo', + 'host': 'foo', + 'path': '/etc/node/' + }, + + 'http:/baz/../foo/bar' : { + 'href': 'http:/baz/../foo/bar', + 'protocol': 'http:', + 'pathname': '/baz/../foo/bar', + 'path': '/baz/../foo/bar' + }, + + 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag' : { + 'href': 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com:8000', + 'auth': 'user:pass', + 'port': '8000', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + '//user:pass@example.com:8000/foo/bar?baz=quux#frag' : { + 'href': '//user:pass@example.com:8000/foo/bar?baz=quux#frag', + 'slashes': true, + 'host': 'example.com:8000', + 'auth': 'user:pass', + 'port': '8000', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + '/foo/bar?baz=quux#frag' : { + 'href': '/foo/bar?baz=quux#frag', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + 'http:/foo/bar?baz=quux#frag' : { + 'href': 'http:/foo/bar?baz=quux#frag', + 'protocol': 'http:', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + 'mailto:foo@bar.com?subject=hello' : { + 'href': 'mailto:foo@bar.com?subject=hello', + 'protocol': 'mailto:', + 'host': 'bar.com', + 'auth' : 'foo', + 'hostname' : 'bar.com', + 'search': '?subject=hello', + 'query': 'subject=hello', + 'path': '?subject=hello' + }, + + 'javascript:alert(\'hello\');' : { + 'href': 'javascript:alert(\'hello\');', + 'protocol': 'javascript:', + 'pathname': 'alert(\'hello\');', + 'path': 'alert(\'hello\');' + }, + + 'xmpp:isaacschlueter@jabber.org' : { + 'href': 'xmpp:isaacschlueter@jabber.org', + 'protocol': 'xmpp:', + 'host': 'jabber.org', + 'auth': 'isaacschlueter', + 'hostname': 'jabber.org' + }, + + 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar' : { + 'href' : 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar', + 'protocol' : 'http:', + 'slashes': true, + 'host' : '127.0.0.1:8080', + 'auth' : 'atpass:foo@bar', + 'hostname' : '127.0.0.1', + 'port' : '8080', + 'pathname': '/path', + 'search' : '?search=foo', + 'query' : 'search=foo', + 'hash' : '#bar', + 'path': '/path?search=foo' + }, + + 'svn+ssh://foo/bar': { + 'href': 'svn+ssh://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'svn+ssh:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dash-test://foo/bar': { + 'href': 'dash-test://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dash-test:foo/bar': { + 'href': 'dash-test:foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'path': '/bar' + }, + + 'dot.test://foo/bar': { + 'href': 'dot.test://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dot.test:foo/bar': { + 'href': 'dot.test:foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'path': '/bar' + }, + + // IDNA tests + 'http://www.日本語.com/' : { + 'href': 'http://www.xn--wgv71a119e.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--wgv71a119e.com', + 'hostname': 'www.xn--wgv71a119e.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://example.Bücher.com/' : { + 'href': 'http://example.xn--bcher-kva.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.xn--bcher-kva.com', + 'hostname': 'example.xn--bcher-kva.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.Äffchen.com/' : { + 'href': 'http://www.xn--ffchen-9ta.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--ffchen-9ta.com', + 'hostname': 'www.xn--ffchen-9ta.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.Äffchen.cOm;A/b/c?d=e#f gi' : { + 'href': 'http://www.xn--ffchen-9ta.com/;A/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--ffchen-9ta.com', + 'hostname': 'www.xn--ffchen-9ta.com', + 'pathname': ';A/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': ';A/b/c?d=e' + }, + + 'http://SÉLIER.COM/' : { + 'href': 'http://xn--slier-bsa.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--slier-bsa.com', + 'hostname': 'xn--slier-bsa.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://ليهمابتكلموشعربي؟.ي؟/' : { + 'href': 'http://xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', + 'hostname': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', + 'pathname': '/', + 'path': '/' + }, + + 'http://➡.ws/➡' : { + 'href': 'http://xn--hgi.ws/➡', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--hgi.ws', + 'hostname': 'xn--hgi.ws', + 'pathname': '/➡', + 'path': '/➡' + }, + + 'http://bucket_name.s3.amazonaws.com/image.jpg': { + protocol: 'http:', + 'slashes': true, + slashes: true, + host: 'bucket_name.s3.amazonaws.com', + hostname: 'bucket_name.s3.amazonaws.com', + pathname: '/image.jpg', + href: 'http://bucket_name.s3.amazonaws.com/image.jpg', + 'path': '/image.jpg' + }, + + 'git+http://github.com/joyent/node.git': { + protocol: 'git+http:', + slashes: true, + host: 'github.com', + hostname: 'github.com', + pathname: '/joyent/node.git', + path: '/joyent/node.git', + href: 'git+http://github.com/joyent/node.git' + }, + + //if local1@domain1 is uses as a relative URL it may + //be parse into auth@hostname, but here there is no + //way to make it work in url.parse, I add the test to be explicit + 'local1@domain1': { + 'pathname': 'local1@domain1', + 'path': 'local1@domain1', + 'href': 'local1@domain1' + }, + + //While this may seem counter-intuitive, a browser will parse + // as a path. + 'www.example.com' : { + 'href': 'www.example.com', + 'pathname': 'www.example.com', + 'path': 'www.example.com' + }, + + // ipv6 support + '[fe80::1]': { + 'href': '[fe80::1]', + 'pathname': '[fe80::1]', + 'path': '[fe80::1]' + }, + + 'coap://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]': { + 'protocol': 'coap:', + 'slashes': true, + 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]', + 'hostname': 'fedc:ba98:7654:3210:fedc:ba98:7654:3210', + 'href': 'coap://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/', + 'pathname': '/', + 'path': '/' + }, + + 'coap://[1080:0:0:0:8:800:200C:417A]:61616/': { + 'protocol': 'coap:', + 'slashes': true, + 'host': '[1080:0:0:0:8:800:200c:417a]:61616', + 'port': '61616', + 'hostname': '1080:0:0:0:8:800:200c:417a', + 'href': 'coap://[1080:0:0:0:8:800:200c:417a]:61616/', + 'pathname': '/', + 'path': '/' + }, + + 'http://user:password@[3ffe:2a00:100:7031::1]:8080': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:password', + 'host': '[3ffe:2a00:100:7031::1]:8080', + 'port': '8080', + 'hostname': '3ffe:2a00:100:7031::1', + 'href': 'http://user:password@[3ffe:2a00:100:7031::1]:8080/', + 'pathname': '/', + 'path': '/' + }, + + 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature': { + 'protocol': 'coap:', + 'slashes': true, + 'auth': 'u:p', + 'host': '[::192.9.5.5]:61616', + 'port': '61616', + 'hostname': '::192.9.5.5', + 'href': 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature', + 'search': '?n=Temperature', + 'query': 'n=Temperature', + 'pathname': '/.well-known/r', + 'path': '/.well-known/r?n=Temperature' + }, + + // empty port + 'http://example.com:': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/', + 'pathname': '/', + 'path': '/' + }, + + 'http://example.com:/a/b.html': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/a/b.html', + 'pathname': '/a/b.html', + 'path': '/a/b.html' + }, + + 'http://example.com:?a=b': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/?a=b', + 'search': '?a=b', + 'query': 'a=b', + 'pathname': '/', + 'path': '/?a=b' + }, + + 'http://example.com:#abc': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/#abc', + 'hash': '#abc', + 'pathname': '/', + 'path': '/' + }, + + 'http://[fe80::1]:/a/b?a=b#abc': { + 'protocol': 'http:', + 'slashes': true, + 'host': '[fe80::1]', + 'hostname': 'fe80::1', + 'href': 'http://[fe80::1]/a/b?a=b#abc', + 'search': '?a=b', + 'query': 'a=b', + 'hash': '#abc', + 'pathname': '/a/b', + 'path': '/a/b?a=b' + }, + + 'http://-lovemonsterz.tumblr.com/rss': { + 'protocol': 'http:', + 'slashes': true, + 'host': '-lovemonsterz.tumblr.com', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://-lovemonsterz.tumblr.com/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://-lovemonsterz.tumblr.com:80/rss': { + 'protocol': 'http:', + 'slashes': true, + 'port': '80', + 'host': '-lovemonsterz.tumblr.com:80', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://-lovemonsterz.tumblr.com:80/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://user:pass@-lovemonsterz.tumblr.com/rss': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'host': '-lovemonsterz.tumblr.com', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://user:pass@-lovemonsterz.tumblr.com/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://user:pass@-lovemonsterz.tumblr.com:80/rss': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'port': '80', + 'host': '-lovemonsterz.tumblr.com:80', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://user:pass@-lovemonsterz.tumblr.com:80/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://_jabber._tcp.google.com/test': { + 'protocol': 'http:', + 'slashes': true, + 'host': '_jabber._tcp.google.com', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://_jabber._tcp.google.com/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://user:pass@_jabber._tcp.google.com/test': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'host': '_jabber._tcp.google.com', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://user:pass@_jabber._tcp.google.com/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://_jabber._tcp.google.com:80/test': { + 'protocol': 'http:', + 'slashes': true, + 'port': '80', + 'host': '_jabber._tcp.google.com:80', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://_jabber._tcp.google.com:80/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://user:pass@_jabber._tcp.google.com:80/test': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'port': '80', + 'host': '_jabber._tcp.google.com:80', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://user:pass@_jabber._tcp.google.com:80/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://x:1/\' <>"`/{}|\\^~`/': { + protocol: 'http:', + slashes: true, + host: 'x:1', + port: '1', + hostname: 'x', + pathname: '/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/', + path: '/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/', + href: 'http://x:1/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/' + }, + + 'http://a@b@c/': { + protocol: 'http:', + slashes: true, + auth: 'a@b', + host: 'c', + hostname: 'c', + href: 'http://a%40b@c/', + path: '/', + pathname: '/' + }, + + 'http://a@b?@c': { + protocol: 'http:', + slashes: true, + auth: 'a', + host: 'b', + hostname: 'b', + href: 'http://a@b/?@c', + path: '/?@c', + pathname: '/', + search: '?@c', + query: '@c' + }, + + 'http://a\r" \t\n<\'b:b@c\r\nd/e?f':{ + protocol: 'http:', + slashes: true, + auth: 'a\r" \t\n<\'b:b', + host: 'c', + port: null, + hostname: 'c', + hash: null, + search: '?f', + query: 'f', + pathname: '%0D%0Ad/e', + path: '%0D%0Ad/e?f', + href: 'http://a%0D%22%20%09%0A%3C\'b:b@c/%0D%0Ad/e?f' + }, + + // git urls used by npm + 'git+ssh://git@github.com:npm/npm': { + protocol: 'git+ssh:', + slashes: true, + auth: 'git', + host: 'github.com', + port: null, + hostname: 'github.com', + hash: null, + search: null, + query: null, + pathname: '/:npm/npm', + path: '/:npm/npm', + href: 'git+ssh://git@github.com/:npm/npm' + } + +}; + +Object.keys(parseTests).forEach(function(u) { + test('parse(' + u + ')', function() { + var actual = url.parse(u), + spaced = url.parse(' \t ' + u + '\n\t'); + expected = parseTests[u]; + + Object.keys(actual).forEach(function (i) { + if (expected[i] === undefined && actual[i] === null) { + expected[i] = null; + } + }); + + assert.deepEqual(actual, expected); + assert.deepEqual(spaced, expected); + + var expected = parseTests[u].href, + actual = url.format(parseTests[u]); + + assert.equal(actual, expected, + 'format(' + u + ') == ' + u + '\nactual:' + actual); + }); +}); + +var parseTestsWithQueryString = { + '/foo/bar?baz=quux#frag' : { + 'href': '/foo/bar?baz=quux#frag', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': { + 'baz': 'quux' + }, + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + 'http://example.com' : { + 'href': 'http://example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'query': {}, + 'search': '', + 'pathname': '/', + 'path': '/' + }, + '/example': { + protocol: null, + slashes: null, + auth: null, + host: null, + port: null, + hostname: null, + hash: null, + search: '', + query: {}, + pathname: '/example', + path: '/example', + href: '/example' + }, + '/example?query=value':{ + protocol: null, + slashes: null, + auth: null, + host: null, + port: null, + hostname: null, + hash: null, + search: '?query=value', + query: { query: 'value' }, + pathname: '/example', + path: '/example?query=value', + href: '/example?query=value' + } +}; + +Object.keys(parseTestsWithQueryString).forEach(function(u) { + test('parse(' + u + ')', function() { + var actual = url.parse(u, true); + var expected = parseTestsWithQueryString[u]; + for (var i in actual) { + if (actual[i] === null && expected[i] === undefined) { + expected[i] = null; + } + } + + assert.deepEqual(actual, expected); + }); +}); + +// some extra formatting tests, just to verify +// that it'll format slightly wonky content to a valid url. +var formatTests = { + 'http://example.com?' : { + 'href': 'http://example.com/?', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'search': '?', + 'query': {}, + 'pathname': '/' + }, + 'http://example.com?foo=bar#frag' : { + 'href': 'http://example.com/?foo=bar#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=bar', + 'query': 'foo=bar', + 'pathname': '/' + }, + 'http://example.com?foo=@bar#frag' : { + 'href': 'http://example.com/?foo=@bar#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=@bar', + 'query': 'foo=@bar', + 'pathname': '/' + }, + 'http://example.com?foo=/bar/#frag' : { + 'href': 'http://example.com/?foo=/bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=/bar/', + 'query': 'foo=/bar/', + 'pathname': '/' + }, + 'http://example.com?foo=?bar/#frag' : { + 'href': 'http://example.com/?foo=?bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=?bar/', + 'query': 'foo=?bar/', + 'pathname': '/' + }, + 'http://example.com#frag=?bar/#frag' : { + 'href': 'http://example.com/#frag=?bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag=?bar/#frag', + 'pathname': '/' + }, + 'http://google.com" onload="alert(42)/' : { + 'href': 'http://google.com/%22%20onload=%22alert(42)/', + 'protocol': 'http:', + 'host': 'google.com', + 'pathname': '/%22%20onload=%22alert(42)/' + }, + 'http://a.com/a/b/c?s#h' : { + 'href': 'http://a.com/a/b/c?s#h', + 'protocol': 'http', + 'host': 'a.com', + 'pathname': 'a/b/c', + 'hash': 'h', + 'search': 's' + }, + 'xmpp:isaacschlueter@jabber.org' : { + 'href': 'xmpp:isaacschlueter@jabber.org', + 'protocol': 'xmpp:', + 'host': 'jabber.org', + 'auth': 'isaacschlueter', + 'hostname': 'jabber.org' + }, + 'http://atpass:foo%40bar@127.0.0.1/' : { + 'href': 'http://atpass:foo%40bar@127.0.0.1/', + 'auth': 'atpass:foo@bar', + 'hostname': '127.0.0.1', + 'protocol': 'http:', + 'pathname': '/' + }, + 'http://atslash%2F%40:%2F%40@foo/' : { + 'href': 'http://atslash%2F%40:%2F%40@foo/', + 'auth': 'atslash/@:/@', + 'hostname': 'foo', + 'protocol': 'http:', + 'pathname': '/' + }, + 'svn+ssh://foo/bar': { + 'href': 'svn+ssh://foo/bar', + 'hostname': 'foo', + 'protocol': 'svn+ssh:', + 'pathname': '/bar', + 'slashes': true + }, + 'dash-test://foo/bar': { + 'href': 'dash-test://foo/bar', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'slashes': true + }, + 'dash-test:foo/bar': { + 'href': 'dash-test:foo/bar', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar' + }, + 'dot.test://foo/bar': { + 'href': 'dot.test://foo/bar', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'slashes': true + }, + 'dot.test:foo/bar': { + 'href': 'dot.test:foo/bar', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar' + }, + // ipv6 support + 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature': { + 'href': 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature', + 'protocol': 'coap:', + 'auth': 'u:p', + 'hostname': '::1', + 'port': '61616', + 'pathname': '/.well-known/r', + 'search': 'n=Temperature' + }, + 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton': { + 'href': 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton', + 'protocol': 'coap', + 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616', + 'pathname': '/s/stopButton' + }, + + // encode context-specific delimiters in path and query, but do not touch + // other non-delimiter chars like `%`. + // + + // `#`,`?` in path + '/path/to/%%23%3F+=&.txt?foo=theA1#bar' : { + href : '/path/to/%%23%3F+=&.txt?foo=theA1#bar', + pathname: '/path/to/%#?+=&.txt', + query: { + foo: 'theA1' + }, + hash: "#bar" + }, + + // `#`,`?` in path + `#` in query + '/path/to/%%23%3F+=&.txt?foo=the%231#bar' : { + href : '/path/to/%%23%3F+=&.txt?foo=the%231#bar', + pathname: '/path/to/%#?+=&.txt', + query: { + foo: 'the#1' + }, + hash: "#bar" + }, + + // `?` and `#` in path and search + 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag': { + href: 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag', + protocol: 'http:', + hostname: 'ex.com', + hash: '#frag', + search: '?abc=the#1?&foo=bar', + pathname: '/foo?100%m#r', + }, + + // `?` and `#` in search only + 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag': { + href: 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag', + protocol: 'http:', + hostname: 'ex.com', + hash: '#frag', + search: '?abc=the#1?&foo=bar', + pathname: '/fooA100%mBr', + } +}; + +Object.keys(formatTests).forEach(function(u) { + test('format(' + u + ')', function() { + var expect = formatTests[u].href; + delete formatTests[u].href; + var actual = url.format(u); + var actualObj = url.format(formatTests[u]); + assert.equal(actual, expect, + 'wonky format(' + u + ') == ' + expect + + '\nactual:' + actual); + assert.equal(actualObj, expect, + 'wonky format(' + JSON.stringify(formatTests[u]) + + ') == ' + expect + + '\nactual: ' + actualObj); + }); +}); + +/* + [from, path, expected] +*/ +var relativeTests = [ + ['/foo/bar/baz', 'quux', '/foo/bar/quux'], + ['/foo/bar/baz', 'quux/asdf', '/foo/bar/quux/asdf'], + ['/foo/bar/baz', 'quux/baz', '/foo/bar/quux/baz'], + ['/foo/bar/baz', '../quux/baz', '/foo/quux/baz'], + ['/foo/bar/baz', '/bar', '/bar'], + ['/foo/bar/baz/', 'quux', '/foo/bar/baz/quux'], + ['/foo/bar/baz/', 'quux/baz', '/foo/bar/baz/quux/baz'], + ['/foo/bar/baz', '../../../../../../../../quux/baz', '/quux/baz'], + ['/foo/bar/baz', '../../../../../../../quux/baz', '/quux/baz'], + ['/foo', '.', '/'], + ['/foo', '..', '/'], + ['/foo/', '.', '/foo/'], + ['/foo/', '..', '/'], + ['/foo/bar', '.', '/foo/'], + ['/foo/bar', '..', '/'], + ['/foo/bar/', '.', '/foo/bar/'], + ['/foo/bar/', '..', '/foo/'], + ['foo/bar', '../../../baz', '../../baz'], + ['foo/bar/', '../../../baz', '../baz'], + ['http://example.com/b//c//d;p?q#blarg', 'https:#hash2', 'https:///#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https:/p/a/t/h?s#hash2', + 'https://p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https://u:p@h.com/p/a/t/h?s#hash2', + 'https://u:p@h.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https:/a/b/c/d', + 'https://a/b/c/d'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:#hash2', + 'http://example.com/b//c//d;p?q#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:/p/a/t/h?s#hash2', + 'http://example.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http://u:p@h.com/p/a/t/h?s#hash2', + 'http://u:p@h.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:/a/b/c/d', + 'http://example.com/a/b/c/d'], + ['/foo/bar/baz', '/../etc/passwd', '/etc/passwd'] +]; + +relativeTests.forEach(function(relativeTest) { + test('resolve(' + [relativeTest[0], relativeTest[1]] + ')', function() { + var a = url.resolve(relativeTest[0], relativeTest[1]), + e = relativeTest[2]; + assert.equal(a, e, + 'resolve(' + [relativeTest[0], relativeTest[1]] + ') == ' + e + + '\n actual=' + a); + }); +}); + + +// https://github.com/joyent/node/issues/568 +[ + undefined, + null, + true, + false, + 0.0, + 0, + [], + {} +].forEach(function(val) { + test('parse(' + val + ')', function() { + assert.throws(function() { url.parse(val); }, TypeError); + }); +}); + + +// +// Tests below taken from Chiron +// http://code.google.com/p/chironjs/source/browse/trunk/src/test/http/url.js +// +// Copyright (c) 2002-2008 Kris Kowal +// used with permission under MIT License +// +// Changes marked with @isaacs + +var bases = [ + 'http://a/b/c/d;p?q', + 'http://a/b/c/d;p?q=1/2', + 'http://a/b/c/d;p=1/2?q', + 'fred:///s//a/b/c', + 'http:///s//a/b/c' +]; + +//[to, from, result] +var relativeTests2 = [ + // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html + ['../c', 'foo:a/b', 'foo:c'], + ['foo:.', 'foo:a', 'foo:'], + ['/foo/../../../bar', 'zz:abc', 'zz:/bar'], + ['/foo/../bar', 'zz:abc', 'zz:/bar'], + // @isaacs Disagree. Not how web browsers resolve this. + ['foo/../../../bar', 'zz:abc', 'zz:bar'], + // ['foo/../../../bar', 'zz:abc', 'zz:../../bar'], // @isaacs Added + ['foo/../bar', 'zz:abc', 'zz:bar'], + ['zz:.', 'zz:abc', 'zz:'], + ['/.', bases[0], 'http://a/'], + ['/.foo', bases[0], 'http://a/.foo'], + ['.foo', bases[0], 'http://a/b/c/.foo'], + + // http://gbiv.com/protocols/uri/test/rel_examples1.html + // examples from RFC 2396 + ['g:h', bases[0], 'g:h'], + ['g', bases[0], 'http://a/b/c/g'], + ['./g', bases[0], 'http://a/b/c/g'], + ['g/', bases[0], 'http://a/b/c/g/'], + ['/g', bases[0], 'http://a/g'], + ['//g', bases[0], 'http://g/'], + // changed with RFC 2396bis + //('?y', bases[0], 'http://a/b/c/d;p?y'], + ['?y', bases[0], 'http://a/b/c/d;p?y'], + ['g?y', bases[0], 'http://a/b/c/g?y'], + // changed with RFC 2396bis + //('#s', bases[0], CURRENT_DOC_URI + '#s'], + ['#s', bases[0], 'http://a/b/c/d;p?q#s'], + ['g#s', bases[0], 'http://a/b/c/g#s'], + ['g?y#s', bases[0], 'http://a/b/c/g?y#s'], + [';x', bases[0], 'http://a/b/c/;x'], + ['g;x', bases[0], 'http://a/b/c/g;x'], + ['g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'], + // changed with RFC 2396bis + //('', bases[0], CURRENT_DOC_URI], + ['', bases[0], 'http://a/b/c/d;p?q'], + ['.', bases[0], 'http://a/b/c/'], + ['./', bases[0], 'http://a/b/c/'], + ['..', bases[0], 'http://a/b/'], + ['../', bases[0], 'http://a/b/'], + ['../g', bases[0], 'http://a/b/g'], + ['../..', bases[0], 'http://a/'], + ['../../', bases[0], 'http://a/'], + ['../../g' , bases[0], 'http://a/g'], + ['../../../g', bases[0], ('http://a/../g', 'http://a/g')], + ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], + // changed with RFC 2396bis + //('/./g', bases[0], 'http://a/./g'], + ['/./g', bases[0], 'http://a/g'], + // changed with RFC 2396bis + //('/../g', bases[0], 'http://a/../g'], + ['/../g', bases[0], 'http://a/g'], + ['g.', bases[0], 'http://a/b/c/g.'], + ['.g', bases[0], 'http://a/b/c/.g'], + ['g..', bases[0], 'http://a/b/c/g..'], + ['..g', bases[0], 'http://a/b/c/..g'], + ['./../g', bases[0], 'http://a/b/g'], + ['./g/.', bases[0], 'http://a/b/c/g/'], + ['g/./h', bases[0], 'http://a/b/c/g/h'], + ['g/../h', bases[0], 'http://a/b/c/h'], + ['g;x=1/./y', bases[0], 'http://a/b/c/g;x=1/y'], + ['g;x=1/../y', bases[0], 'http://a/b/c/y'], + ['g?y/./x', bases[0], 'http://a/b/c/g?y/./x'], + ['g?y/../x', bases[0], 'http://a/b/c/g?y/../x'], + ['g#s/./x', bases[0], 'http://a/b/c/g#s/./x'], + ['g#s/../x', bases[0], 'http://a/b/c/g#s/../x'], + ['http:g', bases[0], ('http:g', 'http://a/b/c/g')], + ['http:', bases[0], ('http:', bases[0])], + // not sure where this one originated + ['/a/b/c/./../../g', bases[0], 'http://a/a/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples2.html + // slashes in base URI's query args + ['g', bases[1], 'http://a/b/c/g'], + ['./g', bases[1], 'http://a/b/c/g'], + ['g/', bases[1], 'http://a/b/c/g/'], + ['/g', bases[1], 'http://a/g'], + ['//g', bases[1], 'http://g/'], + // changed in RFC 2396bis + //('?y', bases[1], 'http://a/b/c/?y'], + ['?y', bases[1], 'http://a/b/c/d;p?y'], + ['g?y', bases[1], 'http://a/b/c/g?y'], + ['g?y/./x' , bases[1], 'http://a/b/c/g?y/./x'], + ['g?y/../x', bases[1], 'http://a/b/c/g?y/../x'], + ['g#s', bases[1], 'http://a/b/c/g#s'], + ['g#s/./x' , bases[1], 'http://a/b/c/g#s/./x'], + ['g#s/../x', bases[1], 'http://a/b/c/g#s/../x'], + ['./', bases[1], 'http://a/b/c/'], + ['../', bases[1], 'http://a/b/'], + ['../g', bases[1], 'http://a/b/g'], + ['../../', bases[1], 'http://a/'], + ['../../g' , bases[1], 'http://a/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples3.html + // slashes in path params + // all of these changed in RFC 2396bis + ['g', bases[2], 'http://a/b/c/d;p=1/g'], + ['./g', bases[2], 'http://a/b/c/d;p=1/g'], + ['g/', bases[2], 'http://a/b/c/d;p=1/g/'], + ['g?y', bases[2], 'http://a/b/c/d;p=1/g?y'], + [';x', bases[2], 'http://a/b/c/d;p=1/;x'], + ['g;x', bases[2], 'http://a/b/c/d;p=1/g;x'], + ['g;x=1/./y', bases[2], 'http://a/b/c/d;p=1/g;x=1/y'], + ['g;x=1/../y', bases[2], 'http://a/b/c/d;p=1/y'], + ['./', bases[2], 'http://a/b/c/d;p=1/'], + ['../', bases[2], 'http://a/b/c/'], + ['../g', bases[2], 'http://a/b/c/g'], + ['../../', bases[2], 'http://a/b/'], + ['../../g' , bases[2], 'http://a/b/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples4.html + // double and triple slash, unknown scheme + ['g:h', bases[3], 'g:h'], + ['g', bases[3], 'fred:///s//a/b/g'], + ['./g', bases[3], 'fred:///s//a/b/g'], + ['g/', bases[3], 'fred:///s//a/b/g/'], + ['/g', bases[3], 'fred:///g'], // may change to fred:///s//a/g + ['//g', bases[3], 'fred://g'], // may change to fred:///s//g + ['//g/x', bases[3], 'fred://g/x'], // may change to fred:///s//g/x + ['///g', bases[3], 'fred:///g'], + ['./', bases[3], 'fred:///s//a/b/'], + ['../', bases[3], 'fred:///s//a/'], + ['../g', bases[3], 'fred:///s//a/g'], + + ['../../', bases[3], 'fred:///s//'], + ['../../g' , bases[3], 'fred:///s//g'], + ['../../../g', bases[3], 'fred:///s/g'], + // may change to fred:///s//a/../../../g + ['../../../../g', bases[3], 'fred:///g'], + + // http://gbiv.com/protocols/uri/test/rel_examples5.html + // double and triple slash, well-known scheme + ['g:h', bases[4], 'g:h'], + ['g', bases[4], 'http:///s//a/b/g'], + ['./g', bases[4], 'http:///s//a/b/g'], + ['g/', bases[4], 'http:///s//a/b/g/'], + ['/g', bases[4], 'http:///g'], // may change to http:///s//a/g + ['//g', bases[4], 'http://g/'], // may change to http:///s//g + ['//g/x', bases[4], 'http://g/x'], // may change to http:///s//g/x + ['///g', bases[4], 'http:///g'], + ['./', bases[4], 'http:///s//a/b/'], + ['../', bases[4], 'http:///s//a/'], + ['../g', bases[4], 'http:///s//a/g'], + ['../../', bases[4], 'http:///s//'], + ['../../g' , bases[4], 'http:///s//g'], + // may change to http:///s//a/../../g + ['../../../g', bases[4], 'http:///s/g'], + // may change to http:///s//a/../../../g + ['../../../../g', bases[4], 'http:///g'], + + // from Dan Connelly's tests in http://www.w3.org/2000/10/swap/uripath.py + ['bar:abc', 'foo:xyz', 'bar:abc'], + ['../abc', 'http://example/x/y/z', 'http://example/x/abc'], + ['http://example/x/abc', 'http://example2/x/y/z', 'http://example/x/abc'], + ['../r', 'http://ex/x/y/z', 'http://ex/x/r'], + ['q/r', 'http://ex/x/y', 'http://ex/x/q/r'], + ['q/r#s', 'http://ex/x/y', 'http://ex/x/q/r#s'], + ['q/r#s/t', 'http://ex/x/y', 'http://ex/x/q/r#s/t'], + ['ftp://ex/x/q/r', 'http://ex/x/y', 'ftp://ex/x/q/r'], + ['', 'http://ex/x/y', 'http://ex/x/y'], + ['', 'http://ex/x/y/', 'http://ex/x/y/'], + ['', 'http://ex/x/y/pdq', 'http://ex/x/y/pdq'], + ['z/', 'http://ex/x/y/', 'http://ex/x/y/z/'], + ['#Animal', + 'file:/swap/test/animal.rdf', + 'file:/swap/test/animal.rdf#Animal'], + ['../abc', 'file:/e/x/y/z', 'file:/e/x/abc'], + ['/example/x/abc', 'file:/example2/x/y/z', 'file:/example/x/abc'], + ['../r', 'file:/ex/x/y/z', 'file:/ex/x/r'], + ['/r', 'file:/ex/x/y/z', 'file:/r'], + ['q/r', 'file:/ex/x/y', 'file:/ex/x/q/r'], + ['q/r#s', 'file:/ex/x/y', 'file:/ex/x/q/r#s'], + ['q/r#', 'file:/ex/x/y', 'file:/ex/x/q/r#'], + ['q/r#s/t', 'file:/ex/x/y', 'file:/ex/x/q/r#s/t'], + ['ftp://ex/x/q/r', 'file:/ex/x/y', 'ftp://ex/x/q/r'], + ['', 'file:/ex/x/y', 'file:/ex/x/y'], + ['', 'file:/ex/x/y/', 'file:/ex/x/y/'], + ['', 'file:/ex/x/y/pdq', 'file:/ex/x/y/pdq'], + ['z/', 'file:/ex/x/y/', 'file:/ex/x/y/z/'], + ['file://meetings.example.com/cal#m1', + 'file:/devel/WWW/2000/10/swap/test/reluri-1.n3', + 'file://meetings.example.com/cal#m1'], + ['file://meetings.example.com/cal#m1', + 'file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', + 'file://meetings.example.com/cal#m1'], + ['./#blort', 'file:/some/dir/foo', 'file:/some/dir/#blort'], + ['./#', 'file:/some/dir/foo', 'file:/some/dir/#'], + // Ryan Lee + ['./', 'http://example/x/abc.efg', 'http://example/x/'], + + + // Graham Klyne's tests + // http://www.ninebynine.org/Software/HaskellUtils/Network/UriTest.xls + // 01-31 are from Connelly's cases + + // 32-49 + ['./q:r', 'http://ex/x/y', 'http://ex/x/q:r'], + ['./p=q:r', 'http://ex/x/y', 'http://ex/x/p=q:r'], + ['?pp/rr', 'http://ex/x/y?pp/qq', 'http://ex/x/y?pp/rr'], + ['y/z', 'http://ex/x/y?pp/qq', 'http://ex/x/y/z'], + ['local/qual@domain.org#frag', + 'mailto:local', + 'mailto:local/qual@domain.org#frag'], + ['more/qual2@domain2.org#frag', + 'mailto:local/qual1@domain1.org', + 'mailto:local/more/qual2@domain2.org#frag'], + ['y?q', 'http://ex/x/y?q', 'http://ex/x/y?q'], + ['/x/y?q', 'http://ex?p', 'http://ex/x/y?q'], + ['c/d', 'foo:a/b', 'foo:a/c/d'], + ['/c/d', 'foo:a/b', 'foo:/c/d'], + ['', 'foo:a/b?c#d', 'foo:a/b?c'], + ['b/c', 'foo:a', 'foo:b/c'], + ['../b/c', 'foo:/a/y/z', 'foo:/a/b/c'], + ['./b/c', 'foo:a', 'foo:b/c'], + ['/./b/c', 'foo:a', 'foo:/b/c'], + ['../../d', 'foo://a//b/c', 'foo://a/d'], + ['.', 'foo:a', 'foo:'], + ['..', 'foo:a', 'foo:'], + + // 50-57[cf. TimBL comments -- + // http://lists.w3.org/Archives/Public/uri/2003Feb/0028.html, + // http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html) + ['abc', 'http://example/x/y%2Fz', 'http://example/x/abc'], + ['../../x%2Fabc', 'http://example/a/x/y/z', 'http://example/a/x%2Fabc'], + ['../x%2Fabc', 'http://example/a/x/y%2Fz', 'http://example/a/x%2Fabc'], + ['abc', 'http://example/x%2Fy/z', 'http://example/x%2Fy/abc'], + ['q%3Ar', 'http://ex/x/y', 'http://ex/x/q%3Ar'], + ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], + ['/x%2Fabc', 'http://example/x/y/z', 'http://example/x%2Fabc'], + ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], + + // 70-77 + ['local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'], + ['local2@domain2?query2', + 'mailto:local1@domain1', + 'mailto:local2@domain2?query2'], + ['local2@domain2?query2', + 'mailto:local1@domain1?query1', + 'mailto:local2@domain2?query2'], + ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], + ['local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'], + ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], + ['http://example/a/b?c/../d', 'foo:bar', 'http://example/a/b?c/../d'], + ['http://example/a/b#c/../d', 'foo:bar', 'http://example/a/b#c/../d'], + + // 82-88 + // @isaacs Disagree. Not how browsers do it. + // ['http:this', 'http://example.org/base/uri', 'http:this'], + // @isaacs Added + ['http:this', 'http://example.org/base/uri', 'http://example.org/base/this'], + ['http:this', 'http:base', 'http:this'], + ['.//g', 'f:/a', 'f://g'], + ['b/c//d/e', 'f://example.org/base/a', 'f://example.org/base/b/c//d/e'], + ['m2@example.ord/c2@example.org', + 'mid:m@example.ord/c@example.org', + 'mid:m@example.ord/m2@example.ord/c2@example.org'], + ['mini1.xml', + 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/', + 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/mini1.xml'], + ['../b/c', 'foo:a/y/z', 'foo:a/b/c'], + + //changeing auth + ['http://diff:auth@www.example.com', + 'http://asdf:qwer@www.example.com', + 'http://diff:auth@www.example.com/'] +]; + +relativeTests2.forEach(function(relativeTest) { + test('resolve(' + [relativeTest[1], relativeTest[0]] + ')', function() { + var a = url.resolve(relativeTest[1], relativeTest[0]), + e = relativeTest[2]; + assert.equal(a, e, + 'resolve(' + [relativeTest[1], relativeTest[0]] + ') == ' + e + + '\n actual=' + a); + }); +}); + +//if format and parse are inverse operations then +//resolveObject(parse(x), y) == parse(resolve(x, y)) + +//host and hostname are special, in this case a '' value is important +var emptyIsImportant = {'host': true, 'hostname': ''}; + +//format: [from, path, expected] +relativeTests.forEach(function(relativeTest) { +test('resolveObject(' + [relativeTest[0], relativeTest[1]] + ')', function() { + var actual = url.resolveObject(url.parse(relativeTest[0]), relativeTest[1]), + expected = url.parse(relativeTest[2]); + + + assert.deepEqual(actual, expected); + + expected = relativeTest[2]; + actual = url.format(actual); + + assert.equal(actual, expected, + 'format(' + actual + ') == ' + expected + '\nactual:' + actual); + }); +}); + +//format: [to, from, result] +// the test: ['.//g', 'f:/a', 'f://g'] is a fundamental problem +// url.parse('f:/a') does not have a host +// url.resolve('f:/a', './/g') does not have a host because you have moved +// down to the g directory. i.e. f: //g, however when this url is parsed +// f:// will indicate that the host is g which is not the case. +// it is unclear to me how to keep this information from being lost +// it may be that a pathname of ////g should collapse to /g but this seems +// to be a lot of work for an edge case. Right now I remove the test +if (relativeTests2[181][0] === './/g' && + relativeTests2[181][1] === 'f:/a' && + relativeTests2[181][2] === 'f://g') { + relativeTests2.splice(181, 1); +} + +relativeTests2.forEach(function(relativeTest) { + test('resolveObject(' + [relativeTest[1], relativeTest[0]] + ')', function() { + var actual = url.resolveObject(url.parse(relativeTest[1]), relativeTest[0]), + expected = url.parse(relativeTest[2]); + + assert.deepEqual(actual, expected); + + var expected = relativeTest[2], + actual = url.format(actual); + + assert.equal(actual, expected, + 'format(' + relativeTest[1] + ') == ' + expected + + '\nactual:' + actual); + }); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/url/url.js b/node_modules/meteor-node-stubs/node_modules/url/url.js new file mode 100644 index 0000000..23ac6f5 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/url.js @@ -0,0 +1,732 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/url/util.js b/node_modules/meteor-node-stubs/node_modules/url/util.js new file mode 100644 index 0000000..97dcf31 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/url/util.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; diff --git a/node_modules/meteor-node-stubs/node_modules/util/.npmignore b/node_modules/meteor-node-stubs/node_modules/util/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/meteor-node-stubs/node_modules/util/.travis.yml b/node_modules/meteor-node-stubs/node_modules/util/.travis.yml new file mode 100644 index 0000000..ded625c --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: +- '0.8' +- '0.10' +env: + global: + - secure: AdUubswCR68/eGD+WWjwTHgFbelwQGnNo81j1IOaUxKw+zgFPzSnFEEtDw7z98pWgg7p9DpCnyzzSnSllP40wq6AG19OwyUJjSLoZK57fp+r8zwTQwWiSqUgMu2YSMmKJPIO/aoSGpRQXT+L1nRrHoUJXgFodyIZgz40qzJeZjc= + - secure: heQuxPVsQ7jBbssoVKimXDpqGjQFiucm6W5spoujmspjDG7oEcHD9ANo9++LoRPrsAmNx56SpMK5fNfVmYediw6SvhXm4Mxt56/fYCrLDBtgGG+1neCeffAi8z1rO8x48m77hcQ6YhbUL5R9uBimUjMX92fZcygAt8Rg804zjFo= diff --git a/node_modules/meteor-node-stubs/node_modules/util/.zuul.yml b/node_modules/meteor-node-stubs/node_modules/util/.zuul.yml new file mode 100644 index 0000000..2105010 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/.zuul.yml @@ -0,0 +1,10 @@ +ui: mocha-qunit +browsers: + - name: chrome + version: 27..latest + - name: firefox + version: latest + - name: safari + version: latest + - name: ie + version: 9..latest diff --git a/node_modules/meteor-node-stubs/node_modules/util/LICENSE b/node_modules/meteor-node-stubs/node_modules/util/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/util/README.md b/node_modules/meteor-node-stubs/node_modules/util/README.md new file mode 100644 index 0000000..1c473d2 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/README.md @@ -0,0 +1,15 @@ +# util + +[![Build Status](https://travis-ci.org/defunctzombie/node-util.png?branch=master)](https://travis-ci.org/defunctzombie/node-util) + +node.js [util](http://nodejs.org/api/util.html) module as a module + +## install via [npm](npmjs.org) + +```shell +npm install util +``` + +## browser support + +This module also works in modern browsers. If you need legacy browser support you will need to polyfill ES5 features. diff --git a/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/LICENSE b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/README.md b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/inherits.js b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/inherits_browser.js b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/package.json b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/package.json new file mode 100644 index 0000000..bad1183 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/test.js b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/meteor-node-stubs/node_modules/util/package.json b/node_modules/meteor-node-stubs/node_modules/util/package.json new file mode 100644 index 0000000..bc1d424 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/package.json @@ -0,0 +1,40 @@ +{ + "author": { + "name": "Joyent", + "url": "http://www.joyent.com" + }, + "name": "util", + "description": "Node.JS util module", + "keywords": [ + "util" + ], + "version": "0.10.3", + "homepage": "https://github.com/defunctzombie/node-util", + "repository": { + "type": "git", + "url": "git://github.com/defunctzombie/node-util.git" + }, + "main": "./util.js", + "scripts": { + "test": "node test/node/*.js && zuul test/browser/*.js" + }, + "dependencies": { + "inherits": "2.0.1" + }, + "license": "MIT", + "devDependencies": { + "zuul": "~1.0.9" + }, + "browser": { + "./support/isBuffer.js": "./support/isBufferBrowser.js" + }, + "readme": "# util\n\n[![Build Status](https://travis-ci.org/defunctzombie/node-util.png?branch=master)](https://travis-ci.org/defunctzombie/node-util)\n\nnode.js [util](http://nodejs.org/api/util.html) module as a module\n\n## install via [npm](npmjs.org)\n\n```shell\nnpm install util\n```\n\n## browser support\n\nThis module also works in modern browsers. If you need legacy browser support you will need to polyfill ES5 features.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/defunctzombie/node-util/issues" + }, + "_id": "util@0.10.3", + "_shasum": "7afb1afe50805246489e3db7fe0ed379336ac0f9", + "_resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", + "_from": "https://registry.npmjs.org/util/-/util-0.10.3.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/util/support/isBuffer.js b/node_modules/meteor-node-stubs/node_modules/util/support/isBuffer.js new file mode 100644 index 0000000..ace9ac0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/support/isBuffer.js @@ -0,0 +1,3 @@ +module.exports = function isBuffer(arg) { + return arg instanceof Buffer; +} diff --git a/node_modules/meteor-node-stubs/node_modules/util/support/isBufferBrowser.js b/node_modules/meteor-node-stubs/node_modules/util/support/isBufferBrowser.js new file mode 100644 index 0000000..0e1bee1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/support/isBufferBrowser.js @@ -0,0 +1,6 @@ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/util/test/browser/inspect.js b/node_modules/meteor-node-stubs/node_modules/util/test/browser/inspect.js new file mode 100644 index 0000000..91af3b0 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/test/browser/inspect.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var util = require('../../'); + +suite('inspect'); + +test('util.inspect - test for sparse array', function () { + var a = ['foo', 'bar', 'baz']; + assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); + delete a[1]; + assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); + assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); + assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); +}); + +test('util.inspect - exceptions should print the error message, not \'{}\'', function () { + assert.equal(util.inspect(new Error()), '[Error]'); + assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); + assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); + assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/util/test/browser/is.js b/node_modules/meteor-node-stubs/node_modules/util/test/browser/is.js new file mode 100644 index 0000000..f63bff9 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/test/browser/is.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); + +var util = require('../../'); + +suite('is'); + +test('util.isArray', function () { + assert.equal(true, util.isArray([])); + assert.equal(true, util.isArray(Array())); + assert.equal(true, util.isArray(new Array())); + assert.equal(true, util.isArray(new Array(5))); + assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); + assert.equal(false, util.isArray({})); + assert.equal(false, util.isArray({ push: function() {} })); + assert.equal(false, util.isArray(/regexp/)); + assert.equal(false, util.isArray(new Error())); + assert.equal(false, util.isArray(Object.create(Array.prototype))); +}); + +test('util.isRegExp', function () { + assert.equal(true, util.isRegExp(/regexp/)); + assert.equal(true, util.isRegExp(RegExp())); + assert.equal(true, util.isRegExp(new RegExp())); + assert.equal(false, util.isRegExp({})); + assert.equal(false, util.isRegExp([])); + assert.equal(false, util.isRegExp(new Date())); + assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); +}); + +test('util.isDate', function () { + assert.equal(true, util.isDate(new Date())); + assert.equal(true, util.isDate(new Date(0))); + assert.equal(false, util.isDate(Date())); + assert.equal(false, util.isDate({})); + assert.equal(false, util.isDate([])); + assert.equal(false, util.isDate(new Error())); + assert.equal(false, util.isDate(Object.create(Date.prototype))); +}); + +test('util.isError', function () { + assert.equal(true, util.isError(new Error())); + assert.equal(true, util.isError(new TypeError())); + assert.equal(true, util.isError(new SyntaxError())); + assert.equal(false, util.isError({})); + assert.equal(false, util.isError({ name: 'Error', message: '' })); + assert.equal(false, util.isError([])); + assert.equal(true, util.isError(Object.create(Error.prototype))); +}); + +test('util._extend', function () { + assert.deepEqual(util._extend({a:1}), {a:1}); + assert.deepEqual(util._extend({a:1}, []), {a:1}); + assert.deepEqual(util._extend({a:1}, null), {a:1}); + assert.deepEqual(util._extend({a:1}, true), {a:1}); + assert.deepEqual(util._extend({a:1}, false), {a:1}); + assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); + assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); +}); + +test('util.isBuffer', function () { + assert.equal(true, util.isBuffer(new Buffer(4))); + assert.equal(true, util.isBuffer(Buffer(4))); + assert.equal(true, util.isBuffer(new Buffer(4))); + assert.equal(true, util.isBuffer(new Buffer([1, 2, 3, 4]))); + assert.equal(false, util.isBuffer({})); + assert.equal(false, util.isBuffer([])); + assert.equal(false, util.isBuffer(new Error())); + assert.equal(false, util.isRegExp(new Date())); + assert.equal(true, util.isBuffer(Object.create(Buffer.prototype))); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/util/test/node/debug.js b/node_modules/meteor-node-stubs/node_modules/util/test/node/debug.js new file mode 100644 index 0000000..ef5f69f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/test/node/debug.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var util = require('../../'); + +if (process.argv[2] === 'child') + child(); +else + parent(); + +function parent() { + test('foo,tud,bar', true); + test('foo,tud', true); + test('tud,bar', true); + test('tud', true); + test('foo,bar', false); + test('', false); +} + +function test(environ, shouldWrite) { + var expectErr = ''; + if (shouldWrite) { + expectErr = 'TUD %PID%: this { is: \'a\' } /debugging/\n' + + 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n'; + } + var expectOut = 'ok\n'; + var didTest = false; + + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child'], { + env: { NODE_DEBUG: environ } + }); + + expectErr = expectErr.split('%PID%').join(child.pid); + + var err = ''; + child.stderr.setEncoding('utf8'); + child.stderr.on('data', function(c) { + err += c; + }); + + var out = ''; + child.stdout.setEncoding('utf8'); + child.stdout.on('data', function(c) { + out += c; + }); + + child.on('close', function(c) { + assert(!c); + assert.equal(err, expectErr); + assert.equal(out, expectOut); + didTest = true; + console.log('ok %j %j', environ, shouldWrite); + }); + + process.on('exit', function() { + assert(didTest); + }); +} + + +function child() { + var debug = util.debuglog('tud'); + debug('this', { is: 'a' }, /debugging/); + debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' }); + console.log('ok'); +} diff --git a/node_modules/meteor-node-stubs/node_modules/util/test/node/format.js b/node_modules/meteor-node-stubs/node_modules/util/test/node/format.js new file mode 100644 index 0000000..f2d1862 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/test/node/format.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var assert = require('assert'); +var util = require('../../'); + +assert.equal(util.format(), ''); +assert.equal(util.format(''), ''); +assert.equal(util.format([]), '[]'); +assert.equal(util.format({}), '{}'); +assert.equal(util.format(null), 'null'); +assert.equal(util.format(true), 'true'); +assert.equal(util.format(false), 'false'); +assert.equal(util.format('test'), 'test'); + +// CHECKME this is for console.log() compatibility - but is it *right*? +assert.equal(util.format('foo', 'bar', 'baz'), 'foo bar baz'); + +assert.equal(util.format('%d', 42.0), '42'); +assert.equal(util.format('%d', 42), '42'); +assert.equal(util.format('%s', 42), '42'); +assert.equal(util.format('%j', 42), '42'); + +assert.equal(util.format('%d', '42.0'), '42'); +assert.equal(util.format('%d', '42'), '42'); +assert.equal(util.format('%s', '42'), '42'); +assert.equal(util.format('%j', '42'), '"42"'); + +assert.equal(util.format('%%s%s', 'foo'), '%sfoo'); + +assert.equal(util.format('%s'), '%s'); +assert.equal(util.format('%s', undefined), 'undefined'); +assert.equal(util.format('%s', 'foo'), 'foo'); +assert.equal(util.format('%s:%s'), '%s:%s'); +assert.equal(util.format('%s:%s', undefined), 'undefined:%s'); +assert.equal(util.format('%s:%s', 'foo'), 'foo:%s'); +assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar'); +assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); +assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); +assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); + +(function() { + var o = {}; + o.o = o; + assert.equal(util.format('%j', o), '[Circular]'); +})(); + +// Errors +assert.equal(util.format(new Error('foo')), '[Error: foo]'); +function CustomError(msg) { + Error.call(this); + Object.defineProperty(this, 'message', { value: msg, enumerable: false }); + Object.defineProperty(this, 'name', { value: 'CustomError', enumerable: false }); +} +util.inherits(CustomError, Error); +assert.equal(util.format(new CustomError('bar')), '[CustomError: bar]'); diff --git a/node_modules/meteor-node-stubs/node_modules/util/test/node/inspect.js b/node_modules/meteor-node-stubs/node_modules/util/test/node/inspect.js new file mode 100644 index 0000000..f766d11 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/test/node/inspect.js @@ -0,0 +1,195 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var assert = require('assert'); +var util = require('../../'); + +// test the internal isDate implementation +var Date2 = require('vm').runInNewContext('Date'); +var d = new Date2(); +var orig = util.inspect(d); +Date2.prototype.foo = 'bar'; +var after = util.inspect(d); +assert.equal(orig, after); + +// test for sparse array +var a = ['foo', 'bar', 'baz']; +assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); +delete a[1]; +assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); +assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); +assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); + +// test for property descriptors +var getter = Object.create(null, { + a: { + get: function() { return 'aaa'; } + } +}); +var setter = Object.create(null, { + b: { + set: function() {} + } +}); +var getterAndSetter = Object.create(null, { + c: { + get: function() { return 'ccc'; }, + set: function() {} + } +}); +assert.equal(util.inspect(getter, true), '{ [a]: [Getter] }'); +assert.equal(util.inspect(setter, true), '{ [b]: [Setter] }'); +assert.equal(util.inspect(getterAndSetter, true), '{ [c]: [Getter/Setter] }'); + +// exceptions should print the error message, not '{}' +assert.equal(util.inspect(new Error()), '[Error]'); +assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); +assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); +assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); +try { + undef(); +} catch (e) { + assert.equal(util.inspect(e), '[ReferenceError: undef is not defined]'); +} +var ex = util.inspect(new Error('FAIL'), true); +assert.ok(ex.indexOf('[Error: FAIL]') != -1); +assert.ok(ex.indexOf('[stack]') != -1); +assert.ok(ex.indexOf('[message]') != -1); + +// GH-1941 +// should not throw: +assert.equal(util.inspect(Object.create(Date.prototype)), '{}'); + +// GH-1944 +assert.doesNotThrow(function() { + var d = new Date(); + d.toUTCString = null; + util.inspect(d); +}); + +assert.doesNotThrow(function() { + var r = /regexp/; + r.toString = null; + util.inspect(r); +}); + +// bug with user-supplied inspect function returns non-string +assert.doesNotThrow(function() { + util.inspect([{ + inspect: function() { return 123; } + }]); +}); + +// GH-2225 +var x = { inspect: util.inspect }; +assert.ok(util.inspect(x).indexOf('inspect') != -1); + +// util.inspect.styles and util.inspect.colors +function test_color_style(style, input, implicit) { + var color_name = util.inspect.styles[style]; + var color = ['', '']; + if(util.inspect.colors[color_name]) + color = util.inspect.colors[color_name]; + + var without_color = util.inspect(input, false, 0, false); + var with_color = util.inspect(input, false, 0, true); + var expect = '\u001b[' + color[0] + 'm' + without_color + + '\u001b[' + color[1] + 'm'; + assert.equal(with_color, expect, 'util.inspect color for style '+style); +} + +test_color_style('special', function(){}); +test_color_style('number', 123.456); +test_color_style('boolean', true); +test_color_style('undefined', undefined); +test_color_style('null', null); +test_color_style('string', 'test string'); +test_color_style('date', new Date); +test_color_style('regexp', /regexp/); + +// an object with "hasOwnProperty" overwritten should not throw +assert.doesNotThrow(function() { + util.inspect({ + hasOwnProperty: null + }); +}); + +// new API, accepts an "options" object +var subject = { foo: 'bar', hello: 31, a: { b: { c: { d: 0 } } } }; +Object.defineProperty(subject, 'hidden', { enumerable: false, value: null }); + +assert(util.inspect(subject, { showHidden: false }).indexOf('hidden') === -1); +assert(util.inspect(subject, { showHidden: true }).indexOf('hidden') !== -1); +assert(util.inspect(subject, { colors: false }).indexOf('\u001b[32m') === -1); +assert(util.inspect(subject, { colors: true }).indexOf('\u001b[32m') !== -1); +assert(util.inspect(subject, { depth: 2 }).indexOf('c: [Object]') !== -1); +assert(util.inspect(subject, { depth: 0 }).indexOf('a: [Object]') !== -1); +assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1); + +// "customInspect" option can enable/disable calling inspect() on objects +subject = { inspect: function() { return 123; } }; + +assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1); +assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1); +assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1); +assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1); + +// custom inspect() functions should be able to return other Objects +subject.inspect = function() { return { foo: 'bar' }; }; + +assert.equal(util.inspect(subject), '{ foo: \'bar\' }'); + +subject.inspect = function(depth, opts) { + assert.strictEqual(opts.customInspectOptions, true); +}; + +util.inspect(subject, { customInspectOptions: true }); + +// util.inspect with "colors" option should produce as many lines as without it +function test_lines(input) { + var count_lines = function(str) { + return (str.match(/\n/g) || []).length; + } + + var without_color = util.inspect(input); + var with_color = util.inspect(input, {colors: true}); + assert.equal(count_lines(without_color), count_lines(with_color)); +} + +test_lines([1, 2, 3, 4, 5, 6, 7]); +test_lines(function() { + var big_array = []; + for (var i = 0; i < 100; i++) { + big_array.push(i); + } + return big_array; +}()); +test_lines({foo: 'bar', baz: 35, b: {a: 35}}); +test_lines({ + foo: 'bar', + baz: 35, + b: {a: 35}, + very_long_key: 'very_long_value', + even_longer_key: ['with even longer value in array'] +}); diff --git a/node_modules/meteor-node-stubs/node_modules/util/test/node/log.js b/node_modules/meteor-node-stubs/node_modules/util/test/node/log.js new file mode 100644 index 0000000..6bd96d1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/test/node/log.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var assert = require('assert'); +var util = require('../../'); + +assert.ok(process.stdout.writable); +assert.ok(process.stderr.writable); + +var stdout_write = global.process.stdout.write; +var strings = []; +global.process.stdout.write = function(string) { + strings.push(string); +}; +console._stderr = process.stdout; + +var tests = [ + {input: 'foo', output: 'foo'}, + {input: undefined, output: 'undefined'}, + {input: null, output: 'null'}, + {input: false, output: 'false'}, + {input: 42, output: '42'}, + {input: function(){}, output: '[Function]'}, + {input: parseInt('not a number', 10), output: 'NaN'}, + {input: {answer: 42}, output: '{ answer: 42 }'}, + {input: [1,2,3], output: '[ 1, 2, 3 ]'} +]; + +// test util.log() +tests.forEach(function(test) { + util.log(test.input); + var result = strings.shift().trim(), + re = (/[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/), + match = re.exec(result); + assert.ok(match); + assert.equal(match[1], test.output); +}); + +global.process.stdout.write = stdout_write; diff --git a/node_modules/meteor-node-stubs/node_modules/util/test/node/util.js b/node_modules/meteor-node-stubs/node_modules/util/test/node/util.js new file mode 100644 index 0000000..633ba69 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/test/node/util.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var assert = require('assert'); +var context = require('vm').runInNewContext; + +var util = require('../../'); + +// isArray +assert.equal(true, util.isArray([])); +assert.equal(true, util.isArray(Array())); +assert.equal(true, util.isArray(new Array())); +assert.equal(true, util.isArray(new Array(5))); +assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); +assert.equal(true, util.isArray(context('Array')())); +assert.equal(false, util.isArray({})); +assert.equal(false, util.isArray({ push: function() {} })); +assert.equal(false, util.isArray(/regexp/)); +assert.equal(false, util.isArray(new Error)); +assert.equal(false, util.isArray(Object.create(Array.prototype))); + +// isRegExp +assert.equal(true, util.isRegExp(/regexp/)); +assert.equal(true, util.isRegExp(RegExp())); +assert.equal(true, util.isRegExp(new RegExp())); +assert.equal(true, util.isRegExp(context('RegExp')())); +assert.equal(false, util.isRegExp({})); +assert.equal(false, util.isRegExp([])); +assert.equal(false, util.isRegExp(new Date())); +assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); + +// isDate +assert.equal(true, util.isDate(new Date())); +assert.equal(true, util.isDate(new Date(0))); +assert.equal(true, util.isDate(new (context('Date')))); +assert.equal(false, util.isDate(Date())); +assert.equal(false, util.isDate({})); +assert.equal(false, util.isDate([])); +assert.equal(false, util.isDate(new Error)); +assert.equal(false, util.isDate(Object.create(Date.prototype))); + +// isError +assert.equal(true, util.isError(new Error)); +assert.equal(true, util.isError(new TypeError)); +assert.equal(true, util.isError(new SyntaxError)); +assert.equal(true, util.isError(new (context('Error')))); +assert.equal(true, util.isError(new (context('TypeError')))); +assert.equal(true, util.isError(new (context('SyntaxError')))); +assert.equal(false, util.isError({})); +assert.equal(false, util.isError({ name: 'Error', message: '' })); +assert.equal(false, util.isError([])); +assert.equal(true, util.isError(Object.create(Error.prototype))); + +// isObject +assert.ok(util.isObject({}) === true); + +// _extend +assert.deepEqual(util._extend({a:1}), {a:1}); +assert.deepEqual(util._extend({a:1}, []), {a:1}); +assert.deepEqual(util._extend({a:1}, null), {a:1}); +assert.deepEqual(util._extend({a:1}, true), {a:1}); +assert.deepEqual(util._extend({a:1}, false), {a:1}); +assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); +assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); diff --git a/node_modules/meteor-node-stubs/node_modules/util/util.js b/node_modules/meteor-node-stubs/node_modules/util/util.js new file mode 100644 index 0000000..e0ea321 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/util/util.js @@ -0,0 +1,586 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/LICENSE b/node_modules/meteor-node-stubs/node_modules/vm-browserify/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/bundle.js b/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/bundle.js new file mode 100644 index 0000000..5dbc43f --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/bundle.js @@ -0,0 +1,473 @@ +var require = function (file, cwd) { + var resolved = require.resolve(file, cwd || '/'); + var mod = require.modules[resolved]; + if (!mod) throw new Error( + 'Failed to resolve module ' + file + ', tried ' + resolved + ); + var res = mod._cached ? mod._cached : mod(); + return res; +} + +require.paths = []; +require.modules = {}; +require.extensions = [".js",".coffee"]; + +require._core = { + 'assert': true, + 'events': true, + 'fs': true, + 'path': true, + 'vm': true +}; + +require.resolve = (function () { + return function (x, cwd) { + if (!cwd) cwd = '/'; + + if (require._core[x]) return x; + var path = require.modules.path(); + var y = cwd || '.'; + + if (x.match(/^(?:\.\.?\/|\/)/)) { + var m = loadAsFileSync(path.resolve(y, x)) + || loadAsDirectorySync(path.resolve(y, x)); + if (m) return m; + } + + var n = loadNodeModulesSync(x, y); + if (n) return n; + + throw new Error("Cannot find module '" + x + "'"); + + function loadAsFileSync (x) { + if (require.modules[x]) { + return x; + } + + for (var i = 0; i < require.extensions.length; i++) { + var ext = require.extensions[i]; + if (require.modules[x + ext]) return x + ext; + } + } + + function loadAsDirectorySync (x) { + x = x.replace(/\/+$/, ''); + var pkgfile = x + '/package.json'; + if (require.modules[pkgfile]) { + var pkg = require.modules[pkgfile](); + var b = pkg.browserify; + if (typeof b === 'object' && b.main) { + var m = loadAsFileSync(path.resolve(x, b.main)); + if (m) return m; + } + else if (typeof b === 'string') { + var m = loadAsFileSync(path.resolve(x, b)); + if (m) return m; + } + else if (pkg.main) { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + } + } + + return loadAsFileSync(x + '/index'); + } + + function loadNodeModulesSync (x, start) { + var dirs = nodeModulesPathsSync(start); + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + var m = loadAsFileSync(dir + '/' + x); + if (m) return m; + var n = loadAsDirectorySync(dir + '/' + x); + if (n) return n; + } + + var m = loadAsFileSync(x); + if (m) return m; + } + + function nodeModulesPathsSync (start) { + var parts; + if (start === '/') parts = [ '' ]; + else parts = path.normalize(start).split('/'); + + var dirs = []; + for (var i = parts.length - 1; i >= 0; i--) { + if (parts[i] === 'node_modules') continue; + var dir = parts.slice(0, i + 1).join('/') + '/node_modules'; + dirs.push(dir); + } + + return dirs; + } + }; +})(); + +require.alias = function (from, to) { + var path = require.modules.path(); + var res = null; + try { + res = require.resolve(from + '/package.json', '/'); + } + catch (err) { + res = require.resolve(from, '/'); + } + var basedir = path.dirname(res); + + var keys = (Object.keys || function (obj) { + var res = []; + for (var key in obj) res.push(key) + return res; + })(require.modules); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key.slice(0, basedir.length + 1) === basedir + '/') { + var f = key.slice(basedir.length); + require.modules[to + f] = require.modules[basedir + f]; + } + else if (key === basedir) { + require.modules[to] = require.modules[basedir]; + } + } +}; + +require.define = function (filename, fn) { + var dirname = require._core[filename] + ? '' + : require.modules.path().dirname(filename) + ; + + var require_ = function (file) { + return require(file, dirname) + }; + require_.resolve = function (name) { + return require.resolve(name, dirname); + }; + require_.modules = require.modules; + require_.define = require.define; + var module_ = { exports : {} }; + + require.modules[filename] = function () { + require.modules[filename]._cached = module_.exports; + fn.call( + module_.exports, + require_, + module_, + module_.exports, + dirname, + filename + ); + require.modules[filename]._cached = module_.exports; + return module_.exports; + }; +}; + +if (typeof process === 'undefined') process = {}; + +if (!process.nextTick) process.nextTick = (function () { + var queue = []; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; + + if (canPost) { + window.addEventListener('message', function (ev) { + if (ev.source === window && ev.data === 'browserify-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); + } + + return function (fn) { + if (canPost) { + queue.push(fn); + window.postMessage('browserify-tick', '*'); + } + else setTimeout(fn, 0); + }; +})(); + +if (!process.title) process.title = 'browser'; + +if (!process.binding) process.binding = function (name) { + if (name === 'evals') return require('vm') + else throw new Error('No such module') +}; + +if (!process.cwd) process.cwd = function () { return '.' }; + +require.define("path", function (require, module, exports, __dirname, __filename) { +function filter (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + if (fn(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length; i >= 0; i--) { + var last = parts[i]; + if (last == '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Regex to split a filename into [*, dir, basename, ext] +// posix version +var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { +var resolvedPath = '', + resolvedAbsolute = false; + +for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) + ? arguments[i] + : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string' || !path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; +} + +// At this point the path should be resolved to a full absolute path, but +// handle relative paths to be safe (might happen when process.cwd() fails) + +// Normalize the path +resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { +var isAbsolute = path.charAt(0) === '/', + trailingSlash = path.slice(-1) === '/'; + +// Normalize the path +path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + return p && typeof p === 'string'; + }).join('/')); +}; + + +exports.dirname = function(path) { + var dir = splitPathRe.exec(path)[1] || ''; + var isWindows = false; + if (!dir) { + // No dirname + return '.'; + } else if (dir.length === 1 || + (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) { + // It is just a slash or a drive letter with a slash + return dir; + } else { + // It is a full dirname, strip trailing slash + return dir.substring(0, dir.length - 1); + } +}; + + +exports.basename = function(path, ext) { + var f = splitPathRe.exec(path)[2] || ''; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPathRe.exec(path)[3] || ''; +}; + +}); + +require.define("vm", function (require, module, exports, __dirname, __filename) { +var Object_keys = function (obj) { + if (Object.keys) return Object.keys(obj) + else { + var res = []; + for (var key in obj) res.push(key) + return res; + } +}; + +var forEach = function (xs, fn) { + if (xs.forEach) return xs.forEach(fn) + else for (var i = 0; i < xs.length; i++) { + fn(xs[i], i, xs); + } +}; + +var Script = exports.Script = function NodeScript (code) { + if (!(this instanceof Script)) return new Script(code); + this.code = code; +}; + +var iframe = document.createElement('iframe'); +if (!iframe.style) iframe.style = {}; +iframe.style.display = 'none'; + +var iframeCapable = true; // until proven otherwise +if (navigator.appName === 'Microsoft Internet Explorer') { + var m = navigator.appVersion.match(/\bMSIE (\d+\.\d+);/); + if (m && parseFloat(m[1]) <= 9.0) { + iframeCapable = false; + } +} + +Script.prototype.runInNewContext = function (context) { + if (!context) context = {}; + + if (!iframeCapable) { + var keys = Object_keys(context); + var args = []; + for (var i = 0; i < keys.length; i++) { + args.push(context[keys[i]]); + } + + var fn = new Function(keys, 'return ' + this.code); + return fn.apply(null, args); + } + + document.body.appendChild(iframe); + + var win = iframe.contentWindow + || (window.frames && window.frames[window.frames.length - 1]) + || window[window.length - 1] + ; + + forEach(Object_keys(context), function (key) { + win[key] = context[key]; + iframe[key] = context[key]; + }); + + if (win.eval) { + // chrome and ff can just .eval() + var res = win.eval(this.code); + } + else { + // this works in IE9 but not anything newer + iframe.setAttribute('src', + 'javascript:__browserifyVmResult=(' + this.code + ')' + ); + if ('__browserifyVmResult' in win) { + var res = win.__browserifyVmResult; + } + else { + iframeCapable = false; + res = this.runInThisContext(context); + } + } + + forEach(Object_keys(win), function (key) { + context[key] = win[key]; + }); + + document.body.removeChild(iframe); + + return res; +}; + +Script.prototype.runInThisContext = function () { + return eval(this.code); // maybe... +}; + +Script.prototype.runInContext = function (context) { + // seems to be just runInNewContext on magical context objects which are + // otherwise indistinguishable from objects except plain old objects + // for the parameter segfaults node + return this.runInNewContext(context); +}; + +forEach(Object_keys(Script.prototype), function (name) { + exports[name] = Script[name] = function (code) { + var s = Script(code); + return s[name].apply(s, [].slice.call(arguments, 1)); + }; +}); + +exports.createScript = function (code) { + return exports.Script(code); +}; + +exports.createContext = Script.createContext = function (context) { + // not really sure what this one does + // seems to just make a shallow copy + var copy = {}; + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; + }); + return copy; +}; + +}); + +require.define("/entry.js", function (require, module, exports, __dirname, __filename) { + var vm = require('vm'); + +$(function () { + var res = vm.runInNewContext('a + 5', { a : 100 }); + $('#res').text(res); +}); + +}); +require("/entry.js"); diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/entry.js b/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/entry.js new file mode 100644 index 0000000..c7d3891 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/entry.js @@ -0,0 +1,6 @@ +var vm = require('vm'); + +$(function () { + var res = vm.runInNewContext('a + 5', { a : 100 }); + $('#res').text(res); +}); diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/index.html b/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/index.html new file mode 100644 index 0000000..1ea0942 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/index.html @@ -0,0 +1,9 @@ + + + + + + + result = + + diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/server.js b/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/server.js new file mode 100644 index 0000000..339d3ee --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/example/run/server.js @@ -0,0 +1,6 @@ +var ecstatic = require('ecstatic')(__dirname); +var http = require('http'); +http.createServer(ecstatic).listen(8000); + +console.log('listening on :8000'); +console.log('# remember to run browserify entry.js -o bundle.js'); diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/index.js b/node_modules/meteor-node-stubs/node_modules/vm-browserify/index.js new file mode 100644 index 0000000..644efd1 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/index.js @@ -0,0 +1,138 @@ +var indexOf = require('indexof'); + +var Object_keys = function (obj) { + if (Object.keys) return Object.keys(obj) + else { + var res = []; + for (var key in obj) res.push(key) + return res; + } +}; + +var forEach = function (xs, fn) { + if (xs.forEach) return xs.forEach(fn) + else for (var i = 0; i < xs.length; i++) { + fn(xs[i], i, xs); + } +}; + +var defineProp = (function() { + try { + Object.defineProperty({}, '_', {}); + return function(obj, name, value) { + Object.defineProperty(obj, name, { + writable: true, + enumerable: false, + configurable: true, + value: value + }) + }; + } catch(e) { + return function(obj, name, value) { + obj[name] = value; + }; + } +}()); + +var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', +'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', +'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', +'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', +'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; + +function Context() {} +Context.prototype = {}; + +var Script = exports.Script = function NodeScript (code) { + if (!(this instanceof Script)) return new Script(code); + this.code = code; +}; + +Script.prototype.runInContext = function (context) { + if (!(context instanceof Context)) { + throw new TypeError("needs a 'context' argument."); + } + + var iframe = document.createElement('iframe'); + if (!iframe.style) iframe.style = {}; + iframe.style.display = 'none'; + + document.body.appendChild(iframe); + + var win = iframe.contentWindow; + var wEval = win.eval, wExecScript = win.execScript; + + if (!wEval && wExecScript) { + // win.eval() magically appears when this is called in IE: + wExecScript.call(win, 'null'); + wEval = win.eval; + } + + forEach(Object_keys(context), function (key) { + win[key] = context[key]; + }); + forEach(globals, function (key) { + if (context[key]) { + win[key] = context[key]; + } + }); + + var winKeys = Object_keys(win); + + var res = wEval.call(win, this.code); + + forEach(Object_keys(win), function (key) { + // Avoid copying circular objects like `top` and `window` by only + // updating existing context properties or new properties in the `win` + // that was only introduced after the eval. + if (key in context || indexOf(winKeys, key) === -1) { + context[key] = win[key]; + } + }); + + forEach(globals, function (key) { + if (!(key in context)) { + defineProp(context, key, win[key]); + } + }); + + document.body.removeChild(iframe); + + return res; +}; + +Script.prototype.runInThisContext = function () { + return eval(this.code); // maybe... +}; + +Script.prototype.runInNewContext = function (context) { + var ctx = Script.createContext(context); + var res = this.runInContext(ctx); + + forEach(Object_keys(ctx), function (key) { + context[key] = ctx[key]; + }); + + return res; +}; + +forEach(Object_keys(Script.prototype), function (name) { + exports[name] = Script[name] = function (code) { + var s = Script(code); + return s[name].apply(s, [].slice.call(arguments, 1)); + }; +}); + +exports.createScript = function (code) { + return exports.Script(code); +}; + +exports.createContext = Script.createContext = function (context) { + var copy = new Context(); + if(typeof context === 'object') { + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; + }); + } + return copy; +}; diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/.npmignore b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/.npmignore new file mode 100644 index 0000000..48a2e24 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/.npmignore @@ -0,0 +1,2 @@ +components +build diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/Makefile b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/Makefile new file mode 100644 index 0000000..3f6119d --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/Makefile @@ -0,0 +1,11 @@ + +build: components index.js + @component build + +components: + @Component install + +clean: + rm -fr build components template.js + +.PHONY: clean diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/Readme.md b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/Readme.md new file mode 100644 index 0000000..99c8dfc --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/Readme.md @@ -0,0 +1,15 @@ + +# indexOf + + Lame indexOf thing, thanks microsoft + +## Example + +```js +var index = require('indexof'); +index(arr, obj); +``` + +## License + + MIT \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/component.json b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/component.json new file mode 100644 index 0000000..e3430d7 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/component.json @@ -0,0 +1,10 @@ +{ + "name": "indexof", + "description": "Microsoft sucks", + "version": "0.0.1", + "keywords": ["index", "array", "indexOf"], + "dependencies": {}, + "scripts": [ + "index.js" + ] +} \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/index.js b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/index.js new file mode 100644 index 0000000..9d9667b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/index.js @@ -0,0 +1,10 @@ + +var indexOf = [].indexOf; + +module.exports = function(arr, obj){ + if (indexOf) return arr.indexOf(obj); + for (var i = 0; i < arr.length; ++i) { + if (arr[i] === obj) return i; + } + return -1; +}; \ No newline at end of file diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/package.json b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/package.json new file mode 100644 index 0000000..ee61e18 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/node_modules/indexof/package.json @@ -0,0 +1,22 @@ +{ + "name": "indexof", + "description": "Microsoft sucks", + "version": "0.0.1", + "keywords": [ + "index", + "array", + "indexOf" + ], + "dependencies": {}, + "component": { + "scripts": { + "indexof/index.js": "index.js" + } + }, + "readme": "\n# indexOf\n\n Lame indexOf thing, thanks microsoft\n\n## Example\n\n```js\nvar index = require('indexof');\nindex(arr, obj);\n```\n\n## License\n\n MIT", + "readmeFilename": "Readme.md", + "_id": "indexof@0.0.1", + "_shasum": "82dc336d232b9062179d05ab3293a66059fd435d", + "_resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", + "_from": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/package.json b/node_modules/meteor-node-stubs/node_modules/vm-browserify/package.json new file mode 100644 index 0000000..1bb1e2b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/package.json @@ -0,0 +1,56 @@ +{ + "name": "vm-browserify", + "version": "0.0.4", + "description": "vm module for the browser", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/substack/vm-browserify.git" + }, + "keywords": [ + "vm", + "browser", + "eval" + ], + "dependencies": { + "indexof": "0.0.1" + }, + "devDependencies": { + "tape": "~2.3.2" + }, + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "scripts": { + "test": "tap test/*.js" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "readme": "# vm-browserify\n\nemulate node's vm module for the browser\n\n[![testling badge](https://ci.testling.com/substack/vm-browserify.png)](https://ci.testling.com/substack/vm-browserify)\n\n# example\n\nJust write some client-side javascript:\n\n``` js\nvar vm = require('vm');\n\n$(function () {\n var res = vm.runInNewContext('a + 5', { a : 100 });\n $('#res').text(res);\n});\n```\n\ncompile it with [browserify](http://github.com/substack/node-browserify):\n\n```\nbrowserify entry.js -o bundle.js\n```\n\nthen whip up some html:\n\n``` html\n\n \n \n \n \n \n result = \n \n\n```\n\nand when you load the page you should see:\n\n```\nresult = 105\n```\n\n# methods\n\n## vm.runInNewContext(code, context={})\n\nEvaluate some `code` in a new iframe with a `context`.\n\nContexts are like wrapping your code in a `with()` except slightly less terrible\nbecause the code is sandboxed into a new iframe.\n\n# install\n\nThis module is depended upon by browserify, so you should just be able to\n`require('vm')` and it will just work. However if you want to use this module\ndirectly you can install it with [npm](http://npmjs.org):\n\n```\nnpm install vm-browserify\n```\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/vm-browserify/issues" + }, + "homepage": "https://github.com/substack/vm-browserify#readme", + "_id": "vm-browserify@0.0.4", + "_shasum": "5d7ea45bbef9e4a6ff65f95438e0a87c357d5a73", + "_resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz", + "_from": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz" +} diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/readme.markdown b/node_modules/meteor-node-stubs/node_modules/vm-browserify/readme.markdown new file mode 100644 index 0000000..1ad139b --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/readme.markdown @@ -0,0 +1,67 @@ +# vm-browserify + +emulate node's vm module for the browser + +[![testling badge](https://ci.testling.com/substack/vm-browserify.png)](https://ci.testling.com/substack/vm-browserify) + +# example + +Just write some client-side javascript: + +``` js +var vm = require('vm'); + +$(function () { + var res = vm.runInNewContext('a + 5', { a : 100 }); + $('#res').text(res); +}); +``` + +compile it with [browserify](http://github.com/substack/node-browserify): + +``` +browserify entry.js -o bundle.js +``` + +then whip up some html: + +``` html + + + + + + + result = + + +``` + +and when you load the page you should see: + +``` +result = 105 +``` + +# methods + +## vm.runInNewContext(code, context={}) + +Evaluate some `code` in a new iframe with a `context`. + +Contexts are like wrapping your code in a `with()` except slightly less terrible +because the code is sandboxed into a new iframe. + +# install + +This module is depended upon by browserify, so you should just be able to +`require('vm')` and it will just work. However if you want to use this module +directly you can install it with [npm](http://npmjs.org): + +``` +npm install vm-browserify +``` + +# license + +MIT diff --git a/node_modules/meteor-node-stubs/node_modules/vm-browserify/test/vm.js b/node_modules/meteor-node-stubs/node_modules/vm-browserify/test/vm.js new file mode 100644 index 0000000..ea8cd31 --- /dev/null +++ b/node_modules/meteor-node-stubs/node_modules/vm-browserify/test/vm.js @@ -0,0 +1,35 @@ +var test = require('tape'); +var vm = require('../'); + +test('vmRunInNewContext', function (t) { + t.plan(6); + + t.equal(vm.runInNewContext('a + 5', { a : 100 }), 105); + + (function () { + var vars = { x : 10 }; + t.equal(vm.runInNewContext('x++', vars), 10); + t.equal(vars.x, 11); + })(); + + (function () { + var vars = { x : 10 }; + t.equal(vm.runInNewContext('var y = 3; y + x++', vars), 13); + t.equal(vars.x, 11); + t.equal(vars.y, 3); + })(); + + t.end(); +}); + +test('vmRunInContext', function (t) { + t.plan(2); + + var context = vm.createContext({ foo: 1 }); + + vm.runInContext('var x = 1', context); + t.deepEqual(context, { foo: 1, x: 1 }); + + vm.runInContext('var y = 1', context); + t.deepEqual(context, { foo: 1, x: 1, y: 1 }); +}); diff --git a/node_modules/meteor-node-stubs/npm-shrinkwrap.json b/node_modules/meteor-node-stubs/npm-shrinkwrap.json new file mode 100644 index 0000000..64aadf2 --- /dev/null +++ b/node_modules/meteor-node-stubs/npm-shrinkwrap.json @@ -0,0 +1,507 @@ +{ + "name": "meteor-node-stubs", + "version": "0.2.3", + "dependencies": { + "assert": { + "version": "1.3.0", + "from": "assert@>=1.3.0 <2.0.0", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.3.0.tgz" + }, + "browserify-zlib": { + "version": "0.1.4", + "from": "browserify-zlib@>=0.1.4 <0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.1.4.tgz", + "dependencies": { + "pako": { + "version": "0.2.8", + "from": "pako@>=0.2.0 <0.3.0", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.8.tgz" + } + } + }, + "buffer": { + "version": "4.5.1", + "from": "buffer@>=4.5.1 <5.0.0", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.5.1.tgz", + "dependencies": { + "base64-js": { + "version": "1.1.2", + "from": "base64-js@>=1.0.2 <2.0.0", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.1.2.tgz" + }, + "ieee754": { + "version": "1.1.6", + "from": "ieee754@>=1.1.4 <2.0.0", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.6.tgz" + }, + "isarray": { + "version": "1.0.0", + "from": "isarray@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz" + } + } + }, + "console-browserify": { + "version": "1.1.0", + "from": "console-browserify@>=1.1.0 <2.0.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", + "dependencies": { + "date-now": { + "version": "0.1.4", + "from": "date-now@>=0.1.4 <0.2.0", + "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz" + } + } + }, + "constants-browserify": { + "version": "1.0.0", + "from": "constants-browserify@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz" + }, + "crypto-browserify": { + "version": "3.11.0", + "from": "crypto-browserify@>=3.11.0 <4.0.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.11.0.tgz", + "dependencies": { + "browserify-cipher": { + "version": "1.0.0", + "from": "browserify-cipher@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.0.tgz", + "dependencies": { + "browserify-aes": { + "version": "1.0.6", + "from": "browserify-aes@>=1.0.4 <2.0.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz", + "dependencies": { + "buffer-xor": { + "version": "1.0.3", + "from": "buffer-xor@>=1.0.2 <2.0.0", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz" + }, + "cipher-base": { + "version": "1.0.2", + "from": "cipher-base@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" + } + } + }, + "browserify-des": { + "version": "1.0.0", + "from": "browserify-des@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.0.tgz", + "dependencies": { + "cipher-base": { + "version": "1.0.2", + "from": "cipher-base@>=1.0.1 <2.0.0", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" + }, + "des.js": { + "version": "1.0.0", + "from": "des.js@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", + "dependencies": { + "minimalistic-assert": { + "version": "1.0.0", + "from": "minimalistic-assert@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz" + } + } + } + } + }, + "evp_bytestokey": { + "version": "1.0.0", + "from": "evp_bytestokey@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz" + } + } + }, + "browserify-sign": { + "version": "4.0.0", + "from": "browserify-sign@>=4.0.0 <5.0.0", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.0.tgz", + "dependencies": { + "bn.js": { + "version": "4.11.1", + "from": "bn.js@>=4.1.0 <5.0.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz" + }, + "browserify-rsa": { + "version": "4.0.1", + "from": "browserify-rsa@>=4.0.0 <5.0.0", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz" + }, + "elliptic": { + "version": "6.2.3", + "from": "elliptic@>=6.0.0 <7.0.0", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.2.3.tgz", + "dependencies": { + "brorand": { + "version": "1.0.5", + "from": "brorand@>=1.0.1 <2.0.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz" + }, + "hash.js": { + "version": "1.0.3", + "from": "hash.js@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.0.3.tgz" + } + } + }, + "parse-asn1": { + "version": "5.0.0", + "from": "parse-asn1@>=5.0.0 <6.0.0", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.0.0.tgz", + "dependencies": { + "asn1.js": { + "version": "4.5.2", + "from": "asn1.js@>=4.0.0 <5.0.0", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.5.2.tgz", + "dependencies": { + "minimalistic-assert": { + "version": "1.0.0", + "from": "minimalistic-assert@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz" + } + } + }, + "browserify-aes": { + "version": "1.0.6", + "from": "browserify-aes@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz", + "dependencies": { + "buffer-xor": { + "version": "1.0.3", + "from": "buffer-xor@>=1.0.2 <2.0.0", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz" + }, + "cipher-base": { + "version": "1.0.2", + "from": "cipher-base@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" + } + } + }, + "evp_bytestokey": { + "version": "1.0.0", + "from": "evp_bytestokey@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz" + } + } + } + } + }, + "create-ecdh": { + "version": "4.0.0", + "from": "create-ecdh@>=4.0.0 <5.0.0", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.0.tgz", + "dependencies": { + "bn.js": { + "version": "4.11.1", + "from": "bn.js@>=4.1.0 <5.0.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz" + }, + "elliptic": { + "version": "6.2.3", + "from": "elliptic@>=6.0.0 <7.0.0", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.2.3.tgz", + "dependencies": { + "brorand": { + "version": "1.0.5", + "from": "brorand@>=1.0.1 <2.0.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz" + }, + "hash.js": { + "version": "1.0.3", + "from": "hash.js@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.0.3.tgz" + } + } + } + } + }, + "create-hash": { + "version": "1.1.2", + "from": "create-hash@>=1.1.0 <2.0.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.1.2.tgz", + "dependencies": { + "cipher-base": { + "version": "1.0.2", + "from": "cipher-base@>=1.0.1 <2.0.0", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" + }, + "ripemd160": { + "version": "1.0.1", + "from": "ripemd160@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-1.0.1.tgz" + }, + "sha.js": { + "version": "2.4.5", + "from": "sha.js@>=2.3.6 <3.0.0", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.5.tgz" + } + } + }, + "create-hmac": { + "version": "1.1.4", + "from": "create-hmac@>=1.1.0 <2.0.0", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.4.tgz" + }, + "diffie-hellman": { + "version": "5.0.2", + "from": "diffie-hellman@>=5.0.0 <6.0.0", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.2.tgz", + "dependencies": { + "bn.js": { + "version": "4.11.1", + "from": "bn.js@>=4.1.0 <5.0.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz" + }, + "miller-rabin": { + "version": "4.0.0", + "from": "miller-rabin@>=4.0.0 <5.0.0", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.0.tgz", + "dependencies": { + "brorand": { + "version": "1.0.5", + "from": "brorand@>=1.0.1 <2.0.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.0.5.tgz" + } + } + } + } + }, + "inherits": { + "version": "2.0.1", + "from": "inherits@>=2.0.1 <3.0.0", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "pbkdf2": { + "version": "3.0.4", + "from": "pbkdf2@>=3.0.3 <4.0.0", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.4.tgz" + }, + "public-encrypt": { + "version": "4.0.0", + "from": "public-encrypt@>=4.0.0 <5.0.0", + "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.0.tgz", + "dependencies": { + "bn.js": { + "version": "4.11.1", + "from": "bn.js@>=4.1.0 <5.0.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.1.tgz" + }, + "browserify-rsa": { + "version": "4.0.1", + "from": "browserify-rsa@>=4.0.0 <5.0.0", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz" + }, + "parse-asn1": { + "version": "5.0.0", + "from": "parse-asn1@>=5.0.0 <6.0.0", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.0.0.tgz", + "dependencies": { + "asn1.js": { + "version": "4.5.2", + "from": "asn1.js@>=4.0.0 <5.0.0", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.5.2.tgz", + "dependencies": { + "minimalistic-assert": { + "version": "1.0.0", + "from": "minimalistic-assert@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.0.tgz" + } + } + }, + "browserify-aes": { + "version": "1.0.6", + "from": "browserify-aes@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.0.6.tgz", + "dependencies": { + "buffer-xor": { + "version": "1.0.3", + "from": "buffer-xor@>=1.0.2 <2.0.0", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz" + }, + "cipher-base": { + "version": "1.0.2", + "from": "cipher-base@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.2.tgz" + } + } + }, + "evp_bytestokey": { + "version": "1.0.0", + "from": "evp_bytestokey@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.0.tgz" + } + } + } + } + }, + "randombytes": { + "version": "2.0.3", + "from": "randombytes@>=2.0.0 <3.0.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.0.3.tgz" + } + } + }, + "domain-browser": { + "version": "1.1.7", + "from": "domain-browser@>=1.1.7 <2.0.0", + "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.1.7.tgz" + }, + "events": { + "version": "1.1.0", + "from": "events@>=1.1.0 <2.0.0", + "resolved": "https://registry.npmjs.org/events/-/events-1.1.0.tgz" + }, + "http-browserify": { + "version": "1.7.0", + "from": "http-browserify@>=1.7.0 <2.0.0", + "resolved": "https://registry.npmjs.org/http-browserify/-/http-browserify-1.7.0.tgz", + "dependencies": { + "Base64": { + "version": "0.2.1", + "from": "Base64@>=0.2.0 <0.3.0", + "resolved": "https://registry.npmjs.org/Base64/-/Base64-0.2.1.tgz" + }, + "inherits": { + "version": "2.0.1", + "from": "inherits@>=2.0.1 <2.1.0", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + } + } + }, + "https-browserify": { + "version": "0.0.1", + "from": "https-browserify@0.0.1", + "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-0.0.1.tgz" + }, + "os-browserify": { + "version": "0.2.1", + "from": "os-browserify@>=0.2.1 <0.3.0", + "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.2.1.tgz" + }, + "path-browserify": { + "version": "0.0.0", + "from": "path-browserify@0.0.0", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz" + }, + "process": { + "version": "0.11.2", + "from": "process@>=0.11.2 <0.12.0", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.2.tgz" + }, + "punycode": { + "version": "1.4.1", + "from": "punycode@>=1.4.1 <2.0.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz" + }, + "querystring-es3": { + "version": "0.2.1", + "from": "querystring-es3@>=0.2.1 <0.3.0", + "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz" + }, + "readable-stream": { + "version": "2.0.6", + "from": "readable-stream@>=2.0.6 <3.0.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.0.6.tgz", + "dependencies": { + "core-util-is": { + "version": "1.0.2", + "from": "core-util-is@>=1.0.0 <1.1.0", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz" + }, + "inherits": { + "version": "2.0.1", + "from": "inherits@>=2.0.1 <2.1.0", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "isarray": { + "version": "1.0.0", + "from": "isarray@>=1.0.0 <2.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz" + }, + "process-nextick-args": { + "version": "1.0.6", + "from": "process-nextick-args@>=1.0.6 <1.1.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.6.tgz" + }, + "util-deprecate": { + "version": "1.0.2", + "from": "util-deprecate@>=1.0.1 <1.1.0", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz" + } + } + }, + "stream-browserify": { + "version": "2.0.1", + "from": "stream-browserify@>=2.0.1 <3.0.0", + "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.1.tgz", + "dependencies": { + "inherits": { + "version": "2.0.1", + "from": "inherits@>=2.0.1 <2.1.0", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + } + } + }, + "string_decoder": { + "version": "0.10.31", + "from": "string_decoder@>=0.10.31 <0.11.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" + }, + "timers-browserify": { + "version": "1.4.2", + "from": "timers-browserify@>=1.4.2 <2.0.0", + "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-1.4.2.tgz" + }, + "tty-browserify": { + "version": "0.0.0", + "from": "tty-browserify@0.0.0", + "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz" + }, + "url": { + "version": "0.11.0", + "from": "url@>=0.11.0 <0.12.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "dependencies": { + "punycode": { + "version": "1.3.2", + "from": "punycode@1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz" + }, + "querystring": { + "version": "0.2.0", + "from": "querystring@0.2.0", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz" + } + } + }, + "util": { + "version": "0.10.3", + "from": "util@>=0.10.3 <0.11.0", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", + "dependencies": { + "inherits": { + "version": "2.0.1", + "from": "inherits@2.0.1", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + } + } + }, + "vm-browserify": { + "version": "0.0.4", + "from": "vm-browserify@0.0.4", + "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz", + "dependencies": { + "indexof": { + "version": "0.0.1", + "from": "indexof@0.0.1", + "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz" + } + } + } + } +} diff --git a/node_modules/meteor-node-stubs/package.json b/node_modules/meteor-node-stubs/package.json new file mode 100644 index 0000000..bb1345e --- /dev/null +++ b/node_modules/meteor-node-stubs/package.json @@ -0,0 +1,92 @@ +{ + "name": "meteor-node-stubs", + "author": { + "name": "Ben Newman", + "email": "ben@meteor.com" + }, + "description": "Stub implementations of Node built-in modules, a la Browserify", + "version": "0.2.3", + "main": "index.js", + "license": "MIT", + "scripts": { + "prepublish": "node build-deps.js" + }, + "dependencies": { + "assert": "^1.3.0", + "browserify-zlib": "^0.1.4", + "buffer": "^4.5.1", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.7", + "events": "^1.1.0", + "http-browserify": "^1.7.0", + "https-browserify": "0.0.1", + "os-browserify": "^0.2.1", + "path-browserify": "0.0.0", + "process": "^0.11.2", + "punycode": "^1.4.1", + "querystring-es3": "^0.2.1", + "readable-stream": "^2.0.6", + "stream-browserify": "^2.0.1", + "string_decoder": "^0.10.31", + "timers-browserify": "^1.4.2", + "tty-browserify": "0.0.0", + "url": "^0.11.0", + "util": "^0.10.3", + "vm-browserify": "0.0.4" + }, + "devDependencies": { + "rimraf": "^2.5.2" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/meteor/node-stubs.git" + }, + "keywords": [ + "stubs", + "shims", + "node", + "builtins", + "core", + "modules", + "browserify", + "webpack", + "meteor" + ], + "bugs": { + "url": "https://github.com/meteor/node-stubs/issues" + }, + "homepage": "https://github.com/meteor/node-stubs#readme", + "gitHead": "2d3849b8081eded7b96064d39f6d85eaf3d6e30c", + "_id": "meteor-node-stubs@0.2.3", + "_shasum": "b4d27fadb0f256ae07c2d12539105df83083863a", + "_from": "meteor-node-stubs@latest", + "_npmVersion": "2.14.22", + "_nodeVersion": "0.10.43", + "_npmUser": { + "name": "benjamn", + "email": "bn@cs.stanford.edu" + }, + "maintainers": [ + { + "name": "benjamn", + "email": "bn@cs.stanford.edu" + }, + { + "name": "mdg", + "email": "npm@meteor.com" + } + ], + "dist": { + "shasum": "b4d27fadb0f256ae07c2d12539105df83083863a", + "tarball": "https://registry.npmjs.org/meteor-node-stubs/-/meteor-node-stubs-0.2.3.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/meteor-node-stubs-0.2.3.tgz_1460124489959_0.682892706245184" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/meteor-node-stubs/-/meteor-node-stubs-0.2.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/projects/collections/schema.js b/projects/collections/schema.js index c11e408..f5ff607 100644 --- a/projects/collections/schema.js +++ b/projects/collections/schema.js @@ -170,7 +170,7 @@ ProjectsSchema = new SimpleSchema({ type: String, label: "Project Name", optional: false, - + }, "description": { type: String, @@ -350,6 +350,11 @@ ProjectsSchema = new SimpleSchema({ type: Boolean, label: "Has this project a completely filled profile to be presented on the Setelin APP?", defaultValue: false + }, + "upvotes": { + type: Number, + label: "vote count", + defaultValue: 0 } /*, media: { diff --git a/projects/server/api/v02/projectsApi.js b/projects/server/api/v02/projectsApi.js index 620517b..7d443ec 100644 --- a/projects/server/api/v02/projectsApi.js +++ b/projects/server/api/v02/projectsApi.js @@ -3,8 +3,8 @@ prettyJson: true, version:'v02', defaultHeaders: {'Content-Type': 'application/json; charset=UTF-8'} - }); - + }); + // Generates: GET on /api/v01/projects // /api/v01/projects/:id for the Projects collection Projects = Mongo.Collection.get('projects'); @@ -28,4 +28,30 @@ data: Projects.findOne({_id:this.urlParams.id}) }; } - }); \ No newline at end of file + }); + + ProjectsApiV02.addRoute('projects/:id/upvote', { + get: function () { + Projects.update(this.urlParams.id, { + // $set: { voteCount: 2 }, + $inc: { "upvotes": 1 }, + }); + return { + status: "success", + data: Projects.findOne({_id:this.urlParams.id}) + }; + } + }); + + ProjectsApiV02.addRoute('projects/:id/downvote', { + get: function () { + Projects.update(this.urlParams.id, { + // $set: { voteCount: 2 }, + $inc: { "upvotes": -1 }, + }); + return { + status: "success", + data: Projects.findOne({_id:this.urlParams.id}) + }; + } +});