Deps updates

This commit is contained in:
Dobie Wollert
2015-11-24 22:12:24 -08:00
parent 974014ab44
commit f5bc55b1f5
504 changed files with 69316 additions and 15 deletions

9
node_modules/cors/.eslintrc generated vendored Normal file
View File

@ -0,0 +1,9 @@
{
"env": {
"node": true
},
"rules": {
"indent": [2, 2],
"quotes": "single"
}
}

3
node_modules/cors/.npmignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
.DS_Store
node_modules
npm-debug.log

3
node_modules/cors/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,3 @@
language: node_js
node_js:
- 0.10

35
node_modules/cors/CONTRIBUTING.md generated vendored Normal file
View File

@ -0,0 +1,35 @@
# contributing to `cors`
CORS is a node.js package for providing a [connect](http://www.senchalabs.org/connect/)/[express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options. Learn more about the project in [the README](README.md).
[![build status](https://secure.travis-ci.org/TroyGoode/node-cors.png)](http://travis-ci.org/TroyGoode/node-cors)
## The CORS Spec
[http://www.w3.org/TR/cors/](http://www.w3.org/TR/cors/)
## Pull Requests Welcome
* Include `'use strict';` in every javascript file.
* 2 space indentation.
* Please run the testing steps below before submitting.
## Testing
```bash
$ npm install
$ npm test
```
## Interactive Testing Harness
[http://node-cors-client.herokuapp.com](http://node-cors-client.herokuapp.com)
Related git repositories:
* [https://github.com/TroyGoode/node-cors-server](https://github.com/TroyGoode/node-cors-server)
* [https://github.com/TroyGoode/node-cors-client](https://github.com/TroyGoode/node-cors-client)
## License
[MIT License](http://www.opensource.org/licenses/mit-license.php)

9
node_modules/cors/LICENSE generated vendored Normal file
View File

@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 2013 Troy Goode <troygoode@gmail.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.

192
node_modules/cors/README.md generated vendored Normal file
View File

@ -0,0 +1,192 @@
# `cors`
CORS is a node.js package for providing a [Connect](http://www.senchalabs.org/connect/)/[Express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options.
**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)**
[![NPM](https://nodei.co/npm/cors.png?downloads=true&stars=true)](https://nodei.co/npm/cors/)
[![build status](https://secure.travis-ci.org/expressjs/cors.png)](http://travis-ci.org/expressjs/cors)
* [Installation](#installation)
* [Usage](#usage)
* [Simple Usage](#simple-usage-enable-all-cors-requests)
* [Enable CORS for a Single Route](#enable-cors-for-a-single-route)
* [Configuring CORS](#configuring-cors)
* [Configuring CORS Asynchronously](#configuring-cors-asynchronously)
* [Enabling CORS Pre-Flight](#enabling-cors-pre-flight)
* [Configuration Options](#configuration-options)
* [Demo](#demo)
* [License](#license)
* [Author](#author)
## Installation (via [npm](https://npmjs.org/package/cors))
```bash
$ npm install cors
```
## Usage
### Simple Usage (Enable *All* CORS Requests)
```javascript
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
app.get('/products/:id', function(req, res, next){
res.json({msg: 'This is CORS-enabled for all origins!'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
```
### Enable CORS for a Single Route
```javascript
var express = require('express')
, cors = require('cors')
, app = express();
app.get('/products/:id', cors(), function(req, res, next){
res.json({msg: 'This is CORS-enabled for all origins!'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
```
### Configuring CORS
```javascript
var express = require('express')
, cors = require('cors')
, app = express();
var corsOptions = {
origin: 'http://example.com'
};
app.get('/products/:id', cors(corsOptions), function(req, res, next){
res.json({msg: 'This is CORS-enabled for only example.com.'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
```
### Configuring CORS w/ Dynamic Origin
```javascript
var express = require('express')
, cors = require('cors')
, app = express();
var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
app.get('/products/:id', cors(corsOptions), function(req, res, next){
res.json({msg: 'This is CORS-enabled for a whitelisted domain.'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
```
### Enabling CORS Pre-Flight
Certain CORS requests are considered 'complex' and require an initial
`OPTIONS` request (called the "pre-flight request"). An example of a
'complex' CORS request is one that uses an HTTP verb other than
GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable
pre-flighting, you must add a new OPTIONS handler for the route you want
to support:
```javascript
var express = require('express')
, cors = require('cors')
, app = express();
app.options('/products/:id', cors()); // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function(req, res, next){
res.json({msg: 'This is CORS-enabled for all origins!'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
```
You can also enable pre-flight across-the-board like so:
```
app.options('*', cors()); // include before other routes
```
### Configuring CORS Asynchronously
```javascript
var express = require('express')
, cors = require('cors')
, app = express();
var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptionsDelegate = function(req, callback){
var corsOptions;
if(whitelist.indexOf(req.header('Origin')) !== -1){
corsOptions = { origin: true }; // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false }; // disable CORS for this request
}
callback(null, corsOptions); // callback expects two parameters: error and options
};
app.get('/products/:id', cors(corsOptionsDelegate), function(req, res, next){
res.json({msg: 'This is CORS-enabled for a whitelisted domain.'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
```
## Configuration Options
* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Expects a string (ex: "http://example.com"). Set to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), as defined by `req.header('Origin')`. Set to `false` to disable CORS. Can also be set to a function, which takes the request origin as the first parameter and a callback (which expects the signature `err [object], allow [bool]`) as the second. Finally, it can also be a regular expression (`/example\.com$/`) or an array of regular expressions and/or strings to match against.
* `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`).
* `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization']`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header.
* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed.
* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted.
* `maxAge`: Configures the **Access-Control-Allow-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted.
* `preflightContinue`: Pass the CORS preflight response to the next handler.
For details on the effect of each CORS header, [read this article on HTML5 Rocks](http://www.html5rocks.com/en/tutorials/cors/).
## Demo
A demo that illustrates CORS working (and not working) using jQuery is available here: [http://node-cors-client.herokuapp.com/](http://node-cors-client.herokuapp.com/)
Code for that demo can be found here:
* Client: [https://github.com/TroyGoode/node-cors-client](https://github.com/TroyGoode/node-cors-client)
* Server: [https://github.com/TroyGoode/node-cors-server](https://github.com/TroyGoode/node-cors-server)
## License
[MIT License](http://www.opensource.org/licenses/mit-license.php)
## Author
[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com))

242
node_modules/cors/lib/index.js generated vendored Normal file
View File

@ -0,0 +1,242 @@
(function () {
'use strict';
var vary = require('vary');
var defaults = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false
};
function isString(s) {
return typeof s === 'string' || s instanceof String;
}
function isOriginAllowed(origin, allowedOrigin) {
if (Array.isArray(allowedOrigin)) {
for (var i = 0; i < allowedOrigin.length; ++i) {
if (isOriginAllowed(origin, allowedOrigin[i])) {
return true;
}
}
return false;
} else if (isString(allowedOrigin)) {
return origin === allowedOrigin;
} else if (allowedOrigin instanceof RegExp) {
return allowedOrigin.test(origin);
} else {
return !!allowedOrigin;
}
}
function configureOrigin(options, req) {
var requestOrigin = req.headers.origin,
headers = [],
isAllowed;
if (!options.origin || options.origin === '*') {
// allow any origin
headers.push([{
key: 'Access-Control-Allow-Origin',
value: '*'
}]);
} else if (isString(options.origin)) {
// fixed origin
headers.push([{
key: 'Access-Control-Allow-Origin',
value: options.origin
}]);
headers.push([{
key: 'Vary',
value: 'Origin'
}]);
} else {
isAllowed = isOriginAllowed(requestOrigin, options.origin);
// reflect origin
headers.push([{
key: 'Access-Control-Allow-Origin',
value: isAllowed ? requestOrigin : false
}]);
if (isAllowed) {
headers.push([{
key: 'Vary',
value: 'Origin'
}]);
}
}
return headers;
}
function configureMethods(options) {
var methods = options.methods || defaults.methods;
if (methods.join) {
methods = options.methods.join(','); // .methods is an array, so turn it into a string
}
return {
key: 'Access-Control-Allow-Methods',
value: methods
};
}
function configureCredentials(options) {
if (options.credentials === true) {
return {
key: 'Access-Control-Allow-Credentials',
value: 'true'
};
}
return null;
}
function configureAllowedHeaders(options, req) {
var headers = options.allowedHeaders || options.headers;
if (!headers) {
headers = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
} else if (headers.join) {
headers = headers.join(','); // .headers is an array, so turn it into a string
}
if (headers && headers.length) {
return {
key: 'Access-Control-Allow-Headers',
value: headers
};
}
return null;
}
function configureExposedHeaders(options) {
var headers = options.exposedHeaders;
if (!headers) {
return null;
} else if (headers.join) {
headers = headers.join(','); // .headers is an array, so turn it into a string
}
if (headers && headers.length) {
return {
key: 'Access-Control-Expose-Headers',
value: headers
};
}
return null;
}
function configureMaxAge(options) {
var maxAge = options.maxAge && options.maxAge.toString();
if (maxAge && maxAge.length) {
return {
key: 'Access-Control-Max-Age',
value: maxAge
};
}
return null;
}
function applyHeaders(headers, res) {
for (var i = 0, n = headers.length; i < n; i++) {
var header = headers[i];
if (header) {
if (Array.isArray(header)) {
applyHeaders(header, res);
} else if (header.key === 'Vary' && header.value) {
vary(res, header.value);
} else if (header.value) {
res.setHeader(header.key, header.value);
}
}
}
}
function cors(options, req, res, next) {
var headers = [],
method = req.method && req.method.toUpperCase && req.method.toUpperCase();
if (method === 'OPTIONS') {
// preflight
headers.push(configureOrigin(options, req));
headers.push(configureCredentials(options, req));
headers.push(configureMethods(options, req));
headers.push(configureAllowedHeaders(options, req));
headers.push(configureMaxAge(options, req));
headers.push(configureExposedHeaders(options, req));
applyHeaders(headers, res);
if (options.preflightContinue ) {
next();
} else {
res.statusCode = 204;
res.end();
}
} else {
// actual response
headers.push(configureOrigin(options, req));
headers.push(configureCredentials(options, req));
headers.push(configureExposedHeaders(options, req));
applyHeaders(headers, res);
next();
}
}
function middlewareWrapper(o) {
// if no options were passed in, use the defaults
if (!o) {
o = {};
}
if (o.origin === undefined) {
o.origin = defaults.origin;
}
if (o.methods === undefined) {
o.methods = defaults.methods;
}
if (o.preflightContinue === undefined) {
o.preflightContinue = defaults.preflightContinue;
}
// if options are static (either via defaults or custom options passed in), wrap in a function
var optionsCallback = null;
if (typeof o === 'function') {
optionsCallback = o;
} else {
optionsCallback = function (req, cb) {
cb(null, o);
};
}
return function (req, res, next) {
optionsCallback(req, function (err, options) {
if (err) {
next(err);
} else {
var originCallback = null;
if (options.origin && typeof options.origin === 'function') {
originCallback = options.origin;
} else if (options.origin) {
originCallback = function (origin, cb) {
cb(null, options.origin);
};
}
if (originCallback) {
originCallback(req.headers.origin, function (err2, origin) {
if (err2 || !origin) {
next(err2);
} else {
var corsOptions = Object.create(options);
corsOptions.origin = origin;
cors(corsOptions, req, res, next);
}
});
} else {
next();
}
}
});
};
}
// can pass either an options hash, an options delegate, or nothing
module.exports = middlewareWrapper;
}());

29
node_modules/cors/node_modules/vary/HISTORY.md generated vendored Normal file
View File

@ -0,0 +1,29 @@
1.1.0 / 2015-09-29
==================
* Only accept valid field names in the `field` argument
- Ensures the resulting string is a valid HTTP header value
1.0.1 / 2015-07-08
==================
* Fix setting empty header from empty `field`
* perf: enable strict mode
* perf: remove argument reassignments
1.0.0 / 2014-08-10
==================
* Accept valid `Vary` header string as `field`
* Add `vary.append` for low-level string manipulation
* Move to `jshttp` orgainzation
0.1.0 / 2014-06-05
==================
* Support array of fields to set
0.0.0 / 2014-06-04
==================
* Initial release

22
node_modules/cors/node_modules/vary/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2014-2015 Douglas Christopher Wilson
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.

91
node_modules/cors/node_modules/vary/README.md generated vendored Normal file
View File

@ -0,0 +1,91 @@
# vary
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Manipulate the HTTP Vary header
## Installation
```sh
$ npm install vary
```
## API
```js
var vary = require('vary')
```
### vary(res, field)
Adds the given header `field` to the `Vary` response header of `res`.
This can be a string of a single field, a string of a valid `Vary`
header, or an array of multiple fields.
This will append the header if not already listed, otherwise leaves
it listed in the current location.
```js
// Append "Origin" to the Vary header of the response
vary(res, 'Origin')
```
### vary.append(header, field)
Adds the given header `field` to the `Vary` response header string `header`.
This can be a string of a single field, a string of a valid `Vary` header,
or an array of multiple fields.
This will append the header if not already listed, otherwise leaves
it listed in the current location. The new header string is returned.
```js
// Get header string appending "Origin" to "Accept, User-Agent"
vary.append('Accept, User-Agent', 'Origin')
```
## Examples
### Updating the Vary header when content is based on it
```js
var http = require('http')
var vary = require('vary')
http.createServer(function onRequest(req, res) {
// about to user-agent sniff
vary(res, 'User-Agent')
var ua = req.headers['user-agent'] || ''
var isMobile = /mobi|android|touch|mini/i.test(ua)
// serve site, depending on isMobile
res.setHeader('Content-Type', 'text/html')
res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user')
})
```
## Testing
```sh
$ npm test
```
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/vary.svg
[npm-url]: https://npmjs.org/package/vary
[node-version-image]: https://img.shields.io/node/v/vary.svg
[node-version-url]: http://nodejs.org/download/
[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg
[travis-url]: https://travis-ci.org/jshttp/vary
[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg
[coveralls-url]: https://coveralls.io/r/jshttp/vary
[downloads-image]: https://img.shields.io/npm/dm/vary.svg
[downloads-url]: https://npmjs.org/package/vary

124
node_modules/cors/node_modules/vary/index.js generated vendored Normal file
View File

@ -0,0 +1,124 @@
/*!
* vary
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module exports.
*/
module.exports = vary;
module.exports.append = append;
/**
* RegExp to match field-name in RFC 7230 sec 3.2
*
* field-name = token
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
* / DIGIT / ALPHA
* ; any VCHAR, except delimiters
*/
var fieldNameRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* Append a field to a vary header.
*
* @param {String} header
* @param {String|Array} field
* @return {String}
* @api public
*/
function append(header, field) {
if (typeof header !== 'string') {
throw new TypeError('header argument is required');
}
if (!field) {
throw new TypeError('field argument is required');
}
// get fields array
var fields = !Array.isArray(field)
? parse(String(field))
: field;
// assert on invalid field names
for (var i = 0; i < fields.length; i++) {
if (!fieldNameRegExp.test(fields[i])) {
throw new TypeError('field argument contains an invalid header name');
}
}
// existing, unspecified vary
if (header === '*') {
return header;
}
// enumerate current values
var val = header;
var vals = parse(header.toLowerCase());
// unspecified vary
if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
return '*';
}
for (var i = 0; i < fields.length; i++) {
var fld = fields[i].toLowerCase();
// append value (case-preserving)
if (vals.indexOf(fld) === -1) {
vals.push(fld);
val = val
? val + ', ' + fields[i]
: fields[i];
}
}
return val;
}
/**
* Parse a vary header into an array.
*
* @param {String} header
* @return {Array}
* @api private
*/
function parse(header) {
return header.trim().split(/ *, */);
}
/**
* Mark that a request is varied on a header field.
*
* @param {Object} res
* @param {String|Array} field
* @api public
*/
function vary(res, field) {
if (!res || !res.getHeader || !res.setHeader) {
// quack quack
throw new TypeError('res argument is required');
}
// get existing header
var val = res.getHeader('Vary') || ''
var header = Array.isArray(val)
? val.join(', ')
: String(val);
// set new header
if ((val = append(header, field))) {
res.setHeader('Vary', val);
}
}

71
node_modules/cors/node_modules/vary/package.json generated vendored Normal file
View File

@ -0,0 +1,71 @@
{
"name": "vary",
"description": "Manipulate the HTTP Vary header",
"version": "1.1.0",
"author": {
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
"license": "MIT",
"keywords": [
"http",
"res",
"vary"
],
"repository": {
"type": "git",
"url": "https://github.com/jshttp/vary"
},
"devDependencies": {
"istanbul": "0.3.21",
"mocha": "2.3.3",
"supertest": "1.1.0"
},
"files": [
"HISTORY.md",
"LICENSE",
"README.md",
"index.js"
],
"engines": {
"node": ">= 0.8"
},
"scripts": {
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
"gitHead": "13b03e9bf97da9d83bfeac84d84144137d84c257",
"bugs": {
"url": "https://github.com/jshttp/vary/issues"
},
"homepage": "https://github.com/jshttp/vary",
"_id": "vary@1.1.0",
"_shasum": "e1e5affbbd16ae768dd2674394b9ad3022653140",
"_from": "vary@>=1.0.0 <2.0.0",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
{
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
},
{
"name": "fishrock123",
"email": "fishrock123@rocketmail.com"
}
],
"dist": {
"shasum": "e1e5affbbd16ae768dd2674394b9ad3022653140",
"tarball": "http://registry.npmjs.org/vary/-/vary-1.1.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/vary/-/vary-1.1.0.tgz"
}

79
node_modules/cors/package.json generated vendored Normal file
View File

@ -0,0 +1,79 @@
{
"name": "cors",
"version": "2.7.1",
"author": {
"name": "Troy Goode",
"email": "troygoode@gmail.com",
"url": "https://github.com/troygoode/"
},
"description": "middleware for dynamically or statically enabling CORS in express/connect applications",
"keywords": [
"cors",
"express",
"connect",
"middleware"
],
"homepage": "https://github.com/expressjs/cors/",
"repository": {
"type": "git",
"url": "git://github.com/expressjs/cors.git"
},
"contributors": [
{
"name": "Troy Goode",
"email": "troygoode@gmail.com",
"url": "https://github.com/troygoode/"
}
],
"license": "MIT",
"bugs": {
"url": "https://github.com/expressjs/cors/issues"
},
"main": "./lib/index.js",
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"vary": "^1"
},
"devDependencies": {
"basic-auth-connect": "^1.0.0",
"body-parser": "^1.12.4",
"eslint": "^0.21.2",
"express": "^4.12.4",
"mocha": "^2.2.5",
"should": "^6.0.3",
"supertest": "^1.0.1"
},
"scripts": {
"test": "npm run lint && ./node_modules/mocha/bin/mocha",
"lint": "./node_modules/eslint/bin/eslint.js lib test"
},
"gitHead": "bef1a97c22a3f15cb23ab2d9cf8e7e3f7134e107",
"_id": "cors@2.7.1",
"_shasum": "3c2e50a58af9ef8c89bee21226b099be1f02739b",
"_from": "cors@*",
"_npmVersion": "2.5.1",
"_nodeVersion": "0.12.0",
"_npmUser": {
"name": "troygoode",
"email": "troygoode@gmail.com"
},
"maintainers": [
{
"name": "troygoode",
"email": "troygoode@gmail.com"
},
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"dist": {
"shasum": "3c2e50a58af9ef8c89bee21226b099be1f02739b",
"tarball": "http://registry.npmjs.org/cors/-/cors-2.7.1.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/cors/-/cors-2.7.1.tgz",
"readme": "ERROR: No README data found!"
}

40
node_modules/cors/test/basic-auth.js generated vendored Normal file
View File

@ -0,0 +1,40 @@
(function () {
/*global describe, it*/
'use strict';
var should = require('should'),
express = require('express'),
supertest = require('supertest'),
basicAuth = require('basic-auth-connect'),
cors = require('../lib');
var app;
/* -------------------------------------------------------------------------- */
app = express();
app.use(basicAuth('username', 'password'));
app.use(cors());
app.post('/', function (req, res) {
res.send('hello world');
});
/* -------------------------------------------------------------------------- */
describe('basic auth', function () {
it('POST works', function (done) {
supertest(app)
.post('/')
.auth('username', 'password')
.expect(200)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
res.text.should.eql('hello world');
done();
});
});
});
}());

81
node_modules/cors/test/body-events.js generated vendored Normal file
View File

@ -0,0 +1,81 @@
(function () {
/*global describe, it*/
'use strict';
var should = require('should'),
express = require('express'),
supertest = require('supertest'),
bodyParser = require('body-parser'),
cors = require('../lib');
var dynamicOrigin,
app1,
app2,
text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed justo turpis, tempor id sem fringilla, cursus tristique purus. Mauris a sollicitudin magna. Etiam dui lacus, vehicula non dictum at, cursus vitae libero. Curabitur lorem nulla, sollicitudin id enim ut, vehicula rhoncus felis. Ut nec iaculis velit. Vivamus at augue nulla. Fusce at molestie arcu. Duis at dui at tellus mattis tincidunt. Vestibulum sit amet dictum metus. Curabitur nec pretium ante. Proin vulputate elit ac lorem gravida, sit amet placerat lorem fringilla. Mauris fermentum, diam et volutpat auctor, ante enim imperdiet purus, sit amet tincidunt ipsum nulla nec est. Fusce id ipsum in sem malesuada laoreet vitae non magna. Praesent commodo turpis in nulla egestas, eu posuere magna venenatis. Integer in aliquam sem. Fusce quis lorem tincidunt eros rutrum lobortis.\n\nNam aliquam cursus ipsum, a hendrerit purus. Cras ultrices viverra nunc ac lacinia. Sed sed diam orci. Vestibulum ut orci a nibh scelerisque pretium. Sed suscipit vestibulum metus, ac ultricies leo sodales a. Aliquam erat volutpat. Vestibulum mauris massa, luctus et libero vel, cursus suscipit nulla. Cras sed erat quis massa fermentum congue. Mauris ultrices sem ligula, id malesuada lectus tincidunt eget. Donec sed nisl elit. Aenean ac lobortis massa. Phasellus felis nisl, dictum a dui volutpat, dictum sagittis diam. Vestibulum lacinia tellus vel commodo consequat.\n\nNulla at varius nibh, non posuere enim. Curabitur urna est, ultrices vel sem nec, consequat molestie nisi. Aliquam sed augue sit amet ante viverra pretium. Cras aliquam turpis vitae eros gravida egestas. Etiam quis dolor non quam suscipit iaculis. Sed euismod est libero, ac ullamcorper elit hendrerit vitae. Vivamus sollicitudin nulla dolor, vitae porta lacus suscipit ac.\n\nSed volutpat, magna in scelerisque dapibus, eros ante volutpat nisi, ac condimentum diam sem sed justo. Aenean justo risus, bibendum vitae blandit ac, mattis quis nunc. Quisque non felis nec justo auctor accumsan non id odio. Mauris vel dui feugiat dolor dapibus convallis in et neque. Phasellus fermentum sollicitudin tortor ac pretium. Proin tristique accumsan nulla eu venenatis. Cras porta lorem ac arcu accumsan pulvinar. Sed dignissim leo augue, a pretium ante viverra id. Phasellus blandit at purus a malesuada. Nam et cursus mauris. Vivamus accumsan augue laoreet lectus lacinia eleifend. Fusce sit amet felis nunc. Pellentesque eu turpis nisl.\n\nPellentesque vitae quam feugiat, volutpat lectus et, faucibus massa. Maecenas consectetur quis nisi eu aliquam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam laoreet condimentum laoreet. Praesent sit amet massa sit amet dui porta condimentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed volutpat massa nec risus malesuada hendrerit.';
/* -------------------------------------------------------------------------- */
dynamicOrigin = function (origin, cb) {
setTimeout(function () {
cb(null, true);
}, 200);
};
/* -------------------------------------------------------------------------- */
app1 = express();
app1.use(cors({origin: dynamicOrigin}));
app1.use(bodyParser.json());
app1.post('/', function (req, res) {
res.send(req.body);
});
/* -------------------------------------------------------------------------- */
app2 = express();
app2.use(bodyParser.json());
app2.use(cors({origin: dynamicOrigin}));
app2.post('/', function (req, res) {
res.send(req.body);
});
/* -------------------------------------------------------------------------- */
describe('body-parser-events', function () {
describe('app1 (cors before bodyparser)', function () {
it('POST works', function (done) {
var body = {
example: text
};
supertest(app1)
.post('/')
.send(body)
.expect(200)
.end(function (err, res) {
should.not.exist(err);
res.body.should.eql(body);
done();
});
});
});
describe('app2 (bodyparser before cors)', function () {
it('POST works', function (done) {
var body = {
example: text
};
supertest(app2)
.post('/')
.send(body)
.expect(200)
.end(function (err, res) {
should.not.exist(err);
res.body.should.eql(body);
done();
});
});
});
});
}());

652
node_modules/cors/test/cors.js generated vendored Normal file
View File

@ -0,0 +1,652 @@
(function () {
/*global describe, it*/
'use strict';
var should = require('should'),
cors = require('../lib');
var fakeRequest = function (headers) {
return {
headers: headers || {
'origin': 'request.com',
'access-control-request-headers': 'requestedHeader1,requestedHeader2'
},
pause: function () {
// do nothing
return;
},
resume: function () {
// do nothing
return;
}
};
},
fakeResponse = function () {
var headers = {};
return {
allHeaders: function () {
return headers;
},
getHeader: function (key) {
return headers[key];
},
setHeader: function (key, value) {
headers[key] = value;
return;
},
get: function (key) {
return headers[key];
}
};
};
describe('cors', function () {
it('passes control to next middleware', function (done) {
// arrange
var req, res, next;
req = fakeRequest();
res = fakeResponse();
next = function () {
done();
};
// act
cors()(req, res, next);
});
it('shortcircuits preflight requests', function (done) {
// arrange
var req, res, next;
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.statusCode.should.equal(204);
done();
};
next = function () {
// assert
done('should not be called');
};
// act
cors()(req, res, next);
});
it('doesn\'t shortcircuit preflight requests with preflightContinue option', function (done) {
// arrange
var req, res, next;
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
done('should not be called');
};
next = function () {
// assert
done();
};
// act
cors({preflightContinue: true})(req, res, next);
});
it('normalizes method names', function (done) {
// arrange
var req, res, next;
req = fakeRequest();
req.method = 'options';
res = fakeResponse();
res.end = function () {
// assert
res.statusCode.should.equal(204);
done();
};
next = function () {
// assert
done('should not be called');
};
// act
cors()(req, res, next);
});
it('no options enables default CORS to all origins', function (done) {
// arrange
var req, res, next;
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
res.getHeader('Access-Control-Allow-Origin').should.equal('*');
should.not.exist(res.getHeader('Access-Control-Allow-Methods'));
done();
};
// act
cors()(req, res, next);
});
it('OPTION call with no options enables default CORS to all origins and methods', function (done) {
// arrange
var req, res, next;
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.statusCode.should.equal(204);
done();
};
next = function () {
// assert
res.getHeader('Access-Control-Allow-Origin').should.equal('*');
res.getHeader('Access-Control-Allow-Methods').should.equal('GET,PUT,PATCH,POST,DELETE');
done();
};
// act
cors()(req, res, next);
});
describe('passing static options', function () {
it('overrides defaults', function (done) {
// arrange
var req, res, next, options;
options = {
origin: 'example.com',
methods: ['FOO', 'bar'],
headers: ['FIZZ', 'buzz'],
credentials: true,
maxAge: 123
};
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.statusCode.should.equal(204);
done();
};
next = function () {
// assert
res.getHeader('Access-Control-Allow-Origin').should.equal('example.com');
res.getHeader('Access-Control-Allow-Methods').should.equal('FOO,bar');
res.getHeader('Access-Control-Allow-Headers').should.equal('FIZZ,buzz');
res.getHeader('Access-Control-Allow-Credentials').should.equal('true');
res.getHeader('Access-Control-Allow-Max-Age').should.equal('123');
done();
};
// act
cors(options)(req, res, next);
});
it('matches request origin against regexp', function(done) {
var req = fakeRequest();
var res = fakeResponse();
var options = { origin: /^(.+\.)?request.com$/ };
cors(options)(req, res, function(err) {
should.not.exist(err);
res.getHeader('Access-Control-Allow-Origin').should.equal(req.headers.origin);
should.exist(res.getHeader('Vary'));
res.getHeader('Vary').should.equal('Origin');
return done();
});
});
it('matches request origin against array of origin checks', function(done) {
var req = fakeRequest();
var res = fakeResponse();
var options = { origin: [ /foo\.com$/, 'request.com' ] };
cors(options)(req, res, function(err) {
should.not.exist(err);
res.getHeader('Access-Control-Allow-Origin').should.equal(req.headers.origin);
should.exist(res.getHeader('Vary'));
res.getHeader('Vary').should.equal('Origin');
return done();
});
});
it('doesn\'t match request origin against array of invalid origin checks', function(done) {
var req = fakeRequest();
var res = fakeResponse();
var options = { origin: [ /foo\.com$/, 'bar.com' ] };
cors(options)(req, res, function(err) {
should.not.exist(err);
should.not.exist(res.getHeader('Access-Control-Allow-Origin'));
should.not.exist(res.getHeader('Vary'));
return done();
});
});
it('origin of false disables cors', function (done) {
// arrange
var req, res, next, options;
options = {
origin: false,
methods: ['FOO', 'bar'],
headers: ['FIZZ', 'buzz'],
credentials: true,
maxAge: 123
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
should.not.exist(res.getHeader('Access-Control-Allow-Origin'));
should.not.exist(res.getHeader('Access-Control-Allow-Methods'));
should.not.exist(res.getHeader('Access-Control-Allow-Headers'));
should.not.exist(res.getHeader('Access-Control-Allow-Credentials'));
should.not.exist(res.getHeader('Access-Control-Allow-Max-Age'));
done();
};
// act
cors(options)(req, res, next);
});
it('can override origin', function (done) {
// arrange
var req, res, next, options;
options = {
origin: 'example.com'
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
res.getHeader('Access-Control-Allow-Origin').should.equal('example.com');
done();
};
// act
cors(options)(req, res, next);
});
it('includes Vary header for specific origins', function (done) {
// arrange
var req, res, next, options;
options = {
origin: 'example.com'
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
should.exist(res.getHeader('Vary'));
res.getHeader('Vary').should.equal('Origin');
done();
};
// act
cors(options)(req, res, next);
});
it('appends to an existing Vary header', function (done) {
// arrange
var req, res, next, options;
options = {
origin: 'example.com'
};
req = fakeRequest();
res = fakeResponse();
res.setHeader('Vary', 'Foo');
next = function () {
// assert
res.getHeader('Vary').should.equal('Foo, Origin');
done();
};
// act
cors(options)(req, res, next);
});
it('origin defaults to *', function (done) {
// arrange
var req, res, next, options;
options = {
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
res.getHeader('Access-Control-Allow-Origin').should.equal('*');
done();
};
// act
cors(options)(req, res, next);
});
it('specifying true for origin reflects requesting origin', function (done) {
// arrange
var req, res, next, options;
options = {
origin: true
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
res.getHeader('Access-Control-Allow-Origin').should.equal('request.com');
done();
};
// act
cors(options)(req, res, next);
});
it('should allow origin when callback returns true', function (done) {
var req, res, next, options;
options = {
origin: function (sentOrigin, cb) {
sentOrigin.should.equal('request.com');
cb(null, true);
}
};
req = fakeRequest();
res = fakeResponse();
next = function () {
res.getHeader('Access-Control-Allow-Origin').should.equal('request.com');
done();
};
cors(options)(req, res, next);
});
it('should not allow origin when callback returns false', function (done) {
var req, res, next, options;
options = {
origin: function (sentOrigin, cb) {
sentOrigin.should.equal('request.com');
cb(null, false);
}
};
req = fakeRequest();
res = fakeResponse();
next = function () {
should.not.exist(res.getHeader('Access-Control-Allow-Origin'));
should.not.exist(res.getHeader('Access-Control-Allow-Methods'));
should.not.exist(res.getHeader('Access-Control-Allow-Headers'));
should.not.exist(res.getHeader('Access-Control-Allow-Credentials'));
should.not.exist(res.getHeader('Access-Control-Allow-Max-Age'));
done();
};
cors(options)(req, res, next);
});
it('should not override options.origin callback', function (done) {
var req, res, next, options;
options = {
origin: function (sentOrigin, cb) {
var isValid = sentOrigin === 'request.com';
cb(null, isValid);
}
};
req = fakeRequest();
res = fakeResponse();
next = function () {
res.getHeader('Access-Control-Allow-Origin').should.equal('request.com');
};
cors(options)(req, res, next);
req = fakeRequest({
'origin': 'invalid-request.com'
});
res = fakeResponse();
next = function () {
should.not.exist(res.getHeader('Access-Control-Allow-Origin'));
should.not.exist(res.getHeader('Access-Control-Allow-Methods'));
should.not.exist(res.getHeader('Access-Control-Allow-Headers'));
should.not.exist(res.getHeader('Access-Control-Allow-Credentials'));
should.not.exist(res.getHeader('Access-Control-Allow-Max-Age'));
done();
};
cors(options)(req, res, next);
});
it('can override methods', function (done) {
// arrange
var req, res, next, options;
options = {
methods: ['method1', 'method2']
};
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.statusCode.should.equal(204);
done();
};
next = function () {
// assert
res.getHeader('Access-Control-Allow-Methods').should.equal('method1,method2');
done();
};
// act
cors(options)(req, res, next);
});
it('methods defaults to GET, PUT, PATCH, POST, DELETE', function (done) {
// arrange
var req, res, next, options;
options = {
};
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.statusCode.should.equal(204);
done();
};
next = function () {
// assert
res.getHeader('Access-Control-Allow-Methods').should.equal('GET,PUT,PATCH,POST,DELETE');
done();
};
// act
cors(options)(req, res, next);
});
it('can specify allowed headers', function (done) {
// arrange
var req, res, options;
options = {
allowedHeaders: ['header1', 'header2']
};
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.getHeader('Access-Control-Allow-Headers').should.equal('header1,header2');
done();
};
// act
cors(options)(req, res, null);
});
it('specifying an empty list or string of allowed headers will result in no response header for allowed headers', function (done) {
// arrange
var req, res, next, options;
options = {
allowedHeaders: []
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
should.not.exist(res.getHeader('Access-Control-Allow-Headers'));
done();
};
// act
cors(options)(req, res, next);
});
it('if no allowed headers are specified, defaults to requested allowed headers', function (done) {
// arrange
var req, res, options;
options = {
};
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.getHeader('Access-Control-Allow-Headers').should.equal('requestedHeader1,requestedHeader2');
done();
};
// act
cors(options)(req, res, null);
});
it('can specify exposed headers', function (done) {
// arrange
var req, res, options, next;
options = {
exposedHeaders: ['custom-header1', 'custom-header2']
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
res.getHeader('Access-Control-Expose-Headers').should.equal('custom-header1,custom-header2');
done();
};
// act
cors(options)(req, res, next);
});
it('includes credentials if explicitly enabled', function (done) {
// arrange
var req, res, options;
options = {
credentials: true
};
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.getHeader('Access-Control-Allow-Credentials').should.equal('true');
done();
};
// act
cors(options)(req, res, null);
});
it('does not includes credentials unless explicitly enabled', function (done) {
// arrange
var req, res, next, options;
options = {
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
should.not.exist(res.getHeader('Access-Control-Allow-Credentials'));
done();
};
// act
cors(options)(req, res, next);
});
it('includes maxAge when specified', function (done) {
// arrange
var req, res, options;
options = {
maxAge: 456
};
req = fakeRequest();
req.method = 'OPTIONS';
res = fakeResponse();
res.end = function () {
// assert
res.getHeader('Access-Control-Max-Age').should.equal('456');
done();
};
// act
cors(options)(req, res, null);
});
it('does not includes maxAge unless specified', function (done) {
// arrange
var req, res, next, options;
options = {
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
should.not.exist(res.getHeader('Access-Control-Allow-Max-Age'));
done();
};
// act
cors(options)(req, res, next);
});
});
describe('passing a function to build options', function () {
it('handles options specified via callback', function (done) {
// arrange
var req, res, next, delegate;
delegate = function (req2, cb) {
cb(null, {
origin: 'delegate.com'
});
};
req = fakeRequest();
res = fakeResponse();
next = function () {
// assert
res.getHeader('Access-Control-Allow-Origin').should.equal('delegate.com');
done();
};
// act
cors(delegate)(req, res, next);
});
it('handles error specified via callback', function (done) {
// arrange
var req, res, next, delegate;
delegate = function (req2, cb) {
cb('some error');
};
req = fakeRequest();
res = fakeResponse();
next = function (err) {
// assert
err.should.equal('some error');
done();
};
// act
cors(delegate)(req, res, next);
});
});
});
}());

77
node_modules/cors/test/error-response.js generated vendored Normal file
View File

@ -0,0 +1,77 @@
(function () {
/*global describe, it*/
'use strict';
var should = require('should'),
express = require('express'),
supertest = require('supertest'),
cors = require('../lib');
var app;
/* -------------------------------------------------------------------------- */
app = express();
app.use(cors());
app.post('/five-hundred', function (req, res, next) {
next(new Error('nope'));
});
app.post('/four-oh-one', function (req, res, next) {
next(new Error('401'));
});
app.post('/four-oh-four', function (req, res, next) {
next();
});
app.use(function (err, req, res, next) {
if (err.message === '401') {
res.status(401).send('unauthorized');
} else {
next(err);
}
});
/* -------------------------------------------------------------------------- */
describe('error response', function () {
it('500', function (done) {
supertest(app)
.post('/five-hundred')
.expect(500)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
res.text.should.startWith('Error: nope');
done();
});
});
it('401', function (done) {
supertest(app)
.post('/four-oh-one')
.expect(401)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
res.text.should.eql('unauthorized');
done();
});
});
it('404', function (done) {
supertest(app)
.post('/four-oh-four')
.expect(404)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
done();
});
});
});
}());

98
node_modules/cors/test/example-app.js generated vendored Normal file
View File

@ -0,0 +1,98 @@
(function () {
/*global describe, it*/
'use strict';
var should = require('should'),
express = require('express'),
supertest = require('supertest'),
cors = require('../lib');
var simpleApp,
complexApp;
/* -------------------------------------------------------------------------- */
simpleApp = express();
simpleApp.head('/', cors(), function (req, res) {
res.status(204).send();
});
simpleApp.get('/', cors(), function (req, res) {
res.send('Hello World (Get)');
});
simpleApp.post('/', cors(), function (req, res) {
res.send('Hello World (Post)');
});
/* -------------------------------------------------------------------------- */
complexApp = express();
complexApp.options('/', cors());
complexApp.delete('/', cors(), function (req, res) {
res.send('Hello World (Delete)');
});
/* -------------------------------------------------------------------------- */
describe('example app(s)', function () {
describe('simple methods', function () {
it('GET works', function (done) {
supertest(simpleApp)
.get('/')
.expect(200)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
res.text.should.eql('Hello World (Get)');
done();
});
});
it('HEAD works', function (done) {
supertest(simpleApp)
.head('/')
.expect(204)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
done();
});
});
it('POST works', function (done) {
supertest(simpleApp)
.post('/')
.expect(200)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
res.text.should.eql('Hello World (Post)');
done();
});
});
});
describe('complex methods', function () {
it('OPTIONS works', function (done) {
supertest(complexApp)
.options('/')
.expect(204)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
done();
});
});
it('DELETE works', function (done) {
supertest(complexApp)
.del('/')
.expect(200)
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
res.text.should.eql('Hello World (Delete)');
done();
});
});
});
});
}());

56
node_modules/cors/test/issue-2.js generated vendored Normal file
View File

@ -0,0 +1,56 @@
(function () {
/*global describe, it*/
'use strict';
var should = require('should'),
express = require('express'),
supertest = require('supertest'),
cors = require('../lib');
var app,
corsOptions;
/* -------------------------------------------------------------------------- */
app = express();
corsOptions = {
origin: true,
methods: ['POST'],
credentials: true,
maxAge: 3600
};
app.options('/api/login', cors(corsOptions));
app.post('/api/login', cors(corsOptions), function (req, res) {
res.send('LOGIN');
});
/* -------------------------------------------------------------------------- */
describe('issue #2', function () {
it('OPTIONS works', function (done) {
supertest(app)
.options('/api/login')
.expect(204)
.set('Origin', 'http://example.com')
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('http://example.com');
done();
});
});
it('POST works', function (done) {
supertest(app)
.post('/api/login')
.expect(200)
.set('Origin', 'http://example.com')
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('http://example.com');
res.text.should.eql('LOGIN');
done();
});
});
});
}());

58
node_modules/cors/test/issue-31.js generated vendored Normal file
View File

@ -0,0 +1,58 @@
(function () {
/*global describe, it*/
'use strict';
var should = require('should'),
express = require('express'),
supertest = require('supertest'),
cors = require('../lib');
var app,
mainRouter,
itemsRouter;
/* -------------------------------------------------------------------------- */
itemsRouter = new express.Router();
itemsRouter.get('/', function (req, res) {
res.send('hello world');
});
mainRouter = new express.Router();
mainRouter.use('/items', itemsRouter);
app = express();
app.use(cors());
app.use(mainRouter);
/* -------------------------------------------------------------------------- */
describe('issue #31', function () {
it('OPTIONS works', function (done) {
supertest(app)
.options('/items')
.expect(204)
.set('Origin', 'http://example.com')
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
done();
});
});
it('GET works', function (done) {
supertest(app)
.get('/items')
.expect(200)
.set('Origin', 'http://example.com')
.end(function (err, res) {
should.not.exist(err);
res.headers['access-control-allow-origin'].should.eql('*');
res.text.should.eql('hello world');
done();
});
});
});
}());

3
node_modules/cors/test/mocha.opts generated vendored Normal file
View File

@ -0,0 +1,3 @@
--ui bdd
--reporter spec
--require should

3
node_modules/jwt-simple/.npmignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
.vimrc*
.git*
.travis.yml

11
node_modules/jwt-simple/History.md generated vendored Normal file
View File

@ -0,0 +1,11 @@
## 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]

22
node_modules/jwt-simple/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 Kazuhito Hokamura <k.hokamura@gmail.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.

33
node_modules/jwt-simple/README.md generated vendored Normal file
View File

@ -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')
```

1
node_modules/jwt-simple/index.js generated vendored Normal file
View File

@ -0,0 +1 @@
module.exports = require('./lib/jwt');

183
node_modules/jwt-simple/lib/jwt.js generated vendored Normal file
View File

@ -0,0 +1,183 @@
/*
* 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.2.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');
}
// 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
* @return {String} token
* @api public
*/
jwt.encode = function jwt_encode(payload, key, algorithm) {
// 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 };
// 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 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, '');
}

57
node_modules/jwt-simple/package.json generated vendored Normal file
View File

@ -0,0 +1,57 @@
{
"name": "jwt-simple",
"description": "JWT(JSON Web Token) encode and decode module",
"version": "0.3.1",
"author": {
"name": "Kazuhito Hokamura",
"email": "k.hokamura@gmail.com"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/hokaccha/node-jwt-simple.git"
},
"devDependencies": {
"mocha": "*",
"expect.js": "*"
},
"scripts": {
"test": "mocha test/*.js"
},
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
},
"keywords": [
"jwt",
"encode",
"decode"
],
"main": "./index",
"gitHead": "8367ebca9379efa3116e57702ecc48bdeedd9841",
"bugs": {
"url": "https://github.com/hokaccha/node-jwt-simple/issues"
},
"homepage": "https://github.com/hokaccha/node-jwt-simple#readme",
"_id": "jwt-simple@0.3.1",
"_shasum": "86e0b121d149534423dbd8044a727e3cf1eb939e",
"_from": "jwt-simple@*",
"_npmVersion": "2.11.0",
"_nodeVersion": "0.10.33",
"_npmUser": {
"name": "hokaccha",
"email": "k.hokamura@gmail.com"
},
"maintainers": [
{
"name": "hokaccha",
"email": "k.hokamura@gmail.com"
}
],
"dist": {
"shasum": "86e0b121d149534423dbd8044a727e3cf1eb939e",
"tarball": "http://registry.npmjs.org/jwt-simple/-/jwt-simple-0.3.1.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/jwt-simple/-/jwt-simple-0.3.1.tgz",
"readme": "ERROR: No README data found!"
}

67
node_modules/jwt-simple/test/basic.js generated vendored Normal file
View File

@ -0,0 +1,67 @@
var jwt = require('../index');
var expect = require('expect.js');
var fs = require('fs');
describe('method and property', function() {
it('jwt has version property', function() {
expect(jwt.version).to.be.a('string');
});
it('jwt has encode and decode method', function() {
expect(jwt.encode).to.be.a('function');
expect(jwt.decode).to.be.a('function');
});
});
describe('encode and decode', 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('key is required', function() {
var fn = jwt.encode.bind(null, { foo: 'bar' });
expect(fn).to.throwException();
});
it('decode token', function() {
var obj = { foo: 'bar' };
var key = 'key';
var token = jwt.encode(obj, key);
var obj2 = jwt.decode(token, key);
expect(obj2).to.eql(obj);
expect(jwt.decode.bind(null, token, 'invalid_key')).to.throwException();
});
it('decode no verify', function() {
var obj = { foo: 'bar' };
var key = 'key';
var token = jwt.encode(obj, key);
var fn1 = jwt.decode.bind(null, token, null);
var fn2 = jwt.decode.bind(null, token, null, true);
expect(fn1).to.throwException();
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.throwException();
expect(jwt.decode.bind(null, token, 'invalid_key')).to.throwException();
});
it('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';
var token = jwt.encode(obj, pem, alg);
var obj2 = jwt.decode(token, cert);
expect(obj2).to.eql(obj);
expect(jwt.decode.bind(null, token, 'invalid_key')).to.throwException();
});
});

13
node_modules/jwt-simple/test/test.crt generated vendored Normal file
View File

@ -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-----

15
node_modules/jwt-simple/test/test.pem generated vendored Normal file
View File

@ -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-----

View File

@ -102,7 +102,12 @@ OAuth2Strategy.prototype.authenticate = function(req, options) {
}
// HACK - Make this better
var callbackURL = 'http://' + req.headers['x-forwarded-host'] + '/auth/callback';
var callbackHost = req.headers['x-forwarded-host'];
if (!callbackHost) {
callbackHost = "localhost:9000";
}
var callbackURL = 'http://' + callbackHost + '/auth/callback';
// var callbackURL = options.callbackURL || this._callbackURL;
if (callbackURL) {
var parsed = url.parse(callbackURL);

45
node_modules/request/.eslintrc generated vendored Normal file
View File

@ -0,0 +1,45 @@
{
"env": {
"node": true
},
"rules": {
// 2-space indentation
"indent": [2, 2],
// Disallow semi-colons, unless needed to disambiguate statement
"semi": [2, "never"],
// Require strings to use single quotes
"quotes": [2, "single"],
// Require curly braces for all control statements
"curly": 2,
// Disallow using variables and functions before they've been defined
"no-use-before-define": 2,
// Allow any case for variable naming
"camelcase": 0,
// Disallow unused variables, except as function arguments
"no-unused-vars": [2, {"args":"none"}],
// Allow leading underscores for method names
// REASON: we use underscores to denote private methods
"no-underscore-dangle": 0,
// Allow multi spaces around operators since they are
// used for alignment. This is not consistent in the
// code.
"no-multi-spaces": 0,
// Style rule is: most objects use { beforeColon: false, afterColon: true }, unless aligning which uses:
//
// {
// beforeColon : true,
// afterColon : true
// }
//
// eslint can't handle this, so the check is disabled.
"key-spacing": 0,
// Allow shadowing vars in outer scope (needs discussion)
"no-shadow": 0,
// Use if () { }
// ^ space
"space-after-keywords": [2, "always"],
// Use if () { }
// ^ space
"space-before-blocks": [2, "always"]
}
}

6
node_modules/request/.npmignore generated vendored Normal file
View File

@ -0,0 +1,6 @@
coverage
tests
node_modules
examples
release.sh
disabled.appveyor.yml

15
node_modules/request/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,15 @@
language: node_js
node_js:
- "4.0"
- "io.js"
- "0.12"
- "0.10"
sudo: false
after_script: "npm run test-cov && cat ./coverage/lcov.info | codecov && cat ./coverage/lcov.info | coveralls"
webhooks:
urls: https://webhooks.gitter.im/e/237280ed4796c19cc626
on_success: change # options: [always|never|change] default: always
on_failure: always # options: [always|never|change] default: always
on_start: false # default: false

553
node_modules/request/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,553 @@
## Change Log
### v2.65.0 (2015/10/11)
- [#1833](https://github.com/request/request/pull/1833) Update aws-sign2 to version 0.6.0 🚀 (@greenkeeperio-bot)
- [#1811](https://github.com/request/request/pull/1811) Enable loose cookie parsing in tough-cookie (@Sebmaster)
- [#1830](https://github.com/request/request/pull/1830) Bring back tilde ranges for all dependencies (@simov)
- [#1821](https://github.com/request/request/pull/1821) Implement support for RFC 2617 MD5-sess algorithm. (@BigDSK)
- [#1828](https://github.com/request/request/pull/1828) Updated qs dependency to 5.2.0 (@acroca)
- [#1818](https://github.com/request/request/pull/1818) Extract `readResponseBody` method out of `onRequestResponse` (@pvoisin)
- [#1819](https://github.com/request/request/pull/1819) Run stringify once (@mgenereu)
- [#1814](https://github.com/request/request/pull/1814) Updated har-validator to version 2.0.2 (@greenkeeperio-bot)
- [#1807](https://github.com/request/request/pull/1807) Updated tough-cookie to version 2.1.0 (@greenkeeperio-bot)
- [#1800](https://github.com/request/request/pull/1800) Add caret ranges for devDependencies, except eslint (@simov)
- [#1799](https://github.com/request/request/pull/1799) Updated karma-browserify to version 4.4.0 (@greenkeeperio-bot)
- [#1797](https://github.com/request/request/pull/1797) Updated tape to version 4.2.0 (@greenkeeperio-bot)
- [#1788](https://github.com/request/request/pull/1788) Pinned all dependencies (@greenkeeperio-bot)
### v2.64.0 (2015/09/25)
- [#1787](https://github.com/request/request/pull/1787) npm ignore examples, release.sh and disabled.appveyor.yml (@thisconnect)
- [#1775](https://github.com/request/request/pull/1775) Fix typo in README.md (@djchie)
- [#1776](https://github.com/request/request/pull/1776) Changed word 'conjuction' to read 'conjunction' in README.md (@ryanwholey)
- [#1785](https://github.com/request/request/pull/1785) Revert: Set default application/json content-type when using json option #1772 (@simov)
### v2.63.0 (2015/09/21)
- [#1772](https://github.com/request/request/pull/1772) Set default application/json content-type when using json option (@jzaefferer)
### v2.62.0 (2015/09/15)
- [#1768](https://github.com/request/request/pull/1768) Add node 4.0 to the list of build targets (@simov)
- [#1767](https://github.com/request/request/pull/1767) Query strings now cooperate with unix sockets (@JoshWillik)
- [#1750](https://github.com/request/request/pull/1750) Revert doc about installation of tough-cookie added in #884 (@LoicMahieu)
- [#1746](https://github.com/request/request/pull/1746) Missed comma in Readme (@vladimirich)
- [#1743](https://github.com/request/request/pull/1743) Fix options not being initialized in defaults method (@simov)
### v2.61.0 (2015/08/19)
- [#1721](https://github.com/request/request/pull/1721) Minor fix in README.md (@arbaaz)
- [#1733](https://github.com/request/request/pull/1733) Avoid useless Buffer transformation (@michelsalib)
- [#1726](https://github.com/request/request/pull/1726) Update README.md (@paulomcnally)
- [#1715](https://github.com/request/request/pull/1715) Fix forever option in node > 0.10 #1709 (@calibr)
- [#1716](https://github.com/request/request/pull/1716) Do not create Buffer from Object in setContentLength(iojs v3.0 issue) (@calibr)
- [#1711](https://github.com/request/request/pull/1711) Add ability to detect connect timeouts (@kevinburke)
- [#1712](https://github.com/request/request/pull/1712) Set certificate expiration to August 2, 2018 (@kevinburke)
- [#1700](https://github.com/request/request/pull/1700) debug() when JSON.parse() on a response body fails (@phillipj)
### v2.60.0 (2015/07/21)
- [#1687](https://github.com/request/request/pull/1687) Fix caseless bug - content-type not being set for multipart/form-data (@simov, @garymathews)
### v2.59.0 (2015/07/20)
- [#1671](https://github.com/request/request/pull/1671) Add tests and docs for using the agent, agentClass, agentOptions and forever options.
Forever option defaults to using http(s).Agent in node 0.12+ (@simov)
- [#1679](https://github.com/request/request/pull/1679) Fix - do not remove OAuth param when using OAuth realm (@simov, @jhalickman)
- [#1668](https://github.com/request/request/pull/1668) updated dependencies (@deamme)
- [#1656](https://github.com/request/request/pull/1656) Fix form method (@simov)
- [#1651](https://github.com/request/request/pull/1651) Preserve HEAD method when using followAllRedirects (@simov)
- [#1652](https://github.com/request/request/pull/1652) Update `encoding` option documentation in README.md (@daniel347x)
- [#1650](https://github.com/request/request/pull/1650) Allow content-type overriding when using the `form` option (@simov)
- [#1646](https://github.com/request/request/pull/1646) Clarify the nature of setting `ca` in `agentOptions` (@jeffcharles)
### v2.58.0 (2015/06/16)
- [#1638](https://github.com/request/request/pull/1638) Use the `extend` module to deep extend in the defaults method (@simov)
- [#1631](https://github.com/request/request/pull/1631) Move tunnel logic into separate module (@simov)
- [#1634](https://github.com/request/request/pull/1634) Fix OAuth query transport_method (@simov)
- [#1603](https://github.com/request/request/pull/1603) Add codecov (@simov)
### v2.57.0 (2015/05/31)
- [#1615](https://github.com/request/request/pull/1615) Replace '.client' with '.socket' as the former was deprecated in 2.2.0. (@ChALkeR)
### v2.56.0 (2015/05/28)
- [#1610](https://github.com/request/request/pull/1610) Bump module dependencies (@simov)
- [#1600](https://github.com/request/request/pull/1600) Extract the querystring logic into separate module (@simov)
- [#1607](https://github.com/request/request/pull/1607) Re-generate certificates (@simov)
- [#1599](https://github.com/request/request/pull/1599) Move getProxyFromURI logic below the check for Invaild URI (#1595) (@simov)
- [#1598](https://github.com/request/request/pull/1598) Fix the way http verbs are defined in order to please intellisense IDEs (@simov, @flannelJesus)
- [#1591](https://github.com/request/request/pull/1591) A few minor fixes: (@simov)
- [#1584](https://github.com/request/request/pull/1584) Refactor test-default tests (according to comments in #1430) (@simov)
- [#1585](https://github.com/request/request/pull/1585) Fixing documentation regarding TLS options (#1583) (@mainakae)
- [#1574](https://github.com/request/request/pull/1574) Refresh the oauth_nonce on redirect (#1573) (@simov)
- [#1570](https://github.com/request/request/pull/1570) Discovered tests that weren't properly running (@seanstrom)
- [#1569](https://github.com/request/request/pull/1569) Fix pause before response arrives (@kevinoid)
- [#1558](https://github.com/request/request/pull/1558) Emit error instead of throw (@simov)
- [#1568](https://github.com/request/request/pull/1568) Fix stall when piping gzipped response (@kevinoid)
- [#1560](https://github.com/request/request/pull/1560) Update combined-stream (@apechimp)
- [#1543](https://github.com/request/request/pull/1543) Initial support for oauth_body_hash on json payloads (@simov, @aesopwolf)
- [#1541](https://github.com/request/request/pull/1541) Fix coveralls (@simov)
- [#1540](https://github.com/request/request/pull/1540) Fix recursive defaults for convenience methods (@simov)
- [#1536](https://github.com/request/request/pull/1536) More eslint style rules (@froatsnook)
- [#1533](https://github.com/request/request/pull/1533) Adding dependency status bar to README.md (@YasharF)
- [#1539](https://github.com/request/request/pull/1539) ensure the latest version of har-validator is included (@ahmadnassri)
- [#1516](https://github.com/request/request/pull/1516) forever+pool test (@devTristan)
### v2.55.0 (2015/04/05)
- [#1520](https://github.com/request/request/pull/1520) Refactor defaults (@simov)
- [#1525](https://github.com/request/request/pull/1525) Delete request headers with undefined value. (@froatsnook)
- [#1521](https://github.com/request/request/pull/1521) Add promise tests (@simov)
- [#1518](https://github.com/request/request/pull/1518) Fix defaults (@simov)
- [#1515](https://github.com/request/request/pull/1515) Allow static invoking of convenience methods (@simov)
- [#1505](https://github.com/request/request/pull/1505) Fix multipart boundary extraction regexp (@simov)
- [#1510](https://github.com/request/request/pull/1510) Fix basic auth form data (@simov)
### v2.54.0 (2015/03/24)
- [#1501](https://github.com/request/request/pull/1501) HTTP Archive 1.2 support (@ahmadnassri)
- [#1486](https://github.com/request/request/pull/1486) Add a test for the forever agent (@akshayp)
- [#1500](https://github.com/request/request/pull/1500) Adding handling for no auth method and null bearer (@philberg)
- [#1498](https://github.com/request/request/pull/1498) Add table of contents in readme (@simov)
- [#1477](https://github.com/request/request/pull/1477) Add support for qs options via qsOptions key (@simov)
- [#1496](https://github.com/request/request/pull/1496) Parameters encoded to base 64 should be decoded as UTF-8, not ASCII. (@albanm)
- [#1494](https://github.com/request/request/pull/1494) Update eslint (@froatsnook)
- [#1474](https://github.com/request/request/pull/1474) Require Colon in Basic Auth (@erykwalder)
- [#1481](https://github.com/request/request/pull/1481) Fix baseUrl and redirections. (@burningtree)
- [#1469](https://github.com/request/request/pull/1469) Feature/base url (@froatsnook)
- [#1459](https://github.com/request/request/pull/1459) Add option to time request/response cycle (including rollup of redirects) (@aaron-em)
- [#1468](https://github.com/request/request/pull/1468) Re-enable io.js/node 0.12 build (@simov, @mikeal, @BBB)
- [#1442](https://github.com/request/request/pull/1442) Fixed the issue with strictSSL tests on 0.12 & io.js by explicitly setting a cipher that matches the cert. (@BBB, @nicolasmccurdy, @demohi, @simov, @0x4139)
- [#1460](https://github.com/request/request/pull/1460) localAddress or proxy config is lost when redirecting (@simov, @0x4139)
- [#1453](https://github.com/request/request/pull/1453) Test on Node.js 0.12 and io.js with allowed failures (@nicolasmccurdy, @demohi)
- [#1426](https://github.com/request/request/pull/1426) Fixing tests to pass on io.js and node 0.12 (only test-https.js stiff failing) (@mikeal)
- [#1446](https://github.com/request/request/pull/1446) Missing HTTP referer header with redirects Fixes #1038 (@simov, @guimonz)
- [#1428](https://github.com/request/request/pull/1428) Deprecate Node v0.8.x (@nylen)
- [#1436](https://github.com/request/request/pull/1436) Add ability to set a requester without setting default options (@tikotzky)
- [#1435](https://github.com/request/request/pull/1435) dry up verb methods (@sethpollack)
- [#1423](https://github.com/request/request/pull/1423) Allow fully qualified multipart content-type header (@simov)
- [#1430](https://github.com/request/request/pull/1430) Fix recursive requester (@tikotzky)
- [#1429](https://github.com/request/request/pull/1429) Throw error when making HEAD request with a body (@tikotzky)
- [#1419](https://github.com/request/request/pull/1419) Add note that the project is broken in 0.12.x (@nylen)
- [#1413](https://github.com/request/request/pull/1413) Fix basic auth (@simov)
- [#1397](https://github.com/request/request/pull/1397) Improve pipe-from-file tests (@nylen)
### v2.53.0 (2015/02/02)
- [#1396](https://github.com/request/request/pull/1396) Do not rfc3986 escape JSON bodies (@nylen, @simov)
- [#1392](https://github.com/request/request/pull/1392) Improve `timeout` option description (@watson)
### v2.52.0 (2015/02/02)
- [#1383](https://github.com/request/request/pull/1383) Add missing HTTPS options that were not being passed to tunnel (@brichard19) (@nylen)
- [#1388](https://github.com/request/request/pull/1388) Upgrade mime-types package version (@roderickhsiao)
- [#1389](https://github.com/request/request/pull/1389) Revise Setup Tunnel Function (@seanstrom)
- [#1374](https://github.com/request/request/pull/1374) Allow explicitly disabling tunneling for proxied https destinations (@nylen)
- [#1376](https://github.com/request/request/pull/1376) Use karma-browserify for tests. Add browser test coverage reporter. (@eiriksm)
- [#1366](https://github.com/request/request/pull/1366) Refactor OAuth into separate module (@simov)
- [#1373](https://github.com/request/request/pull/1373) Rewrite tunnel test to be pure Node.js (@nylen)
- [#1371](https://github.com/request/request/pull/1371) Upgrade test reporter (@nylen)
- [#1360](https://github.com/request/request/pull/1360) Refactor basic, bearer, digest auth logic into separate class (@simov)
- [#1354](https://github.com/request/request/pull/1354) Remove circular dependency from debugging code (@nylen)
- [#1351](https://github.com/request/request/pull/1351) Move digest auth into private prototype method (@simov)
- [#1352](https://github.com/request/request/pull/1352) Update hawk dependency to ~2.3.0 (@mridgway)
- [#1353](https://github.com/request/request/pull/1353) Correct travis-ci badge (@dogancelik)
- [#1349](https://github.com/request/request/pull/1349) Make sure we return on errored browser requests. (@eiriksm)
- [#1346](https://github.com/request/request/pull/1346) getProxyFromURI Extraction Refactor (@seanstrom)
- [#1337](https://github.com/request/request/pull/1337) Standardize test ports on 6767 (@nylen)
- [#1341](https://github.com/request/request/pull/1341) Emit FormData error events as Request error events (@nylen, @rwky)
- [#1343](https://github.com/request/request/pull/1343) Clean up readme badges, and add Travis and Coveralls badges (@nylen)
- [#1345](https://github.com/request/request/pull/1345) Update README.md (@Aaron-Hartwig)
- [#1338](https://github.com/request/request/pull/1338) Always wait for server.close() callback in tests (@nylen)
- [#1342](https://github.com/request/request/pull/1342) Add mock https server and redo start of browser tests for this purpose. (@eiriksm)
- [#1339](https://github.com/request/request/pull/1339) Improve auth docs (@nylen)
- [#1335](https://github.com/request/request/pull/1335) Add support for OAuth plaintext signature method (@simov)
- [#1332](https://github.com/request/request/pull/1332) Add clean script to remove test-browser.js after the tests run (@seanstrom)
- [#1327](https://github.com/request/request/pull/1327) Fix errors generating coverage reports. (@nylen)
- [#1330](https://github.com/request/request/pull/1330) Return empty buffer upon empty response body and encoding is set to null (@seanstrom)
- [#1326](https://github.com/request/request/pull/1326) Use faster container-based infrastructure on Travis (@nylen)
- [#1315](https://github.com/request/request/pull/1315) Implement rfc3986 option (@simov, @nylen, @apoco, @DullReferenceException, @mmalecki, @oliamb, @cliffcrosland, @LewisJEllis, @eiriksm, @poislagarde)
- [#1314](https://github.com/request/request/pull/1314) Detect urlencoded form data header via regex (@simov)
- [#1317](https://github.com/request/request/pull/1317) Improve OAuth1.0 server side flow example (@simov)
### v2.51.0 (2014/12/10)
- [#1310](https://github.com/request/request/pull/1310) Revert changes introduced in https://github.com/request/request/pull/1282 (@simov)
### v2.50.0 (2014/12/09)
- [#1308](https://github.com/request/request/pull/1308) Add browser test to keep track of browserify compability. (@eiriksm)
- [#1299](https://github.com/request/request/pull/1299) Add optional support for jsonReviver (@poislagarde)
- [#1277](https://github.com/request/request/pull/1277) Add Coveralls configuration (@simov)
- [#1307](https://github.com/request/request/pull/1307) Upgrade form-data, add back browserify compability. Fixes #455. (@eiriksm)
- [#1305](https://github.com/request/request/pull/1305) Fix typo in README.md (@LewisJEllis)
- [#1288](https://github.com/request/request/pull/1288) Update README.md to explain custom file use case (@cliffcrosland)
### v2.49.0 (2014/11/28)
- [#1295](https://github.com/request/request/pull/1295) fix(proxy): no-proxy false positive (@oliamb)
- [#1292](https://github.com/request/request/pull/1292) Upgrade `caseless` to 0.8.1 (@mmalecki)
- [#1276](https://github.com/request/request/pull/1276) Set transfer encoding for multipart/related to chunked by default (@simov)
- [#1275](https://github.com/request/request/pull/1275) Fix multipart content-type headers detection (@simov)
- [#1269](https://github.com/request/request/pull/1269) adds streams example for review (@tbuchok)
- [#1238](https://github.com/request/request/pull/1238) Add examples README.md (@simov)
### v2.48.0 (2014/11/12)
- [#1263](https://github.com/request/request/pull/1263) Fixed a syntax error / typo in README.md (@xna2)
- [#1253](https://github.com/request/request/pull/1253) Add multipart chunked flag (@simov, @nylen)
- [#1251](https://github.com/request/request/pull/1251) Clarify that defaults() does not modify global defaults (@nylen)
- [#1250](https://github.com/request/request/pull/1250) Improve documentation for pool and maxSockets options (@nylen)
- [#1237](https://github.com/request/request/pull/1237) Documenting error handling when using streams (@vmattos)
- [#1244](https://github.com/request/request/pull/1244) Finalize changelog command (@nylen)
- [#1241](https://github.com/request/request/pull/1241) Fix typo (@alexanderGugel)
- [#1223](https://github.com/request/request/pull/1223) Show latest version number instead of "upcoming" in changelog (@nylen)
- [#1236](https://github.com/request/request/pull/1236) Document how to use custom CA in README (#1229) (@hypesystem)
- [#1228](https://github.com/request/request/pull/1228) Support for oauth with RSA-SHA1 signing (@nylen)
- [#1216](https://github.com/request/request/pull/1216) Made json and multipart options coexist (@nylen, @simov)
- [#1225](https://github.com/request/request/pull/1225) Allow header white/exclusive lists in any case. (@RReverser)
### v2.47.0 (2014/10/26)
- [#1222](https://github.com/request/request/pull/1222) Move from mikeal/request to request/request (@nylen)
- [#1220](https://github.com/request/request/pull/1220) update qs dependency to 2.3.1 (@FredKSchott)
- [#1212](https://github.com/request/request/pull/1212) Improve tests/test-timeout.js (@nylen)
- [#1219](https://github.com/request/request/pull/1219) remove old globalAgent workaround for node 0.4 (@request)
- [#1214](https://github.com/request/request/pull/1214) Remove cruft left over from optional dependencies (@nylen)
- [#1215](https://github.com/request/request/pull/1215) Add proxyHeaderExclusiveList option for proxy-only headers. (@RReverser)
- [#1211](https://github.com/request/request/pull/1211) Allow 'Host' header instead of 'host' and remember case across redirects (@nylen)
- [#1208](https://github.com/request/request/pull/1208) Improve release script (@nylen)
- [#1213](https://github.com/request/request/pull/1213) Support for custom cookie store (@nylen, @mitsuru)
- [#1197](https://github.com/request/request/pull/1197) Clean up some code around setting the agent (@FredKSchott)
- [#1209](https://github.com/request/request/pull/1209) Improve multipart form append test (@simov)
- [#1207](https://github.com/request/request/pull/1207) Update changelog (@nylen)
- [#1185](https://github.com/request/request/pull/1185) Stream multipart/related bodies (@simov)
### v2.46.0 (2014/10/23)
- [#1198](https://github.com/request/request/pull/1198) doc for TLS/SSL protocol options (@shawnzhu)
- [#1200](https://github.com/request/request/pull/1200) Add a Gitter chat badge to README.md (@gitter-badger)
- [#1196](https://github.com/request/request/pull/1196) Upgrade taper test reporter to v0.3.0 (@nylen)
- [#1199](https://github.com/request/request/pull/1199) Fix lint error: undeclared var i (@nylen)
- [#1191](https://github.com/request/request/pull/1191) Move self.proxy decision logic out of init and into a helper (@FredKSchott)
- [#1190](https://github.com/request/request/pull/1190) Move _buildRequest() logic back into init (@FredKSchott)
- [#1186](https://github.com/request/request/pull/1186) Support Smarter Unix URL Scheme (@FredKSchott)
- [#1178](https://github.com/request/request/pull/1178) update form documentation for new usage (@FredKSchott)
- [#1180](https://github.com/request/request/pull/1180) Enable no-mixed-requires linting rule (@nylen)
- [#1184](https://github.com/request/request/pull/1184) Don't forward authorization header across redirects to different hosts (@nylen)
- [#1183](https://github.com/request/request/pull/1183) Correct README about pre and postamble CRLF using multipart and not mult... (@netpoetica)
- [#1179](https://github.com/request/request/pull/1179) Lint tests directory (@nylen)
- [#1169](https://github.com/request/request/pull/1169) add metadata for form-data file field (@dotcypress)
- [#1173](https://github.com/request/request/pull/1173) remove optional dependencies (@seanstrom)
- [#1165](https://github.com/request/request/pull/1165) Cleanup event listeners and remove function creation from init (@FredKSchott)
- [#1174](https://github.com/request/request/pull/1174) update the request.cookie docs to have a valid cookie example (@seanstrom)
- [#1168](https://github.com/request/request/pull/1168) create a detach helper and use detach helper in replace of nextTick (@seanstrom)
- [#1171](https://github.com/request/request/pull/1171) in post can send form data and use callback (@MiroRadenovic)
- [#1159](https://github.com/request/request/pull/1159) accept charset for x-www-form-urlencoded content-type (@seanstrom)
- [#1157](https://github.com/request/request/pull/1157) Update README.md: body with json=true (@Rob--W)
- [#1164](https://github.com/request/request/pull/1164) Disable tests/test-timeout.js on Travis (@nylen)
- [#1153](https://github.com/request/request/pull/1153) Document how to run a single test (@nylen)
- [#1144](https://github.com/request/request/pull/1144) adds documentation for the "response" event within the streaming section (@tbuchok)
- [#1162](https://github.com/request/request/pull/1162) Update eslintrc file to no longer allow past errors (@FredKSchott)
- [#1155](https://github.com/request/request/pull/1155) Support/use self everywhere (@seanstrom)
- [#1161](https://github.com/request/request/pull/1161) fix no-use-before-define lint warnings (@emkay)
- [#1156](https://github.com/request/request/pull/1156) adding curly brackets to get rid of lint errors (@emkay)
- [#1151](https://github.com/request/request/pull/1151) Fix localAddress test on OS X (@nylen)
- [#1145](https://github.com/request/request/pull/1145) documentation: fix outdated reference to setCookieSync old name in README (@FredKSchott)
- [#1131](https://github.com/request/request/pull/1131) Update pool documentation (@FredKSchott)
- [#1143](https://github.com/request/request/pull/1143) Rewrite all tests to use tape (@nylen)
- [#1137](https://github.com/request/request/pull/1137) Add ability to specifiy querystring lib in options. (@jgrund)
- [#1138](https://github.com/request/request/pull/1138) allow hostname and port in place of host on uri (@cappslock)
- [#1134](https://github.com/request/request/pull/1134) Fix multiple redirects and `self.followRedirect` (@blakeembrey)
- [#1130](https://github.com/request/request/pull/1130) documentation fix: add note about npm test for contributing (@FredKSchott)
- [#1120](https://github.com/request/request/pull/1120) Support/refactor request setup tunnel (@seanstrom)
- [#1129](https://github.com/request/request/pull/1129) linting fix: convert double quote strings to use single quotes (@FredKSchott)
- [#1124](https://github.com/request/request/pull/1124) linting fix: remove unneccesary semi-colons (@FredKSchott)
### v2.45.0 (2014/10/06)
- [#1128](https://github.com/request/request/pull/1128) Add test for setCookie regression (@nylen)
- [#1127](https://github.com/request/request/pull/1127) added tests around using objects as values in a query string (@bcoe)
- [#1103](https://github.com/request/request/pull/1103) Support/refactor request constructor (@nylen, @seanstrom)
- [#1119](https://github.com/request/request/pull/1119) add basic linting to request library (@FredKSchott)
- [#1121](https://github.com/request/request/pull/1121) Revert "Explicitly use sync versions of cookie functions" (@nylen)
- [#1118](https://github.com/request/request/pull/1118) linting fix: Restructure bad empty if statement (@FredKSchott)
- [#1117](https://github.com/request/request/pull/1117) Fix a bad check for valid URIs (@FredKSchott)
- [#1113](https://github.com/request/request/pull/1113) linting fix: space out operators (@FredKSchott)
- [#1116](https://github.com/request/request/pull/1116) Fix typo in `noProxyHost` definition (@FredKSchott)
- [#1114](https://github.com/request/request/pull/1114) linting fix: Added a `new` operator that was missing when creating and throwing a new error (@FredKSchott)
- [#1096](https://github.com/request/request/pull/1096) No_proxy support (@samcday)
- [#1107](https://github.com/request/request/pull/1107) linting-fix: remove unused variables (@FredKSchott)
- [#1112](https://github.com/request/request/pull/1112) linting fix: Make return values consistent and more straitforward (@FredKSchott)
- [#1111](https://github.com/request/request/pull/1111) linting fix: authPieces was getting redeclared (@FredKSchott)
- [#1105](https://github.com/request/request/pull/1105) Use strict mode in request (@FredKSchott)
- [#1110](https://github.com/request/request/pull/1110) linting fix: replace lazy '==' with more strict '===' (@FredKSchott)
- [#1109](https://github.com/request/request/pull/1109) linting fix: remove function call from if-else conditional statement (@FredKSchott)
- [#1102](https://github.com/request/request/pull/1102) Fix to allow setting a `requester` on recursive calls to `request.defaults` (@tikotzky)
- [#1095](https://github.com/request/request/pull/1095) Tweaking engines in package.json (@pdehaan)
- [#1082](https://github.com/request/request/pull/1082) Forward the socket event from the httpModule request (@seanstrom)
- [#972](https://github.com/request/request/pull/972) Clarify gzip handling in the README (@kevinoid)
- [#1089](https://github.com/request/request/pull/1089) Mention that encoding defaults to utf8, not Buffer (@stuartpb)
- [#1088](https://github.com/request/request/pull/1088) Fix cookie example in README.md and make it more clear (@pipi32167)
- [#1027](https://github.com/request/request/pull/1027) Add support for multipart form data in request options. (@crocket)
- [#1076](https://github.com/request/request/pull/1076) use Request.abort() to abort the request when the request has timed-out (@seanstrom)
- [#1068](https://github.com/request/request/pull/1068) add optional postamble required by .NET multipart requests (@netpoetica)
### v2.43.0 (2014/09/18)
- [#1057](https://github.com/request/request/pull/1057) Defaults should not overwrite defined options (@davidwood)
- [#1046](https://github.com/request/request/pull/1046) Propagate datastream errors, useful in case gzip fails. (@ZJONSSON, @Janpot)
- [#1063](https://github.com/request/request/pull/1063) copy the input headers object #1060 (@finnp)
- [#1031](https://github.com/request/request/pull/1031) Explicitly use sync versions of cookie functions (@ZJONSSON)
- [#1056](https://github.com/request/request/pull/1056) Fix redirects when passing url.parse(x) as URL to convenience method (@nylen)
### v2.42.0 (2014/09/04)
- [#1053](https://github.com/request/request/pull/1053) Fix #1051 Parse auth properly when using non-tunneling proxy (@isaacs)
### v2.41.0 (2014/09/04)
- [#1050](https://github.com/request/request/pull/1050) Pass whitelisted headers to tunneling proxy. Organize all tunneling logic. (@isaacs, @Feldhacker)
- [#1035](https://github.com/request/request/pull/1035) souped up nodei.co badge (@rvagg)
- [#1048](https://github.com/request/request/pull/1048) Aws is now possible over a proxy (@steven-aerts)
- [#1039](https://github.com/request/request/pull/1039) extract out helper functions to a helper file (@seanstrom)
- [#1021](https://github.com/request/request/pull/1021) Support/refactor indexjs (@seanstrom)
- [#1033](https://github.com/request/request/pull/1033) Improve and document debug options (@nylen)
- [#1034](https://github.com/request/request/pull/1034) Fix readme headings (@nylen)
- [#1030](https://github.com/request/request/pull/1030) Allow recursive request.defaults (@tikotzky)
- [#1029](https://github.com/request/request/pull/1029) Fix a couple of typos (@nylen)
- [#675](https://github.com/request/request/pull/675) Checking for SSL fault on connection before reading SSL properties (@VRMink)
- [#989](https://github.com/request/request/pull/989) Added allowRedirect function. Should return true if redirect is allowed or false otherwise (@doronin)
- [#1025](https://github.com/request/request/pull/1025) [fixes #1023] Set self._ended to true once response has ended (@mridgway)
- [#1020](https://github.com/request/request/pull/1020) Add back removed debug metadata (@FredKSchott)
- [#1008](https://github.com/request/request/pull/1008) Moving to module instead of cutomer buffer concatenation. (@mikeal)
- [#770](https://github.com/request/request/pull/770) Added dependency badge for README file; (@timgluz, @mafintosh, @lalitkapoor, @stash, @bobyrizov)
- [#1016](https://github.com/request/request/pull/1016) toJSON no longer results in an infinite loop, returns simple objects (@FredKSchott)
- [#1018](https://github.com/request/request/pull/1018) Remove pre-0.4.4 HTTPS fix (@mmalecki)
- [#1006](https://github.com/request/request/pull/1006) Migrate to caseless, fixes #1001 (@mikeal)
- [#995](https://github.com/request/request/pull/995) Fix parsing array of objects (@sjonnet19)
- [#999](https://github.com/request/request/pull/999) Fix fallback for browserify for optional modules. (@eiriksm)
- [#996](https://github.com/request/request/pull/996) Wrong oauth signature when multiple same param keys exist [updated] (@bengl, @hyjin)
### v2.40.0 (2014/08/06)
- [#992](https://github.com/request/request/pull/992) Fix security vulnerability. Update qs (@poeticninja)
- [#988](https://github.com/request/request/pull/988) “--” -> “—” (@upisfree)
- [#987](https://github.com/request/request/pull/987) Show optional modules as being loaded by the module that reqeusted them (@iarna)
### v2.39.0 (2014/07/24)
- [#976](https://github.com/request/request/pull/976) Update README.md (@pvoznenko)
### v2.38.0 (2014/07/22)
- [#952](https://github.com/request/request/pull/952) Adding support to client certificate with proxy use case (@ofirshaked)
- [#884](https://github.com/request/request/pull/884) Documented tough-cookie installation. (@wbyoung)
- [#935](https://github.com/request/request/pull/935) Correct repository url (@fritx)
- [#963](https://github.com/request/request/pull/963) Update changelog (@nylen)
- [#960](https://github.com/request/request/pull/960) Support gzip with encoding on node pre-v0.9.4 (@kevinoid)
- [#953](https://github.com/request/request/pull/953) Add async Content-Length computation when using form-data (@LoicMahieu)
- [#844](https://github.com/request/request/pull/844) Add support for HTTP[S]_PROXY environment variables. Fixes #595. (@jvmccarthy)
- [#946](https://github.com/request/request/pull/946) defaults: merge headers (@aj0strow)
### v2.37.0 (2014/07/07)
- [#957](https://github.com/request/request/pull/957) Silence EventEmitter memory leak warning #311 (@watson)
- [#955](https://github.com/request/request/pull/955) check for content-length header before setting it in nextTick (@camilleanne)
- [#951](https://github.com/request/request/pull/951) Add support for gzip content decoding (@kevinoid)
- [#949](https://github.com/request/request/pull/949) Manually enter querystring in form option (@charlespwd)
- [#944](https://github.com/request/request/pull/944) Make request work with browserify (@eiriksm)
- [#943](https://github.com/request/request/pull/943) New mime module (@eiriksm)
- [#927](https://github.com/request/request/pull/927) Bump version of hawk dep. (@samccone)
- [#907](https://github.com/request/request/pull/907) append secureOptions to poolKey (@medovob)
### v2.35.0 (2014/05/17)
- [#901](https://github.com/request/request/pull/901) Fixes #555 (@pigulla)
- [#897](https://github.com/request/request/pull/897) merge with default options (@vohof)
- [#891](https://github.com/request/request/pull/891) fixes 857 - options object is mutated by calling request (@lalitkapoor)
- [#869](https://github.com/request/request/pull/869) Pipefilter test (@tgohn)
- [#866](https://github.com/request/request/pull/866) Fix typo (@dandv)
- [#861](https://github.com/request/request/pull/861) Add support for RFC 6750 Bearer Tokens (@phedny)
- [#809](https://github.com/request/request/pull/809) upgrade tunnel-proxy to 0.4.0 (@ksato9700)
- [#850](https://github.com/request/request/pull/850) Fix word consistency in readme (@0xNobody)
- [#810](https://github.com/request/request/pull/810) add some exposition to mpu example in README.md (@mikermcneil)
- [#840](https://github.com/request/request/pull/840) improve error reporting for invalid protocols (@FND)
- [#821](https://github.com/request/request/pull/821) added secureOptions back (@nw)
- [#815](https://github.com/request/request/pull/815) Create changelog based on pull requests (@lalitkapoor)
### v2.34.0 (2014/02/18)
- [#516](https://github.com/request/request/pull/516) UNIX Socket URL Support (@lyuzashi)
- [#801](https://github.com/request/request/pull/801) 794 ignore cookie parsing and domain errors (@lalitkapoor)
- [#802](https://github.com/request/request/pull/802) Added the Apache license to the package.json. (@keskival)
- [#793](https://github.com/request/request/pull/793) Adds content-length calculation when submitting forms using form-data li... (@Juul)
- [#785](https://github.com/request/request/pull/785) Provide ability to override content-type when `json` option used (@vvo)
- [#781](https://github.com/request/request/pull/781) simpler isReadStream function (@joaojeronimo)
### v2.32.0 (2014/01/16)
- [#767](https://github.com/request/request/pull/767) Use tough-cookie CookieJar sync API (@stash)
- [#764](https://github.com/request/request/pull/764) Case-insensitive authentication scheme (@bobyrizov)
- [#763](https://github.com/request/request/pull/763) Upgrade tough-cookie to 0.10.0 (@stash)
- [#744](https://github.com/request/request/pull/744) Use Cookie.parse (@lalitkapoor)
- [#757](https://github.com/request/request/pull/757) require aws-sign2 (@mafintosh)
### v2.31.0 (2014/01/08)
- [#645](https://github.com/request/request/pull/645) update twitter api url to v1.1 (@mick)
- [#746](https://github.com/request/request/pull/746) README: Markdown code highlight (@weakish)
- [#745](https://github.com/request/request/pull/745) updating setCookie example to make it clear that the callback is required (@emkay)
- [#742](https://github.com/request/request/pull/742) Add note about JSON output body type (@iansltx)
- [#741](https://github.com/request/request/pull/741) README example is using old cookie jar api (@emkay)
- [#736](https://github.com/request/request/pull/736) Fix callback arguments documentation (@mmalecki)
### v2.30.0 (2013/12/13)
- [#732](https://github.com/request/request/pull/732) JSHINT: Creating global 'for' variable. Should be 'for (var ...'. (@Fritz-Lium)
- [#730](https://github.com/request/request/pull/730) better HTTP DIGEST support (@dai-shi)
- [#728](https://github.com/request/request/pull/728) Fix TypeError when calling request.cookie (@scarletmeow)
### v2.29.0 (2013/12/06)
- [#727](https://github.com/request/request/pull/727) fix requester bug (@jchris)
### v2.28.0 (2013/12/04)
- [#724](https://github.com/request/request/pull/724) README.md: add custom HTTP Headers example. (@tcort)
- [#719](https://github.com/request/request/pull/719) Made a comment gender neutral. (@unsetbit)
- [#715](https://github.com/request/request/pull/715) Request.multipart no longer crashes when header 'Content-type' present (@pastaclub)
- [#710](https://github.com/request/request/pull/710) Fixing listing in callback part of docs. (@lukasz-zak)
- [#696](https://github.com/request/request/pull/696) Edited README.md for formatting and clarity of phrasing (@Zearin)
- [#694](https://github.com/request/request/pull/694) Typo in README (@VRMink)
- [#690](https://github.com/request/request/pull/690) Handle blank password in basic auth. (@diversario)
- [#682](https://github.com/request/request/pull/682) Optional dependencies (@Turbo87)
- [#683](https://github.com/request/request/pull/683) Travis CI support (@Turbo87)
- [#674](https://github.com/request/request/pull/674) change cookie module,to tough-cookie.please check it . (@sxyizhiren)
- [#666](https://github.com/request/request/pull/666) make `ciphers` and `secureProtocol` to work in https request (@richarddong)
- [#656](https://github.com/request/request/pull/656) Test case for #304. (@diversario)
- [#662](https://github.com/request/request/pull/662) option.tunnel to explicitly disable tunneling (@seanmonstar)
- [#659](https://github.com/request/request/pull/659) fix failure when running with NODE_DEBUG=request, and a test for that (@jrgm)
- [#630](https://github.com/request/request/pull/630) Send random cnonce for HTTP Digest requests (@wprl)
### v2.27.0 (2013/08/15)
- [#619](https://github.com/request/request/pull/619) decouple things a bit (@joaojeronimo)
### v2.26.0 (2013/08/07)
- [#613](https://github.com/request/request/pull/613) Fixes #583, moved initialization of self.uri.pathname (@lexander)
- [#605](https://github.com/request/request/pull/605) Only include ":" + pass in Basic Auth if it's defined (fixes #602) (@bendrucker)
### v2.24.0 (2013/07/23)
- [#596](https://github.com/request/request/pull/596) Global agent is being used when pool is specified (@Cauldrath)
- [#594](https://github.com/request/request/pull/594) Emit complete event when there is no callback (@RomainLK)
- [#601](https://github.com/request/request/pull/601) Fixed a small typo (@michalstanko)
### v2.23.0 (2013/07/23)
- [#589](https://github.com/request/request/pull/589) Prevent setting headers after they are sent (@geek)
- [#587](https://github.com/request/request/pull/587) Global cookie jar disabled by default (@threepointone)
### v2.22.0 (2013/07/05)
- [#544](https://github.com/request/request/pull/544) Update http-signature version. (@davidlehn)
- [#581](https://github.com/request/request/pull/581) Fix spelling of "ignoring." (@bigeasy)
- [#568](https://github.com/request/request/pull/568) use agentOptions to create agent when specified in request (@SamPlacette)
- [#564](https://github.com/request/request/pull/564) Fix redirections (@criloz)
- [#541](https://github.com/request/request/pull/541) The exported request function doesn't have an auth method (@tschaub)
- [#542](https://github.com/request/request/pull/542) Expose Request class (@regality)
### v2.21.0 (2013/04/30)
- [#536](https://github.com/request/request/pull/536) Allow explicitly empty user field for basic authentication. (@mikeando)
- [#532](https://github.com/request/request/pull/532) fix typo (@fredericosilva)
- [#497](https://github.com/request/request/pull/497) Added redirect event (@Cauldrath)
- [#503](https://github.com/request/request/pull/503) Fix basic auth for passwords that contain colons (@tonistiigi)
- [#521](https://github.com/request/request/pull/521) Improving test-localAddress.js (@noway421)
- [#529](https://github.com/request/request/pull/529) dependencies versions bump (@jodaka)
### v2.17.0 (2013/04/22)
- [#523](https://github.com/request/request/pull/523) Updating dependencies (@noway421)
- [#520](https://github.com/request/request/pull/520) Fixing test-tunnel.js (@noway421)
- [#519](https://github.com/request/request/pull/519) Update internal path state on post-creation QS changes (@jblebrun)
- [#510](https://github.com/request/request/pull/510) Add HTTP Signature support. (@davidlehn)
- [#502](https://github.com/request/request/pull/502) Fix POST (and probably other) requests that are retried after 401 Unauthorized (@nylen)
- [#508](https://github.com/request/request/pull/508) Honor the .strictSSL option when using proxies (tunnel-agent) (@jhs)
- [#512](https://github.com/request/request/pull/512) Make password optional to support the format: http://username@hostname/ (@pajato1)
- [#513](https://github.com/request/request/pull/513) add 'localAddress' support (@yyfrankyy)
- [#498](https://github.com/request/request/pull/498) Moving response emit above setHeaders on destination streams (@kenperkins)
- [#490](https://github.com/request/request/pull/490) Empty response body (3-rd argument) must be passed to callback as an empty string (@Olegas)
- [#479](https://github.com/request/request/pull/479) Changing so if Accept header is explicitly set, sending json does not ov... (@RoryH)
- [#475](https://github.com/request/request/pull/475) Use `unescape` from `querystring` (@shimaore)
- [#473](https://github.com/request/request/pull/473) V0.10 compat (@isaacs)
- [#471](https://github.com/request/request/pull/471) Using querystring library from visionmedia (@kbackowski)
- [#461](https://github.com/request/request/pull/461) Strip the UTF8 BOM from a UTF encoded response (@kppullin)
- [#460](https://github.com/request/request/pull/460) hawk 0.10.0 (@hueniverse)
- [#462](https://github.com/request/request/pull/462) if query params are empty, then request path shouldn't end with a '?' (merges cleanly now) (@jaipandya)
- [#456](https://github.com/request/request/pull/456) hawk 0.9.0 (@hueniverse)
- [#429](https://github.com/request/request/pull/429) Copy options before adding callback. (@nrn, @nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki)
- [#454](https://github.com/request/request/pull/454) Destroy the response if present when destroying the request (clean merge) (@mafintosh)
- [#310](https://github.com/request/request/pull/310) Twitter Oauth Stuff Out of Date; Now Updated (@joemccann, @isaacs, @mscdex)
- [#413](https://github.com/request/request/pull/413) rename googledoodle.png to .jpg (@nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki)
- [#448](https://github.com/request/request/pull/448) Convenience method for PATCH (@mloar)
- [#444](https://github.com/request/request/pull/444) protect against double callbacks on error path (@spollack)
- [#433](https://github.com/request/request/pull/433) Added support for HTTPS cert & key (@mmalecki)
- [#430](https://github.com/request/request/pull/430) Respect specified {Host,host} headers, not just {host} (@andrewschaaf)
- [#415](https://github.com/request/request/pull/415) Fixed a typo. (@jerem)
- [#338](https://github.com/request/request/pull/338) Add more auth options, including digest support (@nylen)
- [#403](https://github.com/request/request/pull/403) Optimize environment lookup to happen once only (@mmalecki)
- [#398](https://github.com/request/request/pull/398) Add more reporting to tests (@mmalecki)
- [#388](https://github.com/request/request/pull/388) Ensure "safe" toJSON doesn't break EventEmitters (@othiym23)
- [#381](https://github.com/request/request/pull/381) Resolving "Invalid signature. Expected signature base string: " (@landeiro)
- [#380](https://github.com/request/request/pull/380) Fixes missing host header on retried request when using forever agent (@mac-)
- [#376](https://github.com/request/request/pull/376) Headers lost on redirect (@kapetan)
- [#375](https://github.com/request/request/pull/375) Fix for missing oauth_timestamp parameter (@jplock)
- [#374](https://github.com/request/request/pull/374) Correct Host header for proxy tunnel CONNECT (@youurayy)
- [#370](https://github.com/request/request/pull/370) Twitter reverse auth uses x_auth_mode not x_auth_type (@drudge)
- [#369](https://github.com/request/request/pull/369) Don't remove x_auth_mode for Twitter reverse auth (@drudge)
- [#344](https://github.com/request/request/pull/344) Make AWS auth signing find headers correctly (@nlf)
- [#363](https://github.com/request/request/pull/363) rfc3986 on base_uri, now passes tests (@jeffmarshall)
- [#362](https://github.com/request/request/pull/362) Running `rfc3986` on `base_uri` in `oauth.hmacsign` instead of just `encodeURIComponent` (@jeffmarshall)
- [#361](https://github.com/request/request/pull/361) Don't create a Content-Length header if we already have it set (@danjenkins)
- [#360](https://github.com/request/request/pull/360) Delete self._form along with everything else on redirect (@jgautier)
- [#355](https://github.com/request/request/pull/355) stop sending erroneous headers on redirected requests (@azylman)
- [#332](https://github.com/request/request/pull/332) Fix #296 - Only set Content-Type if body exists (@Marsup)
- [#343](https://github.com/request/request/pull/343) Allow AWS to work in more situations, added a note in the README on its usage (@nlf)
- [#320](https://github.com/request/request/pull/320) request.defaults() doesn't need to wrap jar() (@StuartHarris)
- [#322](https://github.com/request/request/pull/322) Fix + test for piped into request bumped into redirect. #321 (@alexindigo)
- [#326](https://github.com/request/request/pull/326) Do not try to remove listener from an undefined connection (@strk)
- [#318](https://github.com/request/request/pull/318) Pass servername to tunneling secure socket creation (@isaacs)
- [#317](https://github.com/request/request/pull/317) Workaround for #313 (@isaacs)
- [#293](https://github.com/request/request/pull/293) Allow parser errors to bubble up to request (@mscdex)
- [#290](https://github.com/request/request/pull/290) A test for #289 (@isaacs)
- [#280](https://github.com/request/request/pull/280) Like in node.js print options if NODE_DEBUG contains the word request (@Filirom1)
- [#207](https://github.com/request/request/pull/207) Fix #206 Change HTTP/HTTPS agent when redirecting between protocols (@isaacs)
- [#214](https://github.com/request/request/pull/214) documenting additional behavior of json option (@jphaas)
- [#272](https://github.com/request/request/pull/272) Boundary begins with CRLF? (@elspoono, @timshadel, @naholyr, @nanodocumet, @TehShrike)
- [#284](https://github.com/request/request/pull/284) Remove stray `console.log()` call in multipart generator. (@bcherry)
- [#241](https://github.com/request/request/pull/241) Composability updates suggested by issue #239 (@polotek)
- [#282](https://github.com/request/request/pull/282) OAuth Authorization header contains non-"oauth_" parameters (@jplock)
- [#279](https://github.com/request/request/pull/279) fix tests with boundary by injecting boundry from header (@benatkin)
- [#273](https://github.com/request/request/pull/273) Pipe back pressure issue (@mafintosh)
- [#268](https://github.com/request/request/pull/268) I'm not OCD seriously (@TehShrike)
- [#263](https://github.com/request/request/pull/263) Bug in OAuth key generation for sha1 (@nanodocumet)
- [#265](https://github.com/request/request/pull/265) uncaughtException when redirected to invalid URI (@naholyr)
- [#262](https://github.com/request/request/pull/262) JSON test should check for equality (@timshadel)
- [#261](https://github.com/request/request/pull/261) Setting 'pool' to 'false' does NOT disable Agent pooling (@timshadel)
- [#249](https://github.com/request/request/pull/249) Fix for the fix of your (closed) issue #89 where self.headers[content-length] is set to 0 for all methods (@sethbridges, @polotek, @zephrax, @jeromegn)
- [#255](https://github.com/request/request/pull/255) multipart allow body === '' ( the empty string ) (@Filirom1)
- [#260](https://github.com/request/request/pull/260) fixed just another leak of 'i' (@sreuter)
- [#246](https://github.com/request/request/pull/246) Fixing the set-cookie header (@jeromegn)
- [#243](https://github.com/request/request/pull/243) Dynamic boundary (@zephrax)
- [#240](https://github.com/request/request/pull/240) don't error when null is passed for options (@polotek)
- [#211](https://github.com/request/request/pull/211) Replace all occurrences of special chars in RFC3986 (@chriso)
- [#224](https://github.com/request/request/pull/224) Multipart content-type change (@janjongboom)
- [#217](https://github.com/request/request/pull/217) need to use Authorization (titlecase) header with Tumblr OAuth (@visnup)
- [#203](https://github.com/request/request/pull/203) Fix cookie and redirect bugs and add auth support for HTTPS tunnel (@milewise)
- [#199](https://github.com/request/request/pull/199) Tunnel (@isaacs)
- [#198](https://github.com/request/request/pull/198) Bugfix on forever usage of util.inherits (@isaacs)
- [#197](https://github.com/request/request/pull/197) Make ForeverAgent work with HTTPS (@isaacs)
- [#193](https://github.com/request/request/pull/193) Fixes GH-119 (@goatslacker)
- [#188](https://github.com/request/request/pull/188) Add abort support to the returned request (@itay)
- [#176](https://github.com/request/request/pull/176) Querystring option (@csainty)
- [#182](https://github.com/request/request/pull/182) Fix request.defaults to support (uri, options, callback) api (@twilson63)
- [#180](https://github.com/request/request/pull/180) Modified the post, put, head and del shortcuts to support uri optional param (@twilson63)
- [#179](https://github.com/request/request/pull/179) fix to add opts in .pipe(stream, opts) (@substack)
- [#177](https://github.com/request/request/pull/177) Issue #173 Support uri as first and optional config as second argument (@twilson63)
- [#170](https://github.com/request/request/pull/170) can't create a cookie in a wrapped request (defaults) (@fabianonunes)
- [#168](https://github.com/request/request/pull/168) Picking off an EasyFix by adding some missing mimetypes. (@serby)
- [#161](https://github.com/request/request/pull/161) Fix cookie jar/headers.cookie collision (#125) (@papandreou)
- [#162](https://github.com/request/request/pull/162) Fix issue #159 (@dpetukhov)
- [#90](https://github.com/request/request/pull/90) add option followAllRedirects to follow post/put redirects (@jroes)
- [#148](https://github.com/request/request/pull/148) Retry Agent (@thejh)
- [#146](https://github.com/request/request/pull/146) Multipart should respect content-type if previously set (@apeace)
- [#144](https://github.com/request/request/pull/144) added "form" option to readme (@petejkim)
- [#133](https://github.com/request/request/pull/133) Fixed cookies parsing (@afanasy)
- [#135](https://github.com/request/request/pull/135) host vs hostname (@iangreenleaf)
- [#132](https://github.com/request/request/pull/132) return the body as a Buffer when encoding is set to null (@jahewson)
- [#112](https://github.com/request/request/pull/112) Support using a custom http-like module (@jhs)
- [#104](https://github.com/request/request/pull/104) Cookie handling contains bugs (@janjongboom)
- [#121](https://github.com/request/request/pull/121) Another patch for cookie handling regression (@jhurliman)
- [#117](https://github.com/request/request/pull/117) Remove the global `i` (@3rd-Eden)
- [#110](https://github.com/request/request/pull/110) Update to Iris Couch URL (@jhs)
- [#86](https://github.com/request/request/pull/86) Can't post binary to multipart requests (@kkaefer)
- [#105](https://github.com/request/request/pull/105) added test for proxy option. (@dominictarr)
- [#102](https://github.com/request/request/pull/102) Implemented cookies - closes issue 82: https://github.com/mikeal/request/issues/82 (@alessioalex)
- [#97](https://github.com/request/request/pull/97) Typo in previous pull causes TypeError in non-0.5.11 versions (@isaacs)
- [#96](https://github.com/request/request/pull/96) Authless parsed url host support (@isaacs)
- [#81](https://github.com/request/request/pull/81) Enhance redirect handling (@danmactough)
- [#78](https://github.com/request/request/pull/78) Don't try to do strictSSL for non-ssl connections (@isaacs)
- [#76](https://github.com/request/request/pull/76) Bug when a request fails and a timeout is set (@Marsup)
- [#70](https://github.com/request/request/pull/70) add test script to package.json (@isaacs, @aheckmann)
- [#73](https://github.com/request/request/pull/73) Fix #71 Respect the strictSSL flag (@isaacs)
- [#69](https://github.com/request/request/pull/69) Flatten chunked requests properly (@isaacs)
- [#67](https://github.com/request/request/pull/67) fixed global variable leaks (@aheckmann)
- [#66](https://github.com/request/request/pull/66) Do not overwrite established content-type headers for read stream deliver (@voodootikigod)
- [#53](https://github.com/request/request/pull/53) Parse json: Issue #51 (@benatkin)
- [#45](https://github.com/request/request/pull/45) Added timeout option (@mbrevoort)
- [#35](https://github.com/request/request/pull/35) The "end" event isn't emitted for some responses (@voxpelli)

44
node_modules/request/CONTRIBUTING.md generated vendored Normal file
View File

@ -0,0 +1,44 @@
# This is an OPEN Open Source Project
-----------------------------------------
## What?
Individuals making significant and valuable contributions are given
commit-access to the project to contribute as they see fit. This project is
more like an open wiki than a standard guarded open source project.
## Rules
There are a few basic ground-rules for contributors:
1. **No `--force` pushes** or modifying the Git history in any way.
1. **Non-master branches** ought to be used for ongoing work.
1. **External API changes and significant modifications** ought to be subject
to an **internal pull-request** to solicit feedback from other contributors.
1. Internal pull-requests to solicit feedback are *encouraged* for any other
non-trivial contribution but left to the discretion of the contributor.
1. For significant changes wait a full 24 hours before merging so that active
contributors who are distributed throughout the world have a chance to weigh
in.
1. Contributors should attempt to adhere to the prevailing code-style.
1. Run `npm test` locally before submitting your PR, to catch any easy to miss
style & testing issues. To diagnose test failures, there are two ways to
run a single test file:
- `node_modules/.bin/taper tests/test-file.js` - run using the default
[`taper`](https://github.com/nylen/taper) test reporter.
- `node tests/test-file.js` - view the raw
[tap](https://testanything.org/) output.
## Releases
Declaring formal releases remains the prerogative of the project maintainer.
## Changes to this arrangement
This is an experiment and feedback is welcome! This document may also be
subject to pull-requests or changes by contributors where you believe you have
something valuable to add or change.
-----------------------------------------

55
node_modules/request/LICENSE generated vendored Normal file
View File

@ -0,0 +1,55 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

1095
node_modules/request/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

156
node_modules/request/index.js generated vendored Executable file
View File

@ -0,0 +1,156 @@
// Copyright 2010-2012 Mikeal Rogers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict'
var extend = require('extend')
, cookies = require('./lib/cookies')
, helpers = require('./lib/helpers')
var isFunction = helpers.isFunction
, paramsHaveRequestBody = helpers.paramsHaveRequestBody
// organize params for patch, post, put, head, del
function initParams(uri, options, callback) {
if (typeof options === 'function') {
callback = options
}
var params = {}
if (typeof options === 'object') {
extend(params, options, {uri: uri})
} else if (typeof uri === 'string') {
extend(params, {uri: uri})
} else {
extend(params, uri)
}
params.callback = callback
return params
}
function request (uri, options, callback) {
if (typeof uri === 'undefined') {
throw new Error('undefined is not a valid uri or options object.')
}
var params = initParams(uri, options, callback)
if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
throw new Error('HTTP HEAD requests MUST NOT include a request body.')
}
return new request.Request(params)
}
function verbFunc (verb) {
var method = verb === 'del' ? 'DELETE' : verb.toUpperCase()
return function (uri, options, callback) {
var params = initParams(uri, options, callback)
params.method = method
return request(params, params.callback)
}
}
// define like this to please codeintel/intellisense IDEs
request.get = verbFunc('get')
request.head = verbFunc('head')
request.post = verbFunc('post')
request.put = verbFunc('put')
request.patch = verbFunc('patch')
request.del = verbFunc('del')
request.jar = function (store) {
return cookies.jar(store)
}
request.cookie = function (str) {
return cookies.parse(str)
}
function wrapRequestMethod (method, options, requester, verb) {
return function (uri, opts, callback) {
var params = initParams(uri, opts, callback)
var target = {}
extend(true, target, options, params)
target.pool = params.pool || options.pool
if (verb) {
target.method = (verb === 'del' ? 'DELETE' : verb.toUpperCase())
}
if (isFunction(requester)) {
method = requester
}
return method(target, target.callback)
}
}
request.defaults = function (options, requester) {
var self = this
options = options || {}
if (typeof options === 'function') {
requester = options
options = {}
}
var defaults = wrapRequestMethod(self, options, requester)
var verbs = ['get', 'head', 'post', 'put', 'patch', 'del']
verbs.forEach(function(verb) {
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
})
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
defaults.jar = self.jar
defaults.defaults = self.defaults
return defaults
}
request.forever = function (agentOptions, optionsArg) {
var options = {}
if (optionsArg) {
extend(options, optionsArg)
}
if (agentOptions) {
options.agentOptions = agentOptions
}
options.forever = true
return request.defaults(options)
}
// Exports
module.exports = request
request.Request = require('./request')
request.initParams = initParams
// Backwards compatibility for request.debug
Object.defineProperty(request, 'debug', {
enumerable : true,
get : function() {
return request.Request.debug
},
set : function(debug) {
request.Request.debug = debug
}
})

168
node_modules/request/lib/auth.js generated vendored Normal file
View File

@ -0,0 +1,168 @@
'use strict'
var caseless = require('caseless')
, uuid = require('node-uuid')
, helpers = require('./helpers')
var md5 = helpers.md5
, toBase64 = helpers.toBase64
function Auth (request) {
// define all public properties here
this.request = request
this.hasAuth = false
this.sentAuth = false
this.bearerToken = null
this.user = null
this.pass = null
}
Auth.prototype.basic = function (user, pass, sendImmediately) {
var self = this
if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
self.request.emit('error', new Error('auth() received invalid user or password'))
}
self.user = user
self.pass = pass
self.hasAuth = true
var header = user + ':' + (pass || '')
if (sendImmediately || typeof sendImmediately === 'undefined') {
var authHeader = 'Basic ' + toBase64(header)
self.sentAuth = true
return authHeader
}
}
Auth.prototype.bearer = function (bearer, sendImmediately) {
var self = this
self.bearerToken = bearer
self.hasAuth = true
if (sendImmediately || typeof sendImmediately === 'undefined') {
if (typeof bearer === 'function') {
bearer = bearer()
}
var authHeader = 'Bearer ' + (bearer || '')
self.sentAuth = true
return authHeader
}
}
Auth.prototype.digest = function (method, path, authHeader) {
// TODO: More complete implementation of RFC 2617.
// - handle challenge.domain
// - support qop="auth-int" only
// - handle Authentication-Info (not necessarily?)
// - check challenge.stale (not necessarily?)
// - increase nc (not necessarily?)
// For reference:
// http://tools.ietf.org/html/rfc2617#section-3
// https://github.com/bagder/curl/blob/master/lib/http_digest.c
var self = this
var challenge = {}
var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
for (;;) {
var match = re.exec(authHeader)
if (!match) {
break
}
challenge[match[1]] = match[2] || match[3]
}
/**
* RFC 2617: handle both MD5 and MD5-sess algorithms.
*
* If the algorithm directive's value is "MD5" or unspecified, then HA1 is
* HA1=MD5(username:realm:password)
* If the algorithm directive's value is "MD5-sess", then HA1 is
* HA1=MD5(MD5(username:realm:password):nonce:cnonce)
*/
var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
var ha1 = md5(user + ':' + realm + ':' + pass)
if (algorithm && algorithm.toLowerCase() === 'md5-sess') {
return md5(ha1 + ':' + nonce + ':' + cnonce)
} else {
return ha1
}
}
var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
var nc = qop && '00000001'
var cnonce = qop && uuid().replace(/-/g, '')
var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce)
var ha2 = md5(method + ':' + path)
var digestResponse = qop
? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
: md5(ha1 + ':' + challenge.nonce + ':' + ha2)
var authValues = {
username: self.user,
realm: challenge.realm,
nonce: challenge.nonce,
uri: path,
qop: qop,
response: digestResponse,
nc: nc,
cnonce: cnonce,
algorithm: challenge.algorithm,
opaque: challenge.opaque
}
authHeader = []
for (var k in authValues) {
if (authValues[k]) {
if (k === 'qop' || k === 'nc' || k === 'algorithm') {
authHeader.push(k + '=' + authValues[k])
} else {
authHeader.push(k + '="' + authValues[k] + '"')
}
}
}
authHeader = 'Digest ' + authHeader.join(', ')
self.sentAuth = true
return authHeader
}
Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
var self = this
, request = self.request
var authHeader
if (bearer === undefined && user === undefined) {
self.request.emit('error', new Error('no auth mechanism defined'))
} else if (bearer !== undefined) {
authHeader = self.bearer(bearer, sendImmediately)
} else {
authHeader = self.basic(user, pass, sendImmediately)
}
if (authHeader) {
request.setHeader('authorization', authHeader)
}
}
Auth.prototype.onResponse = function (response) {
var self = this
, request = self.request
if (!self.hasAuth || self.sentAuth) { return null }
var c = caseless(response.headers)
var authHeader = c.get('www-authenticate')
var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
request.debug('reauth', authVerb)
switch (authVerb) {
case 'basic':
return self.basic(self.user, self.pass, true)
case 'bearer':
return self.bearer(self.bearerToken, true)
case 'digest':
return self.digest(request.method, request.path, authHeader)
}
}
exports.Auth = Auth

39
node_modules/request/lib/cookies.js generated vendored Normal file
View File

@ -0,0 +1,39 @@
'use strict'
var tough = require('tough-cookie')
var Cookie = tough.Cookie
, CookieJar = tough.CookieJar
exports.parse = function(str) {
if (str && str.uri) {
str = str.uri
}
if (typeof str !== 'string') {
throw new Error('The cookie function only accepts STRING as param')
}
return Cookie.parse(str, {loose: true})
}
// Adapt the sometimes-Async api of tough.CookieJar to our requirements
function RequestJar(store) {
var self = this
self._jar = new CookieJar(store, {looseMode: true})
}
RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
var self = this
return self._jar.setCookieSync(cookieOrStr, uri, options || {})
}
RequestJar.prototype.getCookieString = function(uri) {
var self = this
return self._jar.getCookieStringSync(uri)
}
RequestJar.prototype.getCookies = function(uri) {
var self = this
return self._jar.getCookiesSync(uri)
}
exports.jar = function(store) {
return new RequestJar(store)
}

79
node_modules/request/lib/getProxyFromURI.js generated vendored Normal file
View File

@ -0,0 +1,79 @@
'use strict'
function formatHostname(hostname) {
// canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
return hostname.replace(/^\.*/, '.').toLowerCase()
}
function parseNoProxyZone(zone) {
zone = zone.trim().toLowerCase()
var zoneParts = zone.split(':', 2)
, zoneHost = formatHostname(zoneParts[0])
, zonePort = zoneParts[1]
, hasPort = zone.indexOf(':') > -1
return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
}
function uriInNoProxy(uri, noProxy) {
var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
, hostname = formatHostname(uri.hostname)
, noProxyList = noProxy.split(',')
// iterate through the noProxyList until it finds a match.
return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
, hostnameMatched = (
isMatchedAt > -1 &&
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
)
if (noProxyZone.hasPort) {
return (port === noProxyZone.port) && hostnameMatched
}
return hostnameMatched
})
}
function getProxyFromURI(uri) {
// Decide the proper request proxy to use based on the request URI object and the
// environmental variables (NO_PROXY, HTTP_PROXY, etc.)
// respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
// if the noProxy is a wildcard then return null
if (noProxy === '*') {
return null
}
// if the noProxy is not empty and the uri is found return null
if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
return null
}
// Check for HTTP or HTTPS Proxy in environment Else default to null
if (uri.protocol === 'http:') {
return process.env.HTTP_PROXY ||
process.env.http_proxy || null
}
if (uri.protocol === 'https:') {
return process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy || null
}
// if none of that works, return null
// (What uri protocol are you using then?)
return null
}
module.exports = getProxyFromURI

205
node_modules/request/lib/har.js generated vendored Normal file
View File

@ -0,0 +1,205 @@
'use strict'
var fs = require('fs')
var qs = require('querystring')
var validate = require('har-validator')
var util = require('util')
function Har (request) {
this.request = request
}
Har.prototype.reducer = function (obj, pair) {
// new property ?
if (obj[pair.name] === undefined) {
obj[pair.name] = pair.value
return obj
}
// existing? convert to array
var arr = [
obj[pair.name],
pair.value
]
obj[pair.name] = arr
return obj
}
Har.prototype.prep = function (data) {
// construct utility properties
data.queryObj = {}
data.headersObj = {}
data.postData.jsonObj = false
data.postData.paramsObj = false
// construct query objects
if (data.queryString && data.queryString.length) {
data.queryObj = data.queryString.reduce(this.reducer, {})
}
// construct headers objects
if (data.headers && data.headers.length) {
// loweCase header keys
data.headersObj = data.headers.reduceRight(function (headers, header) {
headers[header.name] = header.value
return headers
}, {})
}
// construct Cookie header
if (data.cookies && data.cookies.length) {
var cookies = data.cookies.map(function (cookie) {
return cookie.name + '=' + cookie.value
})
if (cookies.length) {
data.headersObj.cookie = cookies.join('; ')
}
}
// prep body
switch (data.postData.mimeType) {
case 'multipart/mixed':
case 'multipart/related':
case 'multipart/form-data':
case 'multipart/alternative':
// reset values
data.postData.mimeType = 'multipart/form-data'
break
case 'application/x-www-form-urlencoded':
if (!data.postData.params) {
data.postData.text = ''
} else {
data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
// always overwrite
data.postData.text = qs.stringify(data.postData.paramsObj)
}
break
case 'text/json':
case 'text/x-json':
case 'application/json':
case 'application/x-json':
data.postData.mimeType = 'application/json'
if (data.postData.text) {
try {
data.postData.jsonObj = JSON.parse(data.postData.text)
} catch (e) {
this.request.debug(e)
// force back to text/plain
data.postData.mimeType = 'text/plain'
}
}
break
}
return data
}
Har.prototype.options = function (options) {
// skip if no har property defined
if (!options.har) {
return options
}
var har = util._extend({}, options.har)
// only process the first entry
if (har.log && har.log.entries) {
har = har.log.entries[0]
}
// add optional properties to make validation successful
har.url = har.url || options.url || options.uri || options.baseUrl || '/'
har.httpVersion = har.httpVersion || 'HTTP/1.1'
har.queryString = har.queryString || []
har.headers = har.headers || []
har.cookies = har.cookies || []
har.postData = har.postData || {}
har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
har.bodySize = 0
har.headersSize = 0
har.postData.size = 0
if (!validate.request(har)) {
return options
}
// clean up and get some utility properties
var req = this.prep(har)
// construct new options
if (req.url) {
options.url = req.url
}
if (req.method) {
options.method = req.method
}
if (Object.keys(req.queryObj).length) {
options.qs = req.queryObj
}
if (Object.keys(req.headersObj).length) {
options.headers = req.headersObj
}
switch (req.postData.mimeType) {
case 'application/x-www-form-urlencoded':
options.form = req.postData.paramsObj
break
case 'application/json':
if (req.postData.jsonObj) {
options.body = req.postData.jsonObj
options.json = true
}
break
case 'multipart/form-data':
options.formData = {}
req.postData.params.forEach(function (param) {
var attachment = {}
if (!param.fileName && !param.fileName && !param.contentType) {
options.formData[param.name] = param.value
return
}
// attempt to read from disk!
if (param.fileName && !param.value) {
attachment.value = fs.createReadStream(param.fileName)
} else if (param.value) {
attachment.value = param.value
}
if (param.fileName) {
attachment.options = {
filename: param.fileName,
contentType: param.contentType ? param.contentType : null
}
}
options.formData[param.name] = attachment
})
break
default:
if (req.postData.text) {
options.body = req.postData.text
}
}
return options
}
exports.Har = Har

74
node_modules/request/lib/helpers.js generated vendored Normal file
View File

@ -0,0 +1,74 @@
'use strict'
var jsonSafeStringify = require('json-stringify-safe')
, crypto = require('crypto')
function deferMethod() {
if (typeof setImmediate === 'undefined') {
return process.nextTick
}
return setImmediate
}
function isFunction(value) {
return typeof value === 'function'
}
function paramsHaveRequestBody(params) {
return (
params.body ||
params.requestBodyStream ||
(params.json && typeof params.json !== 'boolean') ||
params.multipart
)
}
function safeStringify (obj) {
var ret
try {
ret = JSON.stringify(obj)
} catch (e) {
ret = jsonSafeStringify(obj)
}
return ret
}
function md5 (str) {
return crypto.createHash('md5').update(str).digest('hex')
}
function isReadStream (rs) {
return rs.readable && rs.path && rs.mode
}
function toBase64 (str) {
return (new Buffer(str || '', 'utf8')).toString('base64')
}
function copy (obj) {
var o = {}
Object.keys(obj).forEach(function (i) {
o[i] = obj[i]
})
return o
}
function version () {
var numbers = process.version.replace('v', '').split('.')
return {
major: parseInt(numbers[0], 10),
minor: parseInt(numbers[1], 10),
patch: parseInt(numbers[2], 10)
}
}
exports.isFunction = isFunction
exports.paramsHaveRequestBody = paramsHaveRequestBody
exports.safeStringify = safeStringify
exports.md5 = md5
exports.isReadStream = isReadStream
exports.toBase64 = toBase64
exports.copy = copy
exports.version = version
exports.defer = deferMethod()

109
node_modules/request/lib/multipart.js generated vendored Normal file
View File

@ -0,0 +1,109 @@
'use strict'
var uuid = require('node-uuid')
, CombinedStream = require('combined-stream')
, isstream = require('isstream')
function Multipart (request) {
this.request = request
this.boundary = uuid()
this.chunked = false
this.body = null
}
Multipart.prototype.isChunked = function (options) {
var self = this
, chunked = false
, parts = options.data || options
if (!parts.forEach) {
self.request.emit('error', new Error('Argument error, options.multipart.'))
}
if (options.chunked !== undefined) {
chunked = options.chunked
}
if (self.request.getHeader('transfer-encoding') === 'chunked') {
chunked = true
}
if (!chunked) {
parts.forEach(function (part) {
if (typeof part.body === 'undefined') {
self.request.emit('error', new Error('Body attribute missing in multipart.'))
}
if (isstream(part.body)) {
chunked = true
}
})
}
return chunked
}
Multipart.prototype.setHeaders = function (chunked) {
var self = this
if (chunked && !self.request.hasHeader('transfer-encoding')) {
self.request.setHeader('transfer-encoding', 'chunked')
}
var header = self.request.getHeader('content-type')
if (!header || header.indexOf('multipart') === -1) {
self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
} else {
if (header.indexOf('boundary') !== -1) {
self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
} else {
self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
}
}
}
Multipart.prototype.build = function (parts, chunked) {
var self = this
var body = chunked ? new CombinedStream() : []
function add (part) {
return chunked ? body.append(part) : body.push(new Buffer(part))
}
if (self.request.preambleCRLF) {
add('\r\n')
}
parts.forEach(function (part) {
var preamble = '--' + self.boundary + '\r\n'
Object.keys(part).forEach(function (key) {
if (key === 'body') { return }
preamble += key + ': ' + part[key] + '\r\n'
})
preamble += '\r\n'
add(preamble)
add(part.body)
add('\r\n')
})
add('--' + self.boundary + '--')
if (self.request.postambleCRLF) {
add('\r\n')
}
return body
}
Multipart.prototype.onRequest = function (options) {
var self = this
var chunked = self.isChunked(options)
, parts = options.data || options
self.setHeaders(chunked)
self.chunked = chunked
self.body = self.build(parts, chunked)
}
exports.Multipart = Multipart

147
node_modules/request/lib/oauth.js generated vendored Normal file
View File

@ -0,0 +1,147 @@
'use strict'
var url = require('url')
, qs = require('qs')
, caseless = require('caseless')
, uuid = require('node-uuid')
, oauth = require('oauth-sign')
, crypto = require('crypto')
function OAuth (request) {
this.request = request
this.params = null
}
OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) {
var oa = {}
for (var i in _oauth) {
oa['oauth_' + i] = _oauth[i]
}
if (!oa.oauth_version) {
oa.oauth_version = '1.0'
}
if (!oa.oauth_timestamp) {
oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
}
if (!oa.oauth_nonce) {
oa.oauth_nonce = uuid().replace(/-/g, '')
}
if (!oa.oauth_signature_method) {
oa.oauth_signature_method = 'HMAC-SHA1'
}
var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
delete oa.oauth_consumer_secret
delete oa.oauth_private_key
var token_secret = oa.oauth_token_secret
delete oa.oauth_token_secret
var realm = oa.oauth_realm
delete oa.oauth_realm
delete oa.oauth_transport_method
var baseurl = uri.protocol + '//' + uri.host + uri.pathname
var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'))
oa.oauth_signature = oauth.sign(
oa.oauth_signature_method,
method,
baseurl,
params,
consumer_secret_or_private_key,
token_secret)
if (realm) {
oa.realm = realm
}
return oa
}
OAuth.prototype.buildBodyHash = function(_oauth, body) {
if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
' signature_method not supported with body_hash signing.'))
}
var shasum = crypto.createHash('sha1')
shasum.update(body || '')
var sha1 = shasum.digest('hex')
return new Buffer(sha1).toString('base64')
}
OAuth.prototype.concatParams = function (oa, sep, wrap) {
wrap = wrap || ''
var params = Object.keys(oa).filter(function (i) {
return i !== 'realm' && i !== 'oauth_signature'
}).sort()
if (oa.realm) {
params.splice(0, 0, 'realm')
}
params.push('oauth_signature')
return params.map(function (i) {
return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap
}).join(sep)
}
OAuth.prototype.onRequest = function (_oauth) {
var self = this
self.params = _oauth
var uri = self.request.uri || {}
, method = self.request.method || ''
, headers = caseless(self.request.headers)
, body = self.request.body || ''
, qsLib = self.request.qsLib || qs
var form
, query
, contentType = headers.get('content-type') || ''
, formContentType = 'application/x-www-form-urlencoded'
, transport = _oauth.transport_method || 'header'
if (contentType.slice(0, formContentType.length) === formContentType) {
contentType = formContentType
form = body
}
if (uri.query) {
query = uri.query
}
if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
self.request.emit('error', new Error('oauth: transport_method of body requires POST ' +
'and content-type ' + formContentType))
}
if (!form && typeof _oauth.body_hash === 'boolean') {
_oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString())
}
var oa = self.buildParams(_oauth, uri, method, query, form, qsLib)
switch (transport) {
case 'header':
self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"'))
break
case 'query':
var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&')
self.request.uri = url.parse(href)
self.request.path = self.request.uri.path
break
case 'body':
self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&')
break
default:
self.request.emit('error', new Error('oauth: transport_method invalid'))
}
}
exports.OAuth = OAuth

51
node_modules/request/lib/querystring.js generated vendored Normal file
View File

@ -0,0 +1,51 @@
'use strict'
var qs = require('qs')
, querystring = require('querystring')
function Querystring (request) {
this.request = request
this.lib = null
this.useQuerystring = null
this.parseOptions = null
this.stringifyOptions = null
}
Querystring.prototype.init = function (options) {
if (this.lib) {return}
this.useQuerystring = options.useQuerystring
this.lib = (this.useQuerystring ? querystring : qs)
this.parseOptions = options.qsParseOptions || {}
this.stringifyOptions = options.qsStringifyOptions || {}
}
Querystring.prototype.stringify = function (obj) {
return (this.useQuerystring)
? this.rfc3986(this.lib.stringify(obj,
this.stringifyOptions.sep || null,
this.stringifyOptions.eq || null,
this.stringifyOptions))
: this.lib.stringify(obj, this.stringifyOptions)
}
Querystring.prototype.parse = function (str) {
return (this.useQuerystring)
? this.lib.parse(str,
this.parseOptions.sep || null,
this.parseOptions.eq || null,
this.parseOptions)
: this.lib.parse(str, this.parseOptions)
}
Querystring.prototype.rfc3986 = function (str) {
return str.replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
Querystring.prototype.unescape = querystring.unescape
exports.Querystring = Querystring

154
node_modules/request/lib/redirect.js generated vendored Normal file
View File

@ -0,0 +1,154 @@
'use strict'
var url = require('url')
var isUrl = /^https?:/
function Redirect (request) {
this.request = request
this.followRedirect = true
this.followRedirects = true
this.followAllRedirects = false
this.allowRedirect = function () {return true}
this.maxRedirects = 10
this.redirects = []
this.redirectsFollowed = 0
this.removeRefererHeader = false
}
Redirect.prototype.onRequest = function (options) {
var self = this
if (options.maxRedirects !== undefined) {
self.maxRedirects = options.maxRedirects
}
if (typeof options.followRedirect === 'function') {
self.allowRedirect = options.followRedirect
}
if (options.followRedirect !== undefined) {
self.followRedirects = !!options.followRedirect
}
if (options.followAllRedirects !== undefined) {
self.followAllRedirects = options.followAllRedirects
}
if (self.followRedirects || self.followAllRedirects) {
self.redirects = self.redirects || []
}
if (options.removeRefererHeader !== undefined) {
self.removeRefererHeader = options.removeRefererHeader
}
}
Redirect.prototype.redirectTo = function (response) {
var self = this
, request = self.request
var redirectTo = null
if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
var location = response.caseless.get('location')
request.debug('redirect', location)
if (self.followAllRedirects) {
redirectTo = location
} else if (self.followRedirects) {
switch (request.method) {
case 'PATCH':
case 'PUT':
case 'POST':
case 'DELETE':
// Do not follow redirects
break
default:
redirectTo = location
break
}
}
} else if (response.statusCode === 401) {
var authHeader = request._auth.onResponse(response)
if (authHeader) {
request.setHeader('authorization', authHeader)
redirectTo = request.uri
}
}
return redirectTo
}
Redirect.prototype.onResponse = function (response) {
var self = this
, request = self.request
var redirectTo = self.redirectTo(response)
if (!redirectTo || !self.allowRedirect.call(request, response)) {
return false
}
request.debug('redirect to', redirectTo)
// ignore any potential response body. it cannot possibly be useful
// to us at this point.
// response.resume should be defined, but check anyway before calling. Workaround for browserify.
if (response.resume) {
response.resume()
}
if (self.redirectsFollowed >= self.maxRedirects) {
request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
return false
}
self.redirectsFollowed += 1
if (!isUrl.test(redirectTo)) {
redirectTo = url.resolve(request.uri.href, redirectTo)
}
var uriPrev = request.uri
request.uri = url.parse(redirectTo)
// handle the case where we change protocol from https to http or vice versa
if (request.uri.protocol !== uriPrev.protocol) {
request._updateProtocol()
}
self.redirects.push(
{ statusCode : response.statusCode
, redirectUri: redirectTo
}
)
if (self.followAllRedirects && request.method !== 'HEAD'
&& response.statusCode !== 401 && response.statusCode !== 307) {
request.method = 'GET'
}
// request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
delete request.src
delete request.req
delete request.agent
delete request._started
if (response.statusCode !== 401 && response.statusCode !== 307) {
// Remove parameters from the previous response, unless this is the second request
// for a server that requires digest authentication.
delete request.body
delete request._form
if (request.headers) {
request.removeHeader('host')
request.removeHeader('content-type')
request.removeHeader('content-length')
if (request.uri.hostname !== request.originalHost.split(':')[0]) {
// Remove authorization if changing hostnames (but not if just
// changing ports or protocols). This matches the behavior of curl:
// https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
request.removeHeader('authorization')
}
}
}
if (!self.removeRefererHeader) {
request.setHeader('referer', request.uri.href)
}
request.emit('redirect')
request.init()
return true
}
exports.Redirect = Redirect

183
node_modules/request/lib/tunnel.js generated vendored Normal file
View File

@ -0,0 +1,183 @@
'use strict'
var url = require('url')
, tunnel = require('tunnel-agent')
var defaultProxyHeaderWhiteList = [
'accept',
'accept-charset',
'accept-encoding',
'accept-language',
'accept-ranges',
'cache-control',
'content-encoding',
'content-language',
'content-length',
'content-location',
'content-md5',
'content-range',
'content-type',
'connection',
'date',
'expect',
'max-forwards',
'pragma',
'referer',
'te',
'transfer-encoding',
'user-agent',
'via'
]
var defaultProxyHeaderExclusiveList = [
'proxy-authorization'
]
function constructProxyHost(uriObject) {
var port = uriObject.portA
, protocol = uriObject.protocol
, proxyHost = uriObject.hostname + ':'
if (port) {
proxyHost += port
} else if (protocol === 'https:') {
proxyHost += '443'
} else {
proxyHost += '80'
}
return proxyHost
}
function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) {
var whiteList = proxyHeaderWhiteList
.reduce(function (set, header) {
set[header.toLowerCase()] = true
return set
}, {})
return Object.keys(headers)
.filter(function (header) {
return whiteList[header.toLowerCase()]
})
.reduce(function (set, header) {
set[header] = headers[header]
return set
}, {})
}
function constructTunnelOptions (request, proxyHeaders) {
var proxy = request.proxy
var tunnelOptions = {
proxy : {
host : proxy.hostname,
port : +proxy.port,
proxyAuth : proxy.auth,
headers : proxyHeaders
},
headers : request.headers,
ca : request.ca,
cert : request.cert,
key : request.key,
passphrase : request.passphrase,
pfx : request.pfx,
ciphers : request.ciphers,
rejectUnauthorized : request.rejectUnauthorized,
secureOptions : request.secureOptions,
secureProtocol : request.secureProtocol
}
return tunnelOptions
}
function constructTunnelFnName(uri, proxy) {
var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
return [uriProtocol, proxyProtocol].join('Over')
}
function getTunnelFn(request) {
var uri = request.uri
var proxy = request.proxy
var tunnelFnName = constructTunnelFnName(uri, proxy)
return tunnel[tunnelFnName]
}
function Tunnel (request) {
this.request = request
this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
this.proxyHeaderExclusiveList = []
}
Tunnel.prototype.isEnabled = function (options) {
var request = this.request
// Tunnel HTTPS by default, or if a previous request in the redirect chain
// was tunneled. Allow the user to override this setting.
// If self.tunnel is already set (because this is a redirect), use the
// existing value.
if (typeof request.tunnel !== 'undefined') {
return request.tunnel
}
// If options.tunnel is set (the user specified a value), use it.
if (typeof options.tunnel !== 'undefined') {
return options.tunnel
}
// If the destination is HTTPS, tunnel.
if (request.uri.protocol === 'https:') {
return true
}
// Otherwise, leave tunnel unset, because if a later request in the redirect
// chain is HTTPS then that request (and any subsequent ones) should be
// tunneled.
return undefined
}
Tunnel.prototype.setup = function (options) {
var self = this
, request = self.request
options = options || {}
if (typeof request.proxy === 'string') {
request.proxy = url.parse(request.proxy)
}
if (!request.proxy || !request.tunnel) {
return false
}
// Setup Proxy Header Exclusive List and White List
if (options.proxyHeaderWhiteList) {
self.proxyHeaderWhiteList = options.proxyHeaderWhiteList
}
if (options.proxyHeaderExclusiveList) {
self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList
}
var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
// Setup Proxy Headers and Proxy Headers Host
// Only send the Proxy White Listed Header names
var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList)
proxyHeaders.host = constructProxyHost(request.uri)
proxyHeaderExclusiveList.forEach(request.removeHeader, request)
// Set Agent from Tunnel Data
var tunnelFn = getTunnelFn(request)
var tunnelOptions = constructTunnelOptions(request, proxyHeaders)
request.agent = tunnelFn(tunnelOptions)
return true
}
Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList
Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList
exports.Tunnel = Tunnel

1
node_modules/request/node_modules/.bin/har-validator generated vendored Symbolic link
View File

@ -0,0 +1 @@
../har-validator/bin/har-validator

1
node_modules/request/node_modules/.bin/uuid generated vendored Symbolic link
View File

@ -0,0 +1 @@
../node-uuid/bin/uuid

55
node_modules/request/node_modules/aws-sign2/LICENSE generated vendored Normal file
View File

@ -0,0 +1,55 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@ -0,0 +1,4 @@
aws-sign
========
AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.

212
node_modules/request/node_modules/aws-sign2/index.js generated vendored Normal file
View File

@ -0,0 +1,212 @@
/*!
* Copyright 2010 LearnBoost <dev@learnboost.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Module dependencies.
*/
var crypto = require('crypto')
, parse = require('url').parse
;
/**
* Valid keys.
*/
var keys =
[ 'acl'
, 'location'
, 'logging'
, 'notification'
, 'partNumber'
, 'policy'
, 'requestPayment'
, 'torrent'
, 'uploadId'
, 'uploads'
, 'versionId'
, 'versioning'
, 'versions'
, 'website'
]
/**
* Return an "Authorization" header value with the given `options`
* in the form of "AWS <key>:<signature>"
*
* @param {Object} options
* @return {String}
* @api private
*/
function authorization (options) {
return 'AWS ' + options.key + ':' + sign(options)
}
module.exports = authorization
module.exports.authorization = authorization
/**
* Simple HMAC-SHA1 Wrapper
*
* @param {Object} options
* @return {String}
* @api private
*/
function hmacSha1 (options) {
return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
}
module.exports.hmacSha1 = hmacSha1
/**
* Create a base64 sha1 HMAC for `options`.
*
* @param {Object} options
* @return {String}
* @api private
*/
function sign (options) {
options.message = stringToSign(options)
return hmacSha1(options)
}
module.exports.sign = sign
/**
* Create a base64 sha1 HMAC for `options`.
*
* Specifically to be used with S3 presigned URLs
*
* @param {Object} options
* @return {String}
* @api private
*/
function signQuery (options) {
options.message = queryStringToSign(options)
return hmacSha1(options)
}
module.exports.signQuery= signQuery
/**
* Return a string for sign() with the given `options`.
*
* Spec:
*
* <verb>\n
* <md5>\n
* <content-type>\n
* <date>\n
* [headers\n]
* <resource>
*
* @param {Object} options
* @return {String}
* @api private
*/
function stringToSign (options) {
var headers = options.amazonHeaders || ''
if (headers) headers += '\n'
var r =
[ options.verb
, options.md5
, options.contentType
, options.date ? options.date.toUTCString() : ''
, headers + options.resource
]
return r.join('\n')
}
module.exports.queryStringToSign = stringToSign
/**
* Return a string for sign() with the given `options`, but is meant exclusively
* for S3 presigned URLs
*
* Spec:
*
* <date>\n
* <resource>
*
* @param {Object} options
* @return {String}
* @api private
*/
function queryStringToSign (options){
return 'GET\n\n\n' + options.date + '\n' + options.resource
}
module.exports.queryStringToSign = queryStringToSign
/**
* Perform the following:
*
* - ignore non-amazon headers
* - lowercase fields
* - sort lexicographically
* - trim whitespace between ":"
* - join with newline
*
* @param {Object} headers
* @return {String}
* @api private
*/
function canonicalizeHeaders (headers) {
var buf = []
, fields = Object.keys(headers)
;
for (var i = 0, len = fields.length; i < len; ++i) {
var field = fields[i]
, val = headers[field]
, field = field.toLowerCase()
;
if (0 !== field.indexOf('x-amz')) continue
buf.push(field + ':' + val)
}
return buf.sort().join('\n')
}
module.exports.canonicalizeHeaders = canonicalizeHeaders
/**
* Perform the following:
*
* - ignore non sub-resources
* - sort lexicographically
*
* @param {String} resource
* @return {String}
* @api private
*/
function canonicalizeResource (resource) {
var url = parse(resource, true)
, path = url.pathname
, buf = []
;
Object.keys(url.query).forEach(function(key){
if (!~keys.indexOf(key)) return
var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
buf.push(key + val)
})
return path + (buf.length ? '?' + buf.sort().join('&') : '')
}
module.exports.canonicalizeResource = canonicalizeResource

View File

@ -0,0 +1,49 @@
{
"author": {
"name": "Mikeal Rogers",
"email": "mikeal.rogers@gmail.com",
"url": "http://www.futurealoof.com"
},
"name": "aws-sign2",
"description": "AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.",
"version": "0.6.0",
"repository": {
"url": "git+https://github.com/mikeal/aws-sign.git"
},
"license": "Apache-2.0",
"main": "index.js",
"dependencies": {},
"devDependencies": {},
"optionalDependencies": {},
"engines": {
"node": "*"
},
"gitHead": "8554bdb41268fa295eb1ee300f4adaa9f7f07fec",
"bugs": {
"url": "https://github.com/mikeal/aws-sign/issues"
},
"homepage": "https://github.com/mikeal/aws-sign#readme",
"_id": "aws-sign2@0.6.0",
"scripts": {},
"_shasum": "14342dd38dbcc94d0e5b87d763cd63612c0e794f",
"_from": "aws-sign2@>=0.6.0 <0.7.0",
"_npmVersion": "2.14.4",
"_nodeVersion": "4.1.2",
"_npmUser": {
"name": "mikeal",
"email": "mikeal.rogers@gmail.com"
},
"maintainers": [
{
"name": "mikeal",
"email": "mikeal.rogers@gmail.com"
}
],
"dist": {
"shasum": "14342dd38dbcc94d0e5b87d763cd63612c0e794f",
"tarball": "http://registry.npmjs.org/aws-sign2/-/aws-sign2-0.6.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.6.0.tgz",
"readme": "ERROR: No README data found!"
}

59
node_modules/request/node_modules/bl/.jshintrc generated vendored Normal file
View File

@ -0,0 +1,59 @@
{
"predef": [ ]
, "bitwise": false
, "camelcase": false
, "curly": false
, "eqeqeq": false
, "forin": false
, "immed": false
, "latedef": false
, "noarg": true
, "noempty": true
, "nonew": true
, "plusplus": false
, "quotmark": true
, "regexp": false
, "undef": true
, "unused": true
, "strict": false
, "trailing": true
, "maxlen": 120
, "asi": true
, "boss": true
, "debug": true
, "eqnull": true
, "esnext": true
, "evil": true
, "expr": true
, "funcscope": false
, "globalstrict": false
, "iterator": false
, "lastsemic": true
, "laxbreak": true
, "laxcomma": true
, "loopfunc": true
, "multistr": false
, "onecase": false
, "proto": false
, "regexdash": false
, "scripturl": true
, "smarttabs": false
, "shadow": false
, "sub": true
, "supernew": false
, "validthis": true
, "browser": true
, "couch": false
, "devel": false
, "dojo": false
, "mootools": false
, "node": true
, "nonstandard": true
, "prototypejs": false
, "rhino": false
, "worker": true
, "wsh": false
, "nomen": false
, "onevar": false
, "passfail": false
}

1
node_modules/request/node_modules/bl/.npmignore generated vendored Normal file
View File

@ -0,0 +1 @@
node_modules/

14
node_modules/request/node_modules/bl/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,14 @@
language: node_js
before_install:
- curl --location http://git.io/1OcIZA | bash -s
node_js:
- 0.8
- 0.10
- 0.11
branches:
only:
- master
notifications:
email:
- rod@vagg.org
script: npm test

13
node_modules/request/node_modules/bl/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,13 @@
The MIT License (MIT)
=====================
Copyright (c) 2014 bl contributors
----------------------------------
*bl contributors listed at <https://github.com/rvagg/bl#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.

200
node_modules/request/node_modules/bl/README.md generated vendored Normal file
View File

@ -0,0 +1,200 @@
# bl *(BufferList)*
[![Build Status](https://travis-ci.org/rvagg/bl.svg?branch=master)](https://travis-ci.org/rvagg/bl)
**A Node.js Buffer list collector, reader and streamer thingy.**
[![NPM](https://nodei.co/npm/bl.png?downloads=true&downloadRank=true)](https://nodei.co/npm/bl/)
[![NPM](https://nodei.co/npm-dl/bl.png?months=6&height=3)](https://nodei.co/npm/bl/)
**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them!
The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently.
```js
const BufferList = require('bl')
var bl = new BufferList()
bl.append(new Buffer('abcd'))
bl.append(new Buffer('efg'))
bl.append('hi') // bl will also accept & convert Strings
bl.append(new Buffer('j'))
bl.append(new Buffer([ 0x3, 0x4 ]))
console.log(bl.length) // 12
console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij'
console.log(bl.slice(3, 10).toString('ascii')) // 'defghij'
console.log(bl.slice(3, 6).toString('ascii')) // 'def'
console.log(bl.slice(3, 8).toString('ascii')) // 'defgh'
console.log(bl.slice(5, 10).toString('ascii')) // 'fghij'
// or just use toString!
console.log(bl.toString()) // 'abcdefghij\u0003\u0004'
console.log(bl.toString('ascii', 3, 8)) // 'defgh'
console.log(bl.toString('ascii', 5, 10)) // 'fghij'
// other standard Buffer readables
console.log(bl.readUInt16BE(10)) // 0x0304
console.log(bl.readUInt16LE(10)) // 0x0403
```
Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**:
```js
const bl = require('bl')
, fs = require('fs')
fs.createReadStream('README.md')
.pipe(bl(function (err, data) { // note 'new' isn't strictly required
// `data` is a complete Buffer object containing the full data
console.log(data.toString())
}))
```
Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream.
Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!):
```js
const hyperquest = require('hyperquest')
, bl = require('bl')
, url = 'https://raw.github.com/rvagg/bl/master/README.md'
hyperquest(url).pipe(bl(function (err, data) {
console.log(data.toString())
}))
```
Or, use it as a readable stream to recompose a list of Buffers to an output source:
```js
const BufferList = require('bl')
, fs = require('fs')
var bl = new BufferList()
bl.append(new Buffer('abcd'))
bl.append(new Buffer('efg'))
bl.append(new Buffer('hi'))
bl.append(new Buffer('j'))
bl.pipe(fs.createWriteStream('gibberish.txt'))
```
## API
* <a href="#ctor"><code><b>new BufferList([ callback ])</b></code></a>
* <a href="#length"><code>bl.<b>length</b></code></a>
* <a href="#append"><code>bl.<b>append(buffer)</b></code></a>
* <a href="#get"><code>bl.<b>get(index)</b></code></a>
* <a href="#slice"><code>bl.<b>slice([ start[, end ] ])</b></code></a>
* <a href="#copy"><code>bl.<b>copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])</b></code></a>
* <a href="#duplicate"><code>bl.<b>duplicate()</b></code></a>
* <a href="#consume"><code>bl.<b>consume(bytes)</b></code></a>
* <a href="#toString"><code>bl.<b>toString([encoding, [ start, [ end ]]])</b></code></a>
* <a href="#readXX"><code>bl.<b>readDoubleBE()</b></code>, <code>bl.<b>readDoubleLE()</b></code>, <code>bl.<b>readFloatBE()</b></code>, <code>bl.<b>readFloatLE()</b></code>, <code>bl.<b>readInt32BE()</b></code>, <code>bl.<b>readInt32LE()</b></code>, <code>bl.<b>readUInt32BE()</b></code>, <code>bl.<b>readUInt32LE()</b></code>, <code>bl.<b>readInt16BE()</b></code>, <code>bl.<b>readInt16LE()</b></code>, <code>bl.<b>readUInt16BE()</b></code>, <code>bl.<b>readUInt16LE()</b></code>, <code>bl.<b>readInt8()</b></code>, <code>bl.<b>readUInt8()</b></code></a>
* <a href="#streams">Streams</a>
--------------------------------------------------------
<a name="ctor"></a>
### new BufferList([ callback | buffer | buffer array ])
The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream.
Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object.
`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with:
```js
var bl = require('bl')
var myinstance = bl()
// equivilant to:
var BufferList = require('bl')
var myinstance = new BufferList()
```
--------------------------------------------------------
<a name="length"></a>
### bl.length
Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list.
--------------------------------------------------------
<a name="append"></a>
### bl.append(buffer)
`append(buffer)` adds an additional buffer or BufferList to the internal list.
--------------------------------------------------------
<a name="get"></a>
### bl.get(index)
`get()` will return the byte at the specified index.
--------------------------------------------------------
<a name="slice"></a>
### bl.slice([ start, [ end ] ])
`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively.
If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer.
--------------------------------------------------------
<a name="copy"></a>
### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])
`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively.
--------------------------------------------------------
<a name="duplicate"></a>
### bl.duplicate()
`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example:
```js
var bl = new BufferList()
bl.append('hello')
bl.append(' world')
bl.append('\n')
bl.duplicate().pipe(process.stdout, { end: false })
console.log(bl.toString())
```
--------------------------------------------------------
<a name="consume"></a>
### bl.consume(bytes)
`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers&mdash;initial offsets will be calculated accordingly in order to give you a consistent view of the data.
--------------------------------------------------------
<a name="toString"></a>
### bl.toString([encoding, [ start, [ end ]]])
`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information.
--------------------------------------------------------
<a name="readXX"></a>
### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8()
All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently.
See the <b><code>[Buffer](http://nodejs.org/docs/latest/api/buffer.html)</code></b> documentation for how these work.
--------------------------------------------------------
<a name="streams"></a>
### Streams
**bl** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **bl** instance.
--------------------------------------------------------
## Contributors
**bl** is brought to you by the following hackers:
* [Rod Vagg](https://github.com/rvagg)
* [Matteo Collina](https://github.com/mcollina)
* [Jarett Cruger](https://github.com/jcrugzz)
=======
<a name="license"></a>
## License &amp; copyright
Copyright (c) 2013-2014 bl contributors (listed above).
bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.

216
node_modules/request/node_modules/bl/bl.js generated vendored Normal file
View File

@ -0,0 +1,216 @@
var DuplexStream = require('readable-stream/duplex')
, util = require('util')
function BufferList (callback) {
if (!(this instanceof BufferList))
return new BufferList(callback)
this._bufs = []
this.length = 0
if (typeof callback == 'function') {
this._callback = callback
var piper = function (err) {
if (this._callback) {
this._callback(err)
this._callback = null
}
}.bind(this)
this.on('pipe', function (src) {
src.on('error', piper)
})
this.on('unpipe', function (src) {
src.removeListener('error', piper)
})
}
else if (Buffer.isBuffer(callback))
this.append(callback)
else if (Array.isArray(callback)) {
callback.forEach(function (b) {
Buffer.isBuffer(b) && this.append(b)
}.bind(this))
}
DuplexStream.call(this)
}
util.inherits(BufferList, DuplexStream)
BufferList.prototype._offset = function (offset) {
var tot = 0, i = 0, _t
for (; i < this._bufs.length; i++) {
_t = tot + this._bufs[i].length
if (offset < _t)
return [ i, offset - tot ]
tot = _t
}
}
BufferList.prototype.append = function (buf) {
var isBuffer = Buffer.isBuffer(buf) ||
buf instanceof BufferList
this._bufs.push(isBuffer ? buf : new Buffer(buf))
this.length += buf.length
return this
}
BufferList.prototype._write = function (buf, encoding, callback) {
this.append(buf)
if (callback)
callback()
}
BufferList.prototype._read = function (size) {
if (!this.length)
return this.push(null)
size = Math.min(size, this.length)
this.push(this.slice(0, size))
this.consume(size)
}
BufferList.prototype.end = function (chunk) {
DuplexStream.prototype.end.call(this, chunk)
if (this._callback) {
this._callback(null, this.slice())
this._callback = null
}
}
BufferList.prototype.get = function (index) {
return this.slice(index, index + 1)[0]
}
BufferList.prototype.slice = function (start, end) {
return this.copy(null, 0, start, end)
}
BufferList.prototype.copy = function (dst, dstStart, srcStart, srcEnd) {
if (typeof srcStart != 'number' || srcStart < 0)
srcStart = 0
if (typeof srcEnd != 'number' || srcEnd > this.length)
srcEnd = this.length
if (srcStart >= this.length)
return dst || new Buffer(0)
if (srcEnd <= 0)
return dst || new Buffer(0)
var copy = !!dst
, off = this._offset(srcStart)
, len = srcEnd - srcStart
, bytes = len
, bufoff = (copy && dstStart) || 0
, start = off[1]
, l
, i
// copy/slice everything
if (srcStart === 0 && srcEnd == this.length) {
if (!copy) // slice, just return a full concat
return Buffer.concat(this._bufs)
// copy, need to copy individual buffers
for (i = 0; i < this._bufs.length; i++) {
this._bufs[i].copy(dst, bufoff)
bufoff += this._bufs[i].length
}
return dst
}
// easy, cheap case where it's a subset of one of the buffers
if (bytes <= this._bufs[off[0]].length - start) {
return copy
? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
: this._bufs[off[0]].slice(start, start + bytes)
}
if (!copy) // a slice, we need something to copy in to
dst = new Buffer(len)
for (i = off[0]; i < this._bufs.length; i++) {
l = this._bufs[i].length - start
if (bytes > l) {
this._bufs[i].copy(dst, bufoff, start)
} else {
this._bufs[i].copy(dst, bufoff, start, start + bytes)
break
}
bufoff += l
bytes -= l
if (start)
start = 0
}
return dst
}
BufferList.prototype.toString = function (encoding, start, end) {
return this.slice(start, end).toString(encoding)
}
BufferList.prototype.consume = function (bytes) {
while (this._bufs.length) {
if (bytes > this._bufs[0].length) {
bytes -= this._bufs[0].length
this.length -= this._bufs[0].length
this._bufs.shift()
} else {
this._bufs[0] = this._bufs[0].slice(bytes)
this.length -= bytes
break
}
}
return this
}
BufferList.prototype.duplicate = function () {
var i = 0
, copy = new BufferList()
for (; i < this._bufs.length; i++)
copy.append(this._bufs[i])
return copy
}
BufferList.prototype.destroy = function () {
this._bufs.length = 0;
this.length = 0;
this.push(null);
}
;(function () {
var methods = {
'readDoubleBE' : 8
, 'readDoubleLE' : 8
, 'readFloatBE' : 4
, 'readFloatLE' : 4
, 'readInt32BE' : 4
, 'readInt32LE' : 4
, 'readUInt32BE' : 4
, 'readUInt32LE' : 4
, 'readInt16BE' : 2
, 'readInt16LE' : 2
, 'readUInt16BE' : 2
, 'readUInt16LE' : 2
, 'readInt8' : 1
, 'readUInt8' : 1
}
for (var m in methods) {
(function (m) {
BufferList.prototype[m] = function (offset) {
return this.slice(offset, offset + methods[m])[m](0)
}
}(m))
}
}())
module.exports = BufferList

View File

@ -0,0 +1,5 @@
build/
test/
examples/
fs.js
zlib.js

View File

@ -0,0 +1,50 @@
sudo: false
language: node_js
before_install:
- npm install -g npm@2
- npm install -g npm
notifications:
email: false
matrix:
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: node
env: TASK=test
- node_js: node
env: TASK=browser BROWSER_NAME=opera BROWSER_VERSION="11..latest"
- node_js: node
env: TASK=browser BROWSER_NAME=ie BROWSER_VERSION="9..latest"
- node_js: node
env: TASK=browser BROWSER_NAME=chrome BROWSER_VERSION="41..beta"
- node_js: node
env: TASK=browser BROWSER_NAME=firefox BROWSER_VERSION="36..latest"
- node_js: node
env: TASK=browser BROWSER_NAME=ipad BROWSER_VERSION="['6.1', '7.1', '8.2']"
- node_js: node
env: TASK=browser BROWSER_NAME=iphone BROWSER_VERSION="['6.1', '7.1', '8.2']"
- node_js: node
env: TASK=browser BROWSER_NAME=safari BROWSER_VERSION="5..latest"
- node_js: node
env: TASK=browser BROWSER_NAME=android BROWSER_VERSION="4.0..latest"
script: "npm run $TASK"
env:
global:
- secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc=
- secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI=

View File

@ -0,0 +1 @@
ui: tape

View File

@ -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.

View File

@ -0,0 +1,36 @@
# readable-stream
***Node-core 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)) &lt;christopher.s.dickinson@gmail.com&gt;
- Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B
* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt;
- Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;rod@vagg.org&gt;
- Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D
* **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;newmansam@outlook.com&gt;
* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt;
* **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;d@domenic.me&gt;

File diff suppressed because it is too large Load Diff

View File

@ -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: +1s 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 were 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: were 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

View File

@ -0,0 +1 @@
module.exports = require("./lib/_stream_duplex.js")

View File

@ -0,0 +1,82 @@
// 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';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
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);
}
}

View File

@ -0,0 +1,27 @@
// 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');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
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);
};

View File

@ -0,0 +1,973 @@
'use strict';
module.exports = Readable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Readable.ReadableState = ReadableState;
var EE = require('events');
/*<replacement>*/
var EElistenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function (){try{
Stream = require('st' + 'ream');
}catch(_){}finally{
if (!Stream)
Stream = require('events').EventEmitter;
}}())
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var StringDecoder;
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
var 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;
// 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;
}
}
function Readable(options) {
var 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 {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
if (!addToFront)
state.reading = false;
// 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.readable) {
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;
}

View File

@ -0,0 +1,197 @@
// 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');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
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;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined)
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
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);
}

View File

@ -0,0 +1,527 @@
// 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;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function (){try{
Stream = require('st' + 'ream');
}catch(_){}finally{
if (!Stream)
Stream = require('events').EventEmitter;
}}())
/*</replacement>*/
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;
}
function WritableState(options, stream) {
var 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;
}
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(_){}}());
function Writable(options) {
var 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;
}
} 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) {
processNextTick(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 buffer = [];
var cbs = [];
while (entry) {
cbs.push(entry.callback);
buffer.push(entry);
entry = entry.next;
}
// count the one we are adding, as well.
// TODO(isaacs) clean this up
state.pendingcb++;
state.lastBufferedRequest = null;
doWrite(stream, state, true, state.length, buffer, '', function(err) {
for (var i = 0; i < cbs.length; i++) {
state.pendingcb--;
cbs[i](err);
}
});
// Clear buffer
} 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.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;
}

View File

@ -0,0 +1,3 @@
# core-util-is
The `util.is*` functions introduced in Node v0.12.

View File

@ -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;
-};
+}

View File

@ -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(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;
function isBuffer(arg) {
return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}

View File

@ -0,0 +1,54 @@
{
"name": "core-util-is",
"version": "1.0.1",
"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"
},
"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"
},
"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",
"_id": "core-util-is@1.0.1",
"dist": {
"shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538",
"tarball": "http://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz"
},
"_from": "core-util-is@>=1.0.0 <1.1.0",
"_npmVersion": "1.3.23",
"_npmUser": {
"name": "isaacs",
"email": "i@izs.me"
},
"maintainers": [
{
"name": "isaacs",
"email": "i@izs.me"
}
],
"directories": {},
"_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538",
"_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz",
"scripts": {}
}

View File

@ -0,0 +1,106 @@
// 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(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]';
}
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;
function isBuffer(arg) {
return arg instanceof Buffer;
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}

View File

@ -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.

View File

@ -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

View File

@ -0,0 +1 @@
module.exports = require('util').inherits

View File

@ -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
}
}

View File

@ -0,0 +1,50 @@
{
"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"
},
"license": "ISC",
"scripts": {
"test": "node test"
},
"bugs": {
"url": "https://github.com/isaacs/inherits/issues"
},
"_id": "inherits@2.0.1",
"dist": {
"shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1",
"tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz"
},
"_from": "inherits@>=2.0.1 <2.1.0",
"_npmVersion": "1.3.8",
"_npmUser": {
"name": "isaacs",
"email": "i@izs.me"
},
"maintainers": [
{
"name": "isaacs",
"email": "i@izs.me"
}
],
"directories": {},
"_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1",
"_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz",
"readme": "ERROR: No README data found!",
"homepage": "https://github.com/isaacs/inherits"
}

View File

@ -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')

View File

@ -0,0 +1,54 @@
# isarray
`Array#isArray` for older browsers.
## 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 &lt;julian@juliangruber.com&gt;
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.

View File

@ -0,0 +1,209 @@
/**
* Require the given path.
*
* @param {String} path
* @return {Object} exports
* @api public
*/
function require(path, parent, orig) {
var resolved = require.resolve(path);
// lookup failed
if (null == resolved) {
orig = orig || path;
parent = parent || 'root';
var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
err.path = orig;
err.parent = parent;
err.require = true;
throw err;
}
var module = require.modules[resolved];
// perform real require()
// by invoking the module's
// registered function
if (!module.exports) {
module.exports = {};
module.client = module.component = true;
module.call(this, module.exports, require.relative(resolved), module);
}
return module.exports;
}
/**
* Registered modules.
*/
require.modules = {};
/**
* Registered aliases.
*/
require.aliases = {};
/**
* Resolve `path`.
*
* Lookup:
*
* - PATH/index.js
* - PATH.js
* - PATH
*
* @param {String} path
* @return {String} path or null
* @api private
*/
require.resolve = function(path) {
if (path.charAt(0) === '/') path = path.slice(1);
var index = path + '/index.js';
var paths = [
path,
path + '.js',
path + '.json',
path + '/index.js',
path + '/index.json'
];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (require.modules.hasOwnProperty(path)) return path;
}
if (require.aliases.hasOwnProperty(index)) {
return require.aliases[index];
}
};
/**
* Normalize `path` relative to the current path.
*
* @param {String} curr
* @param {String} path
* @return {String}
* @api private
*/
require.normalize = function(curr, path) {
var segs = [];
if ('.' != path.charAt(0)) return path;
curr = curr.split('/');
path = path.split('/');
for (var i = 0; i < path.length; ++i) {
if ('..' == path[i]) {
curr.pop();
} else if ('.' != path[i] && '' != path[i]) {
segs.push(path[i]);
}
}
return curr.concat(segs).join('/');
};
/**
* Register module at `path` with callback `definition`.
*
* @param {String} path
* @param {Function} definition
* @api private
*/
require.register = function(path, definition) {
require.modules[path] = definition;
};
/**
* Alias a module definition.
*
* @param {String} from
* @param {String} to
* @api private
*/
require.alias = function(from, to) {
if (!require.modules.hasOwnProperty(from)) {
throw new Error('Failed to alias "' + from + '", it does not exist');
}
require.aliases[to] = from;
};
/**
* Return a require function relative to the `parent` path.
*
* @param {String} parent
* @return {Function}
* @api private
*/
require.relative = function(parent) {
var p = require.normalize(parent, '..');
/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.
*/
function localRequire(path) {
var resolved = localRequire.resolve(path);
return require(resolved, parent, path);
}
/**
* Resolve relative to the parent.
*/
localRequire.resolve = function(path) {
var c = path.charAt(0);
if ('/' == c) return path.slice(1);
if ('.' == c) return require.normalize(p, path);
// resolve deps by returning
// the dep in the nearest "deps"
// directory
var segs = parent.split('/');
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;
path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
return path;
};
/**
* Check if module is defined at `path`.
*/
localRequire.exists = function(path) {
return require.modules.hasOwnProperty(localRequire.resolve(path));
};
return localRequire;
};
require.register("isarray/index.js", function(exports, require, module){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
});
require.alias("isarray/index.js", "isarray/index.js");

View File

@ -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"
}

View File

@ -0,0 +1,3 @@
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};

View File

@ -0,0 +1,53 @@
{
"name": "isarray",
"description": "Array#isArray for older browsers",
"version": "0.0.1",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/isarray.git"
},
"homepage": "https://github.com/juliangruber/isarray",
"main": "index.js",
"scripts": {
"test": "tap test/*.js"
},
"dependencies": {},
"devDependencies": {
"tap": "*"
},
"keywords": [
"browser",
"isarray",
"array"
],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT",
"_id": "isarray@0.0.1",
"dist": {
"shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf",
"tarball": "http://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz"
},
"_from": "isarray@0.0.1",
"_npmVersion": "1.2.18",
"_npmUser": {
"name": "juliangruber",
"email": "julian@juliangruber.com"
},
"maintainers": [
{
"name": "juliangruber",
"email": "julian@juliangruber.com"
}
],
"directories": {},
"_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf",
"_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"bugs": {
"url": "https://github.com/juliangruber/isarray/issues"
},
"readme": "ERROR: No README data found!"
}

View File

@ -0,0 +1,7 @@
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.11"
- "0.12"
- "iojs"

View File

@ -0,0 +1,13 @@
'use strict';
module.exports = 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);
});
}

View File

@ -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.**

View File

@ -0,0 +1,45 @@
{
"name": "process-nextick-args",
"version": "1.0.3",
"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"
},
"gitHead": "e855846a69662b9489f1ad3dde1ebf2ccc4370b8",
"_id": "process-nextick-args@1.0.3",
"_shasum": "e272eed825d5e9f4ea74d8d73b1fe311c3beb630",
"_from": "process-nextick-args@>=1.0.0 <1.1.0",
"_npmVersion": "2.9.0",
"_nodeVersion": "2.5.0",
"_npmUser": {
"name": "cwmma",
"email": "calvin.metcalf@gmail.com"
},
"dist": {
"shasum": "e272eed825d5e9f4ea74d8d73b1fe311c3beb630",
"tarball": "http://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.3.tgz"
},
"maintainers": [
{
"name": "cwmma",
"email": "calvin.metcalf@gmail.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.3.tgz",
"readme": "ERROR: No README data found!"
}

View File

@ -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');
```

View File

@ -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);
});

View File

@ -0,0 +1,2 @@
build
test

View File

@ -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.

View File

@ -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.

Some files were not shown because too many files have changed in this diff Show More