modif comtabilite
This commit is contained in:
+59
-12
@@ -1,5 +1,56 @@
|
||||
## Change Log
|
||||
|
||||
### v2.87.0 (2018/05/21)
|
||||
- [#2943](https://github.com/request/request/pull/2943) Replace hawk dependency with a local implemenation (#2943) (@hueniverse)
|
||||
|
||||
### v2.86.0 (2018/05/15)
|
||||
- [#2885](https://github.com/request/request/pull/2885) Remove redundant code (for Node.js 0.9.4 and below) and dependency (@ChALkeR)
|
||||
- [#2942](https://github.com/request/request/pull/2942) Make Test GREEN Again! (@simov)
|
||||
- [#2923](https://github.com/request/request/pull/2923) Alterations for failing CI tests (@gareth-robinson)
|
||||
|
||||
### v2.85.0 (2018/03/12)
|
||||
- [#2880](https://github.com/request/request/pull/2880) Revert "Update hawk to 7.0.7 (#2880)" (@simov)
|
||||
|
||||
### v2.84.0 (2018/03/12)
|
||||
- [#2793](https://github.com/request/request/pull/2793) Fixed calculation of oauth_body_hash, issue #2792 (@dvishniakov)
|
||||
- [#2880](https://github.com/request/request/pull/2880) Update hawk to 7.0.7 (#2880) (@kornel-kedzierski)
|
||||
|
||||
### v2.83.0 (2017/09/27)
|
||||
- [#2776](https://github.com/request/request/pull/2776) Updating tough-cookie due to security fix. (#2776) (@karlnorling)
|
||||
|
||||
### v2.82.0 (2017/09/19)
|
||||
- [#2703](https://github.com/request/request/pull/2703) Add Node.js v8 to Travis CI (@ryysud)
|
||||
- [#2751](https://github.com/request/request/pull/2751) Update of hawk and qs to latest version (#2751) (@Olivier-Moreau)
|
||||
- [#2658](https://github.com/request/request/pull/2658) Fixed some text in README.md (#2658) (@Marketionist)
|
||||
- [#2635](https://github.com/request/request/pull/2635) chore(package): update aws-sign2 to version 0.7.0 (#2635) (@greenkeeperio-bot)
|
||||
- [#2641](https://github.com/request/request/pull/2641) Update README to simplify & update convenience methods (#2641) (@FredKSchott)
|
||||
- [#2541](https://github.com/request/request/pull/2541) Add convenience method for HTTP OPTIONS (#2541) (@jamesseanwright)
|
||||
- [#2605](https://github.com/request/request/pull/2605) Add promise support section to README (#2605) (@FredKSchott)
|
||||
- [#2579](https://github.com/request/request/pull/2579) refactor(lint): replace eslint with standard (#2579) (@ahmadnassri)
|
||||
- [#2598](https://github.com/request/request/pull/2598) Update codecov to version 2.0.2 🚀 (@greenkeeperio-bot)
|
||||
- [#2590](https://github.com/request/request/pull/2590) Adds test-timing keepAlive test (@nicjansma)
|
||||
- [#2589](https://github.com/request/request/pull/2589) fix tabulation on request example README.MD (@odykyi)
|
||||
- [#2594](https://github.com/request/request/pull/2594) chore(dependencies): har-validator to 5.x [removes babel dep] (@ahmadnassri)
|
||||
|
||||
### v2.81.0 (2017/03/09)
|
||||
- [#2584](https://github.com/request/request/pull/2584) Security issue: Upgrade qs to version 6.4.0 (@sergejmueller)
|
||||
- [#2578](https://github.com/request/request/pull/2578) safe-buffer doesn't zero-fill by default, its just a polyfill. (#2578) (@mikeal)
|
||||
- [#2566](https://github.com/request/request/pull/2566) Timings: Tracks 'lookup', adds 'wait' time, fixes connection re-use (#2566) (@nicjansma)
|
||||
- [#2574](https://github.com/request/request/pull/2574) Migrating to safe-buffer for improved security. (@mikeal)
|
||||
- [#2573](https://github.com/request/request/pull/2573) fixes #2572 (@ahmadnassri)
|
||||
|
||||
### v2.80.0 (2017/03/04)
|
||||
- [#2571](https://github.com/request/request/pull/2571) Correctly format the Host header for IPv6 addresses (@JamesMGreene)
|
||||
- [#2558](https://github.com/request/request/pull/2558) Update README.md example snippet (@FredKSchott)
|
||||
- [#2221](https://github.com/request/request/pull/2221) Adding a simple Response object reference in argument specification (@calamarico)
|
||||
- [#2452](https://github.com/request/request/pull/2452) Adds .timings array with DNC, TCP, request and response times (@nicjansma)
|
||||
- [#2553](https://github.com/request/request/pull/2553) add ISSUE_TEMPLATE, move PR template (@FredKSchott)
|
||||
- [#2539](https://github.com/request/request/pull/2539) Create PULL_REQUEST_TEMPLATE.md (@FredKSchott)
|
||||
- [#2524](https://github.com/request/request/pull/2524) Update caseless to version 0.12.0 🚀 (@greenkeeperio-bot)
|
||||
- [#2460](https://github.com/request/request/pull/2460) Fix wrong MIME type in example (@OwnageIsMagic)
|
||||
- [#2514](https://github.com/request/request/pull/2514) Change tags to keywords in package.json (@humphd)
|
||||
- [#2492](https://github.com/request/request/pull/2492) More lenient gzip decompression (@addaleax)
|
||||
|
||||
### v2.79.0 (2016/11/18)
|
||||
- [#2368](https://github.com/request/request/pull/2368) Fix typeof check in test-pool.js (@forivall)
|
||||
- [#2394](https://github.com/request/request/pull/2394) Use `files` in package.json (@SimenB)
|
||||
@@ -108,7 +159,7 @@
|
||||
- [#1902](https://github.com/request/request/pull/1902) node-uuid@1.4.7 breaks build 🚨 (@greenkeeperio-bot)
|
||||
- [#1894](https://github.com/request/request/pull/1894) Fix tunneling after redirection from https (Original: #1881) (@simov, @falms)
|
||||
- [#1893](https://github.com/request/request/pull/1893) Update eslint to version 1.9.0 🚀 (@greenkeeperio-bot)
|
||||
- [#1852](https://github.com/request/request/pull/1852) Update eslint to version 1.7.3 🚀 (@simov, @greenkeeperio-bot, @paulomcnally, @michelsalib, @arbaaz, @vladimirich, @LoicMahieu, @JoshWillik, @jzaefferer, @ryanwholey, @djchie, @thisconnect, @mgenereu, @acroca, @Sebmaster, @KoltesDigital)
|
||||
- [#1852](https://github.com/request/request/pull/1852) Update eslint to version 1.7.3 🚀 (@simov, @greenkeeperio-bot, @paulomcnally, @michelsalib, @arbaaz, @nsklkn, @LoicMahieu, @JoshWillik, @jzaefferer, @ryanwholey, @djchie, @thisconnect, @mgenereu, @acroca, @Sebmaster, @KoltesDigital)
|
||||
- [#1876](https://github.com/request/request/pull/1876) Implement loose matching for har mime types (@simov)
|
||||
- [#1875](https://github.com/request/request/pull/1875) Update bluebird to version 3.0.2 🚀 (@simov, @greenkeeperio-bot)
|
||||
- [#1871](https://github.com/request/request/pull/1871) Update browserify to version 12.0.1 🚀 (@greenkeeperio-bot)
|
||||
@@ -152,7 +203,7 @@
|
||||
- [#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)
|
||||
- [#1746](https://github.com/request/request/pull/1746) Missed comma in Readme (@nsklkn)
|
||||
- [#1743](https://github.com/request/request/pull/1743) Fix options not being initialized in defaults method (@simov)
|
||||
|
||||
### v2.61.0 (2015/08/19)
|
||||
@@ -169,7 +220,8 @@
|
||||
- [#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)
|
||||
- [#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)
|
||||
@@ -430,7 +482,7 @@
|
||||
- [#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)
|
||||
- [#996](https://github.com/request/request/pull/996) Wrong oauth signature when multiple same param keys exist [updated] (@bengl)
|
||||
|
||||
### v2.40.0 (2014/08/06)
|
||||
- [#992](https://github.com/request/request/pull/992) Fix security vulnerability. Update qs (@poeticninja)
|
||||
@@ -496,15 +548,10 @@
|
||||
- [#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)
|
||||
@@ -538,10 +585,10 @@
|
||||
- [#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)
|
||||
- [#521](https://github.com/request/request/pull/521) Improving test-localAddress.js (@noway)
|
||||
- [#529](https://github.com/request/request/pull/529) dependencies versions bump (@jodaka)
|
||||
- [#523](https://github.com/request/request/pull/523) Updating dependencies (@noway421)
|
||||
- [#520](https://github.com/request/request/pull/520) Fixing test-tunnel.js (@noway421)
|
||||
- [#523](https://github.com/request/request/pull/523) Updating dependencies (@noway)
|
||||
- [#520](https://github.com/request/request/pull/520) Fixing test-tunnel.js (@noway)
|
||||
- [#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)
|
||||
|
||||
+85
-86
@@ -18,16 +18,17 @@ Request is designed to be the simplest way possible to make http calls. It suppo
|
||||
```js
|
||||
var request = require('request');
|
||||
request('http://www.google.com', function (error, response, body) {
|
||||
if (!error && response.statusCode == 200) {
|
||||
console.log(body) // Show the HTML for the Google homepage.
|
||||
}
|
||||
})
|
||||
console.log('error:', error); // Print the error if one occurred
|
||||
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
|
||||
console.log('body:', body); // Print the HTML for the Google homepage.
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## Table of contents
|
||||
|
||||
- [Streaming](#streaming)
|
||||
- [Promises & Async/Await](#promises--asyncawait)
|
||||
- [Forms](#forms)
|
||||
- [HTTP Authentication](#http-authentication)
|
||||
- [Custom HTTP Headers](#custom-http-headers)
|
||||
@@ -142,6 +143,22 @@ You can still use intermediate proxies, the requests will still follow HTTP forw
|
||||
---
|
||||
|
||||
|
||||
## Promises & Async/Await
|
||||
|
||||
`request` supports both streaming and callback interfaces natively. If you'd like `request` to return a Promise instead, you can use an alternative interface wrapper for `request`. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use `async`/`await` in ES2017.
|
||||
|
||||
Several alternative interfaces are provided by the request team, including:
|
||||
- [`request-promise`](https://github.com/request/request-promise) (uses [Bluebird](https://github.com/petkaantonov/bluebird) Promises)
|
||||
- [`request-promise-native`](https://github.com/request/request-promise-native) (uses native Promises)
|
||||
- [`request-promise-any`](https://github.com/request/request-promise-any) (uses [any-promise](https://www.npmjs.com/package/any-promise) Promises)
|
||||
|
||||
|
||||
[back to top](#table-of-contents)
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Forms
|
||||
|
||||
`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
|
||||
@@ -170,7 +187,7 @@ var formData = {
|
||||
// Pass a simple key-value pair
|
||||
my_field: 'my_value',
|
||||
// Pass data via Buffers
|
||||
my_buffer: new Buffer([1, 2, 3]),
|
||||
my_buffer: Buffer.from([1, 2, 3]),
|
||||
// Pass data via Streams
|
||||
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
|
||||
// Pass multiple values /w an Array
|
||||
@@ -185,7 +202,7 @@ var formData = {
|
||||
value: fs.createReadStream('/dev/urandom'),
|
||||
options: {
|
||||
filename: 'topsecret.jpg',
|
||||
contentType: 'image/jpg'
|
||||
contentType: 'image/jpeg'
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -204,7 +221,7 @@ For advanced cases, you can access the form-data object itself via `r.form()`. T
|
||||
var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
|
||||
var form = r.form();
|
||||
form.append('my_field', 'my_value');
|
||||
form.append('my_buffer', new Buffer([1, 2, 3]));
|
||||
form.append('my_buffer', Buffer.from([1, 2, 3]));
|
||||
form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
|
||||
```
|
||||
See the [form-data README](https://github.com/form-data/form-data) for more information & examples.
|
||||
@@ -287,13 +304,13 @@ The method form takes parameters
|
||||
`auth(username, password, sendImmediately, bearer)`.
|
||||
|
||||
`sendImmediately` defaults to `true`, which causes a basic or bearer
|
||||
authentication header to be sent. If `sendImmediately` is `false`, then
|
||||
authentication header to be sent. If `sendImmediately` is `false`, then
|
||||
`request` will retry with a proper authentication header after receiving a
|
||||
`401` response from the server (which must contain a `WWW-Authenticate` header
|
||||
indicating the required authentication method).
|
||||
|
||||
Note that you can also specify basic authentication using the URL itself, as
|
||||
detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the
|
||||
detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the
|
||||
`user:password` before the host with an `@` sign:
|
||||
|
||||
```js
|
||||
@@ -358,7 +375,7 @@ request(options, callback);
|
||||
|
||||
## OAuth Signing
|
||||
|
||||
[OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The
|
||||
[OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The
|
||||
default signing algorithm is
|
||||
[HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2):
|
||||
|
||||
@@ -477,7 +494,7 @@ See [the wikipedia page on HTTP Tunneling](https://en.wikipedia.org/wiki/HTTP_tu
|
||||
for more information.
|
||||
|
||||
By default, when proxying `http` traffic, request will simply make a
|
||||
standard proxied `http` request. This is done by making the `url`
|
||||
standard proxied `http` request. This is done by making the `url`
|
||||
section of the initial line of the request a fully qualified url to
|
||||
the endpoint.
|
||||
|
||||
@@ -493,7 +510,7 @@ request body or whatever
|
||||
|
||||
Because a pure "http over http" tunnel offers no additional security
|
||||
or other features, it is generally simpler to go with a
|
||||
straightforward HTTP proxy in this case. However, if you would like
|
||||
straightforward HTTP proxy in this case. However, if you would like
|
||||
to force a tunneling proxy, you may set the `tunnel` option to `true`.
|
||||
|
||||
You can also make a standard proxied `http` request by explicitly setting
|
||||
@@ -608,7 +625,7 @@ request.get(options);
|
||||
|
||||
### Using `options.agentOptions`
|
||||
|
||||
In the example below, we call an API requires client side SSL certificate
|
||||
In the example below, we call an API that requires client side SSL certificate
|
||||
(in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:
|
||||
|
||||
```js
|
||||
@@ -667,7 +684,7 @@ request.get({
|
||||
|
||||
The `options.har` property will override the values: `url`, `method`, `qs`, `headers`, `form`, `formData`, `body`, `json`, as well as construct multipart data and read files from disk when `request.postData.params[].fileName` is present without a matching `value`.
|
||||
|
||||
a validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
|
||||
A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
|
||||
|
||||
```js
|
||||
var request = require('request')
|
||||
@@ -717,7 +734,7 @@ a validation step will check if the HAR Request format matches the latest spec (
|
||||
The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.
|
||||
|
||||
- `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()`
|
||||
- `baseUrl` - fully qualified uri string used as the base url. Most useful with `request.defaults`, for example when you want to do many requests to the same domain. If `baseUrl` is `https://example.com/api/`, then requesting `/end/point?test=true` will fetch `https://example.com/api/end/point?test=true`. When `baseUrl` is given, `uri` must also be a string.
|
||||
- `baseUrl` - fully qualified uri string used as the base url. Most useful with `request.defaults`, for example when you want to do many requests to the same domain. If `baseUrl` is `https://example.com/api/`, then requesting `/end/point?test=true` will fetch `https://example.com/api/end/point?test=true`. When `baseUrl` is given, `uri` must also be a string.
|
||||
- `method` - http method (default: `"GET"`)
|
||||
- `headers` - http headers (default: `{}`)
|
||||
|
||||
@@ -726,8 +743,8 @@ The first argument can be either a `url` or an `options` object. The only requir
|
||||
- `qs` - object containing querystring values to be appended to the `uri`
|
||||
- `qsParseOptions` - object containing options to pass to the [qs.parse](https://github.com/hapijs/qs#parsing-objects) method. Alternatively pass options to the [querystring.parse](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_parse_str_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`
|
||||
- `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`. For example, to change the way arrays are converted to query strings using the `qs` module pass the `arrayFormat` option with one of `indices|brackets|repeat`
|
||||
- `useQuerystring` - If true, use `querystring` to stringify and parse
|
||||
querystrings, otherwise use `qs` (default: `false`). Set this option to
|
||||
- `useQuerystring` - if true, use `querystring` to stringify and parse
|
||||
querystrings, otherwise use `qs` (default: `false`). Set this option to
|
||||
`true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the
|
||||
default `foo[0]=bar&foo[1]=baz`.
|
||||
|
||||
@@ -735,7 +752,7 @@ The first argument can be either a `url` or an `options` object. The only requir
|
||||
|
||||
- `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer`, `String` or `ReadStream`. If `json` is `true`, then `body` must be a JSON-serializable object.
|
||||
- `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded` header. When passed no options, a `FormData` instance is returned (and is piped to request). See "Forms" section above.
|
||||
- `formData` - Data to pass for a `multipart/form-data` request. See
|
||||
- `formData` - data to pass for a `multipart/form-data` request. See
|
||||
[Forms](#forms) section above.
|
||||
- `multipart` - array of objects which contain their own headers and `body`
|
||||
attributes. Sends a `multipart/related` request. See [Forms](#forms) section
|
||||
@@ -746,17 +763,17 @@ The first argument can be either a `url` or an `options` object. The only requir
|
||||
In non-chunked requests, data items with body streams are not allowed.
|
||||
- `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request.
|
||||
- `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request.
|
||||
- `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
|
||||
- `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
|
||||
- `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body.
|
||||
- `jsonReplacer` - a [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that will be passed to `JSON.stringify()` when stringifying a JSON request body.
|
||||
|
||||
---
|
||||
|
||||
- `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
|
||||
- `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.
|
||||
- `hawk` - Options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
|
||||
- `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`, and optionally `session` (note that this only works for services that require session as part of the canonical string). Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. **Note:** you need to `npm install aws4` first.
|
||||
- `httpSignature` - Options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
|
||||
- `auth` - a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
|
||||
- `oauth` - options for OAuth HMAC-SHA1 signing. See documentation above.
|
||||
- `hawk` - options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
|
||||
- `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`, and optionally `session` (note that this only works for services that require session as part of the canonical string). Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. If you are using SigV4, you can also include a `service` property that specifies the service name. **Note:** you need to `npm install aws4` first.
|
||||
- `httpSignature` - options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
|
||||
|
||||
---
|
||||
|
||||
@@ -768,9 +785,9 @@ The first argument can be either a `url` or an `options` object. The only requir
|
||||
|
||||
---
|
||||
|
||||
- `encoding` - Encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.)
|
||||
- `gzip` - If `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below.
|
||||
- `jar` - If `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
|
||||
- `encoding` - encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.)
|
||||
- `gzip` - if `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below.
|
||||
- `jar` - if `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
|
||||
|
||||
---
|
||||
|
||||
@@ -778,14 +795,14 @@ The first argument can be either a `url` or an `options` object. The only requir
|
||||
- `agentClass` - alternatively specify your agent's class name
|
||||
- `agentOptions` - and pass its options. **Note:** for HTTPS see [tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) and the [documentation above](#using-optionsagentoptions).
|
||||
- `forever` - set to `true` to use the [forever-agent](https://github.com/request/forever-agent) **Note:** Defaults to `http(s).Agent({keepAlive:true})` in node 0.12+
|
||||
- `pool` - An object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified.
|
||||
- `pool` - an object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified.
|
||||
- A `maxSockets` property can also be provided on the `pool` object to set the max number of sockets for all agents created (ex: `pool: {maxSockets: Infinity}`).
|
||||
- Note that if you are sending multiple requests in a loop and creating
|
||||
multiple new `pool` objects, `maxSockets` will not work as intended. To
|
||||
multiple new `pool` objects, `maxSockets` will not work as intended. To
|
||||
work around this, either use [`request.defaults`](#requestdefaultsoptions)
|
||||
with your pool options or create the pool object with the `maxSockets`
|
||||
property outside of the loop.
|
||||
- `timeout` - Integer containing the number of milliseconds to wait for a
|
||||
- `timeout` - integer containing the number of milliseconds to wait for a
|
||||
server to send response headers (and start the response body) before aborting
|
||||
the request. Note that if the underlying TCP connection cannot be established,
|
||||
the OS-wide TCP connection timeout will overrule the `timeout` option ([the
|
||||
@@ -795,9 +812,9 @@ default in Linux can be anywhere from 20-120 seconds][linux-timeout]).
|
||||
|
||||
---
|
||||
|
||||
- `localAddress` - Local interface to bind for network connections.
|
||||
- `proxy` - An HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)
|
||||
- `strictSSL` - If `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
|
||||
- `localAddress` - local interface to bind for network connections.
|
||||
- `proxy` - an HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)
|
||||
- `strictSSL` - if `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
|
||||
- `tunnel` - controls the behavior of
|
||||
[HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling)
|
||||
as follows:
|
||||
@@ -805,21 +822,38 @@ default in Linux can be anywhere from 20-120 seconds][linux-timeout]).
|
||||
- `true` - always tunnel to the destination by making a `CONNECT` request to
|
||||
the proxy
|
||||
- `false` - request the destination as a `GET` request.
|
||||
- `proxyHeaderWhiteList` - A whitelist of headers to send to a
|
||||
- `proxyHeaderWhiteList` - a whitelist of headers to send to a
|
||||
tunneling proxy.
|
||||
- `proxyHeaderExclusiveList` - A whitelist of headers to send
|
||||
- `proxyHeaderExclusiveList` - a whitelist of headers to send
|
||||
exclusively to a tunneling proxy and not to destination.
|
||||
|
||||
---
|
||||
|
||||
- `time` - If `true`, the request-response cycle (including all redirects) is timed at millisecond resolution, and the result provided on the response's `elapsedTime` property. The `responseStartTime` property is also available to indicate the timestamp when the response begins.
|
||||
- `har` - A [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)*
|
||||
- `time` - if `true`, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object:
|
||||
- `elapsedTime` Duration of the entire request/response in milliseconds (*deprecated*).
|
||||
- `responseStartTime` Timestamp when the response began (in Unix Epoch milliseconds) (*deprecated*).
|
||||
- `timingStart` Timestamp of the start of the request (in Unix Epoch milliseconds).
|
||||
- `timings` Contains event timestamps in millisecond resolution relative to `timingStart`. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
|
||||
- `socket` Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_socket) module's `socket` event fires. This happens when the socket is assigned to the request.
|
||||
- `lookup` Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_lookup) module's `lookup` event fires. This happens when the DNS has been resolved.
|
||||
- `connect`: Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_connect) module's `connect` event fires. This happens when the server acknowledges the TCP connection.
|
||||
- `response`: Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_response) module's `response` event fires. This happens when the first bytes are received from the server.
|
||||
- `end`: Relative timestamp when the last bytes of the response are received.
|
||||
- `timingPhases` Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
|
||||
- `wait`: Duration of socket initialization (`timings.socket`)
|
||||
- `dns`: Duration of DNS lookup (`timings.lookup` - `timings.socket`)
|
||||
- `tcp`: Duration of TCP connection (`timings.connect` - `timings.socket`)
|
||||
- `firstByte`: Duration of HTTP server response (`timings.response` - `timings.connect`)
|
||||
- `download`: Duration of HTTP download (`timings.end` - `timings.response`)
|
||||
- `total`: Duration entire HTTP round-trip (`timings.end`)
|
||||
|
||||
- `har` - a [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)*
|
||||
- `callback` - alternatively pass the request's callback in the options object
|
||||
|
||||
The callback argument gets 3 arguments:
|
||||
|
||||
1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object)
|
||||
2. An [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) object
|
||||
2. An [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) object (Response object)
|
||||
3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied)
|
||||
|
||||
[back to top](#table-of-contents)
|
||||
@@ -857,55 +891,19 @@ var specialRequest = baseRequest.defaults({
|
||||
})
|
||||
```
|
||||
|
||||
### request.put
|
||||
### request.METHOD()
|
||||
|
||||
Same as `request()`, but defaults to `method: "PUT"`.
|
||||
These HTTP method convenience functions act just like `request()` but with a default method already set for you:
|
||||
|
||||
```js
|
||||
request.put(url)
|
||||
```
|
||||
- *request.get()*: Defaults to `method: "GET"`.
|
||||
- *request.post()*: Defaults to `method: "POST"`.
|
||||
- *request.put()*: Defaults to `method: "PUT"`.
|
||||
- *request.patch()*: Defaults to `method: "PATCH"`.
|
||||
- *request.del() / request.delete()*: Defaults to `method: "DELETE"`.
|
||||
- *request.head()*: Defaults to `method: "HEAD"`.
|
||||
- *request.options()*: Defaults to `method: "OPTIONS"`.
|
||||
|
||||
### request.patch
|
||||
|
||||
Same as `request()`, but defaults to `method: "PATCH"`.
|
||||
|
||||
```js
|
||||
request.patch(url)
|
||||
```
|
||||
|
||||
### request.post
|
||||
|
||||
Same as `request()`, but defaults to `method: "POST"`.
|
||||
|
||||
```js
|
||||
request.post(url)
|
||||
```
|
||||
|
||||
### request.head
|
||||
|
||||
Same as `request()`, but defaults to `method: "HEAD"`.
|
||||
|
||||
```js
|
||||
request.head(url)
|
||||
```
|
||||
|
||||
### request.del / request.delete
|
||||
|
||||
Same as `request()`, but defaults to `method: "DELETE"`.
|
||||
|
||||
```js
|
||||
request.del(url)
|
||||
request.delete(url)
|
||||
```
|
||||
|
||||
### request.get
|
||||
|
||||
Same as `request()` (for uniformity).
|
||||
|
||||
```js
|
||||
request.get(url)
|
||||
```
|
||||
### request.cookie
|
||||
### request.cookie()
|
||||
|
||||
Function that creates a new cookie.
|
||||
|
||||
@@ -1002,7 +1000,7 @@ request.get('http://10.255.255.1', {timeout: 1500}, function(err) {
|
||||
```
|
||||
|
||||
For backwards-compatibility, response compression is not supported by default.
|
||||
To accept gzip-compressed responses, set the `gzip` option to `true`. Note
|
||||
To accept gzip-compressed responses, set the `gzip` option to `true`. Note
|
||||
that the body data passed through `request` is automatically decompressed
|
||||
while the response object is unmodified and will contain compressed data if
|
||||
the server sent a compressed response.
|
||||
@@ -1019,7 +1017,8 @@ the server sent a compressed response.
|
||||
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
|
||||
console.log('the decoded data is: ' + body)
|
||||
}
|
||||
).on('data', function(data) {
|
||||
)
|
||||
.on('data', function(data) {
|
||||
// decompressed data as it is received
|
||||
console.log('decoded chunk: ' + data)
|
||||
})
|
||||
|
||||
+13
-14
@@ -14,15 +14,14 @@
|
||||
|
||||
'use strict'
|
||||
|
||||
var extend = require('extend')
|
||||
, cookies = require('./lib/cookies')
|
||||
, helpers = require('./lib/helpers')
|
||||
var extend = require('extend')
|
||||
var cookies = require('./lib/cookies')
|
||||
var helpers = require('./lib/helpers')
|
||||
|
||||
var paramsHaveRequestBody = helpers.paramsHaveRequestBody
|
||||
|
||||
|
||||
// organize params for patch, post, put, head, del
|
||||
function initParams(uri, options, callback) {
|
||||
function initParams (uri, options, callback) {
|
||||
if (typeof options === 'function') {
|
||||
callback = options
|
||||
}
|
||||
@@ -66,6 +65,7 @@ function verbFunc (verb) {
|
||||
// define like this to please codeintel/intellisense IDEs
|
||||
request.get = verbFunc('get')
|
||||
request.head = verbFunc('head')
|
||||
request.options = verbFunc('options')
|
||||
request.post = verbFunc('post')
|
||||
request.put = verbFunc('put')
|
||||
request.patch = verbFunc('patch')
|
||||
@@ -81,7 +81,6 @@ request.cookie = function (str) {
|
||||
}
|
||||
|
||||
function wrapRequestMethod (method, options, requester, verb) {
|
||||
|
||||
return function (uri, opts, callback) {
|
||||
var params = initParams(uri, opts, callback)
|
||||
|
||||
@@ -112,15 +111,15 @@ request.defaults = function (options, requester) {
|
||||
options = {}
|
||||
}
|
||||
|
||||
var defaults = wrapRequestMethod(self, options, requester)
|
||||
var defaults = wrapRequestMethod(self, options, requester)
|
||||
|
||||
var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
|
||||
verbs.forEach(function(verb) {
|
||||
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
|
||||
verbs.forEach(function (verb) {
|
||||
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
|
||||
})
|
||||
|
||||
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
|
||||
defaults.jar = self.jar
|
||||
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
|
||||
defaults.jar = self.jar
|
||||
defaults.defaults = self.defaults
|
||||
return defaults
|
||||
}
|
||||
@@ -146,11 +145,11 @@ request.initParams = initParams
|
||||
|
||||
// Backwards compatibility for request.debug
|
||||
Object.defineProperty(request, 'debug', {
|
||||
enumerable : true,
|
||||
get : function() {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return request.Request.debug
|
||||
},
|
||||
set : function(debug) {
|
||||
set: function (debug) {
|
||||
request.Request.debug = debug
|
||||
}
|
||||
})
|
||||
|
||||
+5
-6
@@ -1,12 +1,11 @@
|
||||
'use strict'
|
||||
|
||||
var caseless = require('caseless')
|
||||
, uuid = require('uuid')
|
||||
, helpers = require('./helpers')
|
||||
var uuid = require('uuid/v4')
|
||||
var helpers = require('./helpers')
|
||||
|
||||
var md5 = helpers.md5
|
||||
, toBase64 = helpers.toBase64
|
||||
|
||||
var toBase64 = helpers.toBase64
|
||||
|
||||
function Auth (request) {
|
||||
// define all public properties here
|
||||
@@ -126,7 +125,7 @@ Auth.prototype.digest = function (method, path, authHeader) {
|
||||
|
||||
Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
|
||||
var self = this
|
||||
, request = self.request
|
||||
var request = self.request
|
||||
|
||||
var authHeader
|
||||
if (bearer === undefined && user === undefined) {
|
||||
@@ -143,7 +142,7 @@ Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
|
||||
|
||||
Auth.prototype.onResponse = function (response) {
|
||||
var self = this
|
||||
, request = self.request
|
||||
var request = self.request
|
||||
|
||||
if (!self.hasAuth || self.sentAuth) { return null }
|
||||
|
||||
|
||||
+7
-8
@@ -3,10 +3,9 @@
|
||||
var tough = require('tough-cookie')
|
||||
|
||||
var Cookie = tough.Cookie
|
||||
, CookieJar = tough.CookieJar
|
||||
var CookieJar = tough.CookieJar
|
||||
|
||||
|
||||
exports.parse = function(str) {
|
||||
exports.parse = function (str) {
|
||||
if (str && str.uri) {
|
||||
str = str.uri
|
||||
}
|
||||
@@ -17,23 +16,23 @@ exports.parse = function(str) {
|
||||
}
|
||||
|
||||
// Adapt the sometimes-Async api of tough.CookieJar to our requirements
|
||||
function RequestJar(store) {
|
||||
function RequestJar (store) {
|
||||
var self = this
|
||||
self._jar = new CookieJar(store, {looseMode: true})
|
||||
}
|
||||
RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
|
||||
RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
|
||||
var self = this
|
||||
return self._jar.setCookieSync(cookieOrStr, uri, options || {})
|
||||
}
|
||||
RequestJar.prototype.getCookieString = function(uri) {
|
||||
RequestJar.prototype.getCookieString = function (uri) {
|
||||
var self = this
|
||||
return self._jar.getCookieStringSync(uri)
|
||||
}
|
||||
RequestJar.prototype.getCookies = function(uri) {
|
||||
RequestJar.prototype.getCookies = function (uri) {
|
||||
var self = this
|
||||
return self._jar.getCookiesSync(uri)
|
||||
}
|
||||
|
||||
exports.jar = function(store) {
|
||||
exports.jar = function (store) {
|
||||
return new RequestJar(store)
|
||||
}
|
||||
|
||||
+18
-18
@@ -1,33 +1,33 @@
|
||||
'use strict'
|
||||
|
||||
function formatHostname(hostname) {
|
||||
function formatHostname (hostname) {
|
||||
// canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
|
||||
return hostname.replace(/^\.*/, '.').toLowerCase()
|
||||
}
|
||||
|
||||
function parseNoProxyZone(zone) {
|
||||
function parseNoProxyZone (zone) {
|
||||
zone = zone.trim().toLowerCase()
|
||||
|
||||
var zoneParts = zone.split(':', 2)
|
||||
, zoneHost = formatHostname(zoneParts[0])
|
||||
, zonePort = zoneParts[1]
|
||||
, hasPort = zone.indexOf(':') > -1
|
||||
var zoneHost = formatHostname(zoneParts[0])
|
||||
var zonePort = zoneParts[1]
|
||||
var hasPort = zone.indexOf(':') > -1
|
||||
|
||||
return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
|
||||
}
|
||||
|
||||
function uriInNoProxy(uri, noProxy) {
|
||||
function uriInNoProxy (uri, noProxy) {
|
||||
var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
|
||||
, hostname = formatHostname(uri.hostname)
|
||||
, noProxyList = noProxy.split(',')
|
||||
var hostname = formatHostname(uri.hostname)
|
||||
var noProxyList = noProxy.split(',')
|
||||
|
||||
// iterate through the noProxyList until it finds a match.
|
||||
return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
|
||||
return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
|
||||
var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
|
||||
, hostnameMatched = (
|
||||
isMatchedAt > -1 &&
|
||||
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
|
||||
)
|
||||
var hostnameMatched = (
|
||||
isMatchedAt > -1 &&
|
||||
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
|
||||
)
|
||||
|
||||
if (noProxyZone.hasPort) {
|
||||
return (port === noProxyZone.port) && hostnameMatched
|
||||
@@ -37,7 +37,7 @@ function uriInNoProxy(uri, noProxy) {
|
||||
})
|
||||
}
|
||||
|
||||
function getProxyFromURI(uri) {
|
||||
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)
|
||||
@@ -60,14 +60,14 @@ function getProxyFromURI(uri) {
|
||||
|
||||
if (uri.protocol === 'http:') {
|
||||
return process.env.HTTP_PROXY ||
|
||||
process.env.http_proxy || null
|
||||
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
|
||||
process.env.https_proxy ||
|
||||
process.env.HTTP_PROXY ||
|
||||
process.env.http_proxy || null
|
||||
}
|
||||
|
||||
// if none of that works, return null
|
||||
|
||||
+5
-15
@@ -71,14 +71,10 @@ Har.prototype.prep = function (data) {
|
||||
'multipart/related',
|
||||
'multipart/form-data',
|
||||
'multipart/alternative'])) {
|
||||
|
||||
// reset values
|
||||
data.postData.mimeType = 'multipart/form-data'
|
||||
}
|
||||
|
||||
else if (some([
|
||||
} else if (some([
|
||||
'application/x-www-form-urlencoded'])) {
|
||||
|
||||
if (!data.postData.params) {
|
||||
data.postData.text = ''
|
||||
} else {
|
||||
@@ -87,14 +83,11 @@ Har.prototype.prep = function (data) {
|
||||
// always overwrite
|
||||
data.postData.text = qs.stringify(data.postData.paramsObj)
|
||||
}
|
||||
}
|
||||
|
||||
else if (some([
|
||||
} else if (some([
|
||||
'text/json',
|
||||
'text/x-json',
|
||||
'application/json',
|
||||
'application/x-json'])) {
|
||||
|
||||
data.postData.mimeType = 'application/json'
|
||||
|
||||
if (data.postData.text) {
|
||||
@@ -168,14 +161,12 @@ Har.prototype.options = function (options) {
|
||||
}
|
||||
if (test('application/x-www-form-urlencoded')) {
|
||||
options.form = req.postData.paramsObj
|
||||
}
|
||||
else if (test('application/json')) {
|
||||
} else if (test('application/json')) {
|
||||
if (req.postData.jsonObj) {
|
||||
options.body = req.postData.jsonObj
|
||||
options.json = true
|
||||
}
|
||||
}
|
||||
else if (test('multipart/form-data')) {
|
||||
} else if (test('multipart/form-data')) {
|
||||
options.formData = {}
|
||||
|
||||
req.postData.params.forEach(function (param) {
|
||||
@@ -202,8 +193,7 @@ Har.prototype.options = function (options) {
|
||||
|
||||
options.formData[param.name] = attachment
|
||||
})
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
if (req.postData.text) {
|
||||
options.body = req.postData.text
|
||||
}
|
||||
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
'use strict'
|
||||
|
||||
var crypto = require('crypto')
|
||||
|
||||
function randomString (size) {
|
||||
var bits = (size + 1) * 6
|
||||
var buffer = crypto.randomBytes(Math.ceil(bits / 8))
|
||||
var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
|
||||
return string.slice(0, size)
|
||||
}
|
||||
|
||||
function calculatePayloadHash (payload, algorithm, contentType) {
|
||||
var hash = crypto.createHash(algorithm)
|
||||
hash.update('hawk.1.payload\n')
|
||||
hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n')
|
||||
hash.update(payload || '')
|
||||
hash.update('\n')
|
||||
return hash.digest('base64')
|
||||
}
|
||||
|
||||
exports.calculateMac = function (credentials, opts) {
|
||||
var normalized = 'hawk.1.header\n' +
|
||||
opts.ts + '\n' +
|
||||
opts.nonce + '\n' +
|
||||
(opts.method || '').toUpperCase() + '\n' +
|
||||
opts.resource + '\n' +
|
||||
opts.host.toLowerCase() + '\n' +
|
||||
opts.port + '\n' +
|
||||
(opts.hash || '') + '\n'
|
||||
|
||||
if (opts.ext) {
|
||||
normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n')
|
||||
}
|
||||
|
||||
normalized = normalized + '\n'
|
||||
|
||||
if (opts.app) {
|
||||
normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n'
|
||||
}
|
||||
|
||||
var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized)
|
||||
var digest = hmac.digest('base64')
|
||||
return digest
|
||||
}
|
||||
|
||||
exports.header = function (uri, method, opts) {
|
||||
var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000)
|
||||
var credentials = opts.credentials
|
||||
if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) {
|
||||
return ''
|
||||
}
|
||||
|
||||
var artifacts = {
|
||||
ts: timestamp,
|
||||
nonce: opts.nonce || randomString(6),
|
||||
method: method,
|
||||
resource: uri.pathname + (uri.search || ''),
|
||||
host: uri.hostname,
|
||||
port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
|
||||
hash: opts.hash,
|
||||
ext: opts.ext,
|
||||
app: opts.app,
|
||||
dlg: opts.dlg
|
||||
}
|
||||
|
||||
if (!artifacts.hash && (opts.payload || opts.payload === '')) {
|
||||
artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType)
|
||||
}
|
||||
|
||||
var mac = exports.calculateMac(credentials, artifacts)
|
||||
|
||||
var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''
|
||||
var header = 'Hawk id="' + credentials.id +
|
||||
'", ts="' + artifacts.ts +
|
||||
'", nonce="' + artifacts.nonce +
|
||||
(artifacts.hash ? '", hash="' + artifacts.hash : '') +
|
||||
(hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') +
|
||||
'", mac="' + mac + '"'
|
||||
|
||||
if (artifacts.app) {
|
||||
header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'
|
||||
}
|
||||
|
||||
return header
|
||||
}
|
||||
+11
-10
@@ -1,13 +1,14 @@
|
||||
'use strict'
|
||||
|
||||
var jsonSafeStringify = require('json-stringify-safe')
|
||||
, crypto = require('crypto')
|
||||
var crypto = require('crypto')
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
|
||||
var defer = typeof setImmediate === 'undefined'
|
||||
? process.nextTick
|
||||
: setImmediate
|
||||
|
||||
function paramsHaveRequestBody(params) {
|
||||
function paramsHaveRequestBody (params) {
|
||||
return (
|
||||
params.body ||
|
||||
params.requestBodyStream ||
|
||||
@@ -35,7 +36,7 @@ function isReadStream (rs) {
|
||||
}
|
||||
|
||||
function toBase64 (str) {
|
||||
return (new Buffer(str || '', 'utf8')).toString('base64')
|
||||
return Buffer.from(str || '', 'utf8').toString('base64')
|
||||
}
|
||||
|
||||
function copy (obj) {
|
||||
@@ -56,10 +57,10 @@ function version () {
|
||||
}
|
||||
|
||||
exports.paramsHaveRequestBody = paramsHaveRequestBody
|
||||
exports.safeStringify = safeStringify
|
||||
exports.md5 = md5
|
||||
exports.isReadStream = isReadStream
|
||||
exports.toBase64 = toBase64
|
||||
exports.copy = copy
|
||||
exports.version = version
|
||||
exports.defer = defer
|
||||
exports.safeStringify = safeStringify
|
||||
exports.md5 = md5
|
||||
exports.isReadStream = isReadStream
|
||||
exports.toBase64 = toBase64
|
||||
exports.copy = copy
|
||||
exports.version = version
|
||||
exports.defer = defer
|
||||
|
||||
+8
-8
@@ -1,9 +1,9 @@
|
||||
'use strict'
|
||||
|
||||
var uuid = require('uuid')
|
||||
, CombinedStream = require('combined-stream')
|
||||
, isstream = require('isstream')
|
||||
|
||||
var uuid = require('uuid/v4')
|
||||
var CombinedStream = require('combined-stream')
|
||||
var isstream = require('isstream')
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
|
||||
function Multipart (request) {
|
||||
this.request = request
|
||||
@@ -14,8 +14,8 @@ function Multipart (request) {
|
||||
|
||||
Multipart.prototype.isChunked = function (options) {
|
||||
var self = this
|
||||
, chunked = false
|
||||
, parts = options.data || options
|
||||
var chunked = false
|
||||
var parts = options.data || options
|
||||
|
||||
if (!parts.forEach) {
|
||||
self.request.emit('error', new Error('Argument error, options.multipart.'))
|
||||
@@ -71,7 +71,7 @@ Multipart.prototype.build = function (parts, chunked) {
|
||||
if (typeof part === 'number') {
|
||||
part = part.toString()
|
||||
}
|
||||
return chunked ? body.append(part) : body.push(new Buffer(part))
|
||||
return chunked ? body.append(part) : body.push(Buffer.from(part))
|
||||
}
|
||||
|
||||
if (self.request.preambleCRLF) {
|
||||
@@ -102,7 +102,7 @@ Multipart.prototype.onRequest = function (options) {
|
||||
var self = this
|
||||
|
||||
var chunked = self.isChunked(options)
|
||||
, parts = options.data || options
|
||||
var parts = options.data || options
|
||||
|
||||
self.setHeaders(chunked)
|
||||
self.chunked = chunked
|
||||
|
||||
+22
-21
@@ -1,12 +1,12 @@
|
||||
'use strict'
|
||||
|
||||
var url = require('url')
|
||||
, qs = require('qs')
|
||||
, caseless = require('caseless')
|
||||
, uuid = require('uuid')
|
||||
, oauth = require('oauth-sign')
|
||||
, crypto = require('crypto')
|
||||
|
||||
var qs = require('qs')
|
||||
var caseless = require('caseless')
|
||||
var uuid = require('uuid/v4')
|
||||
var oauth = require('oauth-sign')
|
||||
var crypto = require('crypto')
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
|
||||
function OAuth (request) {
|
||||
this.request = request
|
||||
@@ -22,7 +22,7 @@ OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib)
|
||||
oa.oauth_version = '1.0'
|
||||
}
|
||||
if (!oa.oauth_timestamp) {
|
||||
oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
|
||||
oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString()
|
||||
}
|
||||
if (!oa.oauth_nonce) {
|
||||
oa.oauth_nonce = uuid().replace(/-/g, '')
|
||||
@@ -31,11 +31,11 @@ OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib)
|
||||
oa.oauth_signature_method = 'HMAC-SHA1'
|
||||
}
|
||||
|
||||
var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
|
||||
var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase
|
||||
delete oa.oauth_consumer_secret
|
||||
delete oa.oauth_private_key
|
||||
|
||||
var token_secret = oa.oauth_token_secret
|
||||
var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase
|
||||
delete oa.oauth_token_secret
|
||||
|
||||
var realm = oa.oauth_realm
|
||||
@@ -50,8 +50,9 @@ OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib)
|
||||
method,
|
||||
baseurl,
|
||||
params,
|
||||
consumer_secret_or_private_key,
|
||||
token_secret)
|
||||
consumer_secret_or_private_key, // eslint-disable-line camelcase
|
||||
token_secret // eslint-disable-line camelcase
|
||||
)
|
||||
|
||||
if (realm) {
|
||||
oa.realm = realm
|
||||
@@ -60,7 +61,7 @@ OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib)
|
||||
return oa
|
||||
}
|
||||
|
||||
OAuth.prototype.buildBodyHash = function(_oauth, body) {
|
||||
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.'))
|
||||
@@ -70,7 +71,7 @@ OAuth.prototype.buildBodyHash = function(_oauth, body) {
|
||||
shasum.update(body || '')
|
||||
var sha1 = shasum.digest('hex')
|
||||
|
||||
return new Buffer(sha1).toString('base64')
|
||||
return Buffer.from(sha1, 'hex').toString('base64')
|
||||
}
|
||||
|
||||
OAuth.prototype.concatParams = function (oa, sep, wrap) {
|
||||
@@ -95,16 +96,16 @@ OAuth.prototype.onRequest = function (_oauth) {
|
||||
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 method = self.request.method || ''
|
||||
var headers = caseless(self.request.headers)
|
||||
var body = self.request.body || ''
|
||||
var qsLib = self.request.qsLib || qs
|
||||
|
||||
var form
|
||||
, query
|
||||
, contentType = headers.get('content-type') || ''
|
||||
, formContentType = 'application/x-www-form-urlencoded'
|
||||
, transport = _oauth.transport_method || 'header'
|
||||
var query
|
||||
var contentType = headers.get('content-type') || ''
|
||||
var formContentType = 'application/x-www-form-urlencoded'
|
||||
var transport = _oauth.transport_method || 'header'
|
||||
|
||||
if (contentType.slice(0, formContentType.length) === formContentType) {
|
||||
contentType = formContentType
|
||||
|
||||
+2
-3
@@ -1,8 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
var qs = require('qs')
|
||||
, querystring = require('querystring')
|
||||
|
||||
var querystring = require('querystring')
|
||||
|
||||
function Querystring (request) {
|
||||
this.request = request
|
||||
@@ -13,7 +12,7 @@ function Querystring (request) {
|
||||
}
|
||||
|
||||
Querystring.prototype.init = function (options) {
|
||||
if (this.lib) {return}
|
||||
if (this.lib) { return }
|
||||
|
||||
this.useQuerystring = options.useQuerystring
|
||||
this.lib = (this.useQuerystring ? querystring : qs)
|
||||
|
||||
+7
-10
@@ -9,7 +9,7 @@ function Redirect (request) {
|
||||
this.followRedirects = true
|
||||
this.followAllRedirects = false
|
||||
this.followOriginalHttpMethod = false
|
||||
this.allowRedirect = function () {return true}
|
||||
this.allowRedirect = function () { return true }
|
||||
this.maxRedirects = 10
|
||||
this.redirects = []
|
||||
this.redirectsFollowed = 0
|
||||
@@ -44,7 +44,7 @@ Redirect.prototype.onRequest = function (options) {
|
||||
|
||||
Redirect.prototype.redirectTo = function (response) {
|
||||
var self = this
|
||||
, request = self.request
|
||||
var request = self.request
|
||||
|
||||
var redirectTo = null
|
||||
if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
|
||||
@@ -78,7 +78,7 @@ Redirect.prototype.redirectTo = function (response) {
|
||||
|
||||
Redirect.prototype.onResponse = function (response) {
|
||||
var self = this
|
||||
, request = self.request
|
||||
var request = self.request
|
||||
|
||||
var redirectTo = self.redirectTo(response)
|
||||
if (!redirectTo || !self.allowRedirect.call(request, response)) {
|
||||
@@ -112,13 +112,10 @@ Redirect.prototype.onResponse = function (response) {
|
||||
delete request.agent
|
||||
}
|
||||
|
||||
self.redirects.push(
|
||||
{ statusCode : response.statusCode
|
||||
, redirectUri: redirectTo
|
||||
}
|
||||
)
|
||||
if (self.followAllRedirects && request.method !== 'HEAD'
|
||||
&& response.statusCode !== 401 && response.statusCode !== 307) {
|
||||
self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })
|
||||
|
||||
if (self.followAllRedirects && request.method !== 'HEAD' &&
|
||||
response.statusCode !== 401 && response.statusCode !== 307) {
|
||||
request.method = self.followOriginalHttpMethod ? request.method : 'GET'
|
||||
}
|
||||
// request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
|
||||
|
||||
+25
-26
@@ -1,7 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
var url = require('url')
|
||||
, tunnel = require('tunnel-agent')
|
||||
var tunnel = require('tunnel-agent')
|
||||
|
||||
var defaultProxyHeaderWhiteList = [
|
||||
'accept',
|
||||
@@ -31,10 +31,10 @@ var defaultProxyHeaderExclusiveList = [
|
||||
'proxy-authorization'
|
||||
]
|
||||
|
||||
function constructProxyHost(uriObject) {
|
||||
function constructProxyHost (uriObject) {
|
||||
var port = uriObject.port
|
||||
, protocol = uriObject.protocol
|
||||
, proxyHost = uriObject.hostname + ':'
|
||||
var protocol = uriObject.protocol
|
||||
var proxyHost = uriObject.hostname + ':'
|
||||
|
||||
if (port) {
|
||||
proxyHost += port
|
||||
@@ -47,7 +47,7 @@ function constructProxyHost(uriObject) {
|
||||
return proxyHost
|
||||
}
|
||||
|
||||
function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) {
|
||||
function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) {
|
||||
var whiteList = proxyHeaderWhiteList
|
||||
.reduce(function (set, header) {
|
||||
set[header.toLowerCase()] = true
|
||||
@@ -68,41 +68,40 @@ function constructTunnelOptions (request, proxyHeaders) {
|
||||
var proxy = request.proxy
|
||||
|
||||
var tunnelOptions = {
|
||||
proxy : {
|
||||
host : proxy.hostname,
|
||||
port : +proxy.port,
|
||||
proxyAuth : proxy.auth,
|
||||
headers : proxyHeaders
|
||||
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
|
||||
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) {
|
||||
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) {
|
||||
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
|
||||
@@ -114,8 +113,8 @@ function Tunnel (request) {
|
||||
|
||||
Tunnel.prototype.isEnabled = function () {
|
||||
var self = this
|
||||
, request = self.request
|
||||
// Tunnel HTTPS by default. Allow the user to override this setting.
|
||||
var request = self.request
|
||||
// Tunnel HTTPS by default. Allow the user to override this setting.
|
||||
|
||||
// If self.tunnelOverride is set (the user specified a value), use it.
|
||||
if (typeof self.tunnelOverride !== 'undefined') {
|
||||
@@ -133,7 +132,7 @@ Tunnel.prototype.isEnabled = function () {
|
||||
|
||||
Tunnel.prototype.setup = function (options) {
|
||||
var self = this
|
||||
, request = self.request
|
||||
var request = self.request
|
||||
|
||||
options = options || {}
|
||||
|
||||
|
||||
Generated
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = tab
|
||||
indent_size = 4
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
max_line_length = 150
|
||||
|
||||
[CHANGELOG.md]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.json]
|
||||
max_line_length = off
|
||||
|
||||
[Makefile]
|
||||
max_line_length = off
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"root": true,
|
||||
|
||||
"extends": "@ljharb",
|
||||
|
||||
"rules": {
|
||||
"complexity": [2, 20],
|
||||
"eqeqeq": [2, "allow-null"],
|
||||
"func-name-matching": [1],
|
||||
"max-depth": [1, 4],
|
||||
"max-statements": [2, 26],
|
||||
"no-extra-parens": [1],
|
||||
"no-magic-numbers": [0],
|
||||
"no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"],
|
||||
"sort-keys": [0],
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
{
|
||||
"es3": true,
|
||||
|
||||
"additionalRules": [],
|
||||
|
||||
"requireSemicolons": true,
|
||||
|
||||
"disallowMultipleSpaces": true,
|
||||
|
||||
"disallowIdentifierNames": [],
|
||||
|
||||
"requireCurlyBraces": {
|
||||
"allExcept": [],
|
||||
"keywords": ["if", "else", "for", "while", "do", "try", "catch"]
|
||||
},
|
||||
|
||||
"requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"],
|
||||
|
||||
"disallowSpaceAfterKeywords": [],
|
||||
|
||||
"disallowSpaceBeforeComma": true,
|
||||
"disallowSpaceAfterComma": false,
|
||||
"disallowSpaceBeforeSemicolon": true,
|
||||
|
||||
"disallowNodeTypes": [
|
||||
"DebuggerStatement",
|
||||
"LabeledStatement",
|
||||
"SwitchCase",
|
||||
"SwitchStatement",
|
||||
"WithStatement"
|
||||
],
|
||||
|
||||
"requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] },
|
||||
|
||||
"requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true },
|
||||
"requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true },
|
||||
"disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true },
|
||||
"requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true },
|
||||
"disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true },
|
||||
|
||||
"requireSpaceBetweenArguments": true,
|
||||
|
||||
"disallowSpacesInsideParentheses": true,
|
||||
|
||||
"disallowSpacesInsideArrayBrackets": true,
|
||||
|
||||
"disallowQuotedKeysInObjects": { "allExcept": ["reserved"] },
|
||||
|
||||
"disallowSpaceAfterObjectKeys": true,
|
||||
|
||||
"requireCommaBeforeLineBreak": true,
|
||||
|
||||
"disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
|
||||
"requireSpaceAfterPrefixUnaryOperators": [],
|
||||
|
||||
"disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
|
||||
"requireSpaceBeforePostfixUnaryOperators": [],
|
||||
|
||||
"disallowSpaceBeforeBinaryOperators": [],
|
||||
"requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
|
||||
|
||||
"requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
|
||||
"disallowSpaceAfterBinaryOperators": [],
|
||||
|
||||
"disallowImplicitTypeConversion": ["binary", "string"],
|
||||
|
||||
"disallowKeywords": ["with", "eval"],
|
||||
|
||||
"requireKeywordsOnNewLine": [],
|
||||
"disallowKeywordsOnNewLine": ["else"],
|
||||
|
||||
"requireLineFeedAtFileEnd": true,
|
||||
|
||||
"disallowTrailingWhitespace": true,
|
||||
|
||||
"disallowTrailingComma": true,
|
||||
|
||||
"excludeFiles": ["node_modules/**", "vendor/**"],
|
||||
|
||||
"disallowMultipleLineStrings": true,
|
||||
|
||||
"requireDotNotation": { "allExcept": ["keywords"] },
|
||||
|
||||
"requireParenthesesAroundIIFE": true,
|
||||
|
||||
"validateLineBreaks": "LF",
|
||||
|
||||
"validateQuoteMarks": {
|
||||
"escape": true,
|
||||
"mark": "'"
|
||||
},
|
||||
|
||||
"disallowOperatorBeforeLineBreak": [],
|
||||
|
||||
"requireSpaceBeforeKeywords": [
|
||||
"do",
|
||||
"for",
|
||||
"if",
|
||||
"else",
|
||||
"switch",
|
||||
"case",
|
||||
"try",
|
||||
"catch",
|
||||
"finally",
|
||||
"while",
|
||||
"with",
|
||||
"return"
|
||||
],
|
||||
|
||||
"validateAlignedFunctionParameters": {
|
||||
"lineBreakAfterOpeningBraces": true,
|
||||
"lineBreakBeforeClosingBraces": true
|
||||
},
|
||||
|
||||
"requirePaddingNewLinesBeforeExport": true,
|
||||
|
||||
"validateNewlineAfterArrayElements": {
|
||||
"maximum": 6
|
||||
},
|
||||
|
||||
"requirePaddingNewLinesAfterUseStrict": true,
|
||||
|
||||
"disallowArrowFunctions": true,
|
||||
|
||||
"disallowMultiLineTernary": true,
|
||||
|
||||
"validateOrderInObjectKeys": false,
|
||||
|
||||
"disallowIdenticalDestructuringNames": true,
|
||||
|
||||
"disallowNestedTernaries": { "maxLevel": 1 },
|
||||
|
||||
"requireSpaceAfterComma": { "allExcept": ["trailing"] },
|
||||
"requireAlignedMultilineParams": false,
|
||||
|
||||
"requireSpacesInGenerator": {
|
||||
"afterStar": true
|
||||
},
|
||||
|
||||
"disallowSpacesInGenerator": {
|
||||
"beforeStar": true
|
||||
},
|
||||
|
||||
"disallowVar": false,
|
||||
|
||||
"requireArrayDestructuring": false,
|
||||
|
||||
"requireEnhancedObjectLiterals": false,
|
||||
|
||||
"requireObjectDestructuring": false,
|
||||
|
||||
"requireEarlyReturn": false,
|
||||
|
||||
"requireCapitalizedConstructorsNew": {
|
||||
"allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"]
|
||||
},
|
||||
|
||||
"requireImportAlphabetized": false,
|
||||
|
||||
"requireSpaceBeforeObjectValues": true,
|
||||
"requireSpaceBeforeDestructuredValues": true,
|
||||
|
||||
"disallowSpacesInsideTemplateStringPlaceholders": true,
|
||||
|
||||
"disallowArrayDestructuringReturn": false,
|
||||
|
||||
"requireNewlineBeforeSingleStatementsInIf": false,
|
||||
|
||||
"disallowUnusedVariables": true,
|
||||
|
||||
"requireSpacesInsideImportedObjectBraces": true,
|
||||
|
||||
"requireUseStrict": true
|
||||
}
|
||||
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
language: node_js
|
||||
os:
|
||||
- linux
|
||||
node_js:
|
||||
- "10.7"
|
||||
- "9.11"
|
||||
- "8.11"
|
||||
- "7.10"
|
||||
- "6.14"
|
||||
- "5.12"
|
||||
- "4.9"
|
||||
- "iojs-v3.3"
|
||||
- "iojs-v2.5"
|
||||
- "iojs-v1.8"
|
||||
- "0.12"
|
||||
- "0.10"
|
||||
- "0.8"
|
||||
before_install:
|
||||
- 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac'
|
||||
- 'nvm install-latest-npm'
|
||||
install:
|
||||
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;'
|
||||
script:
|
||||
- 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi'
|
||||
- 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi'
|
||||
- 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi'
|
||||
- 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi'
|
||||
sudo: false
|
||||
env:
|
||||
- TEST=true
|
||||
matrix:
|
||||
fast_finish: true
|
||||
include:
|
||||
- node_js: "lts/*"
|
||||
env: PRETEST=true
|
||||
- node_js: "lts/*"
|
||||
env: POSTTEST=true
|
||||
- node_js: "4"
|
||||
env: COVERAGE=true
|
||||
- node_js: "10.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "10.5"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "10.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "10.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "10.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "10.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "10.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.10"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.9"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.8"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.7"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.5"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "9.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.10"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.9"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.8"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.7"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.5"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "8.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.9"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.8"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.7"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.5"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "7.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.13"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.12"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.11"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.10"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.9"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.8"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.7"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.5"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "6.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.11"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.10"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.9"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.8"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.7"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.5"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "5.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.8"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.7"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.5"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "4.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v3.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v3.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v3.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v2.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v2.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v2.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v2.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v2.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v1.7"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v1.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v1.5"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v1.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v1.3"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v1.2"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v1.1"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "iojs-v1.0"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "0.11"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "0.9"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "0.6"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
- node_js: "0.4"
|
||||
env: TEST=true ALLOW_FAILURE=true
|
||||
allow_failures:
|
||||
- os: osx
|
||||
- env: TEST=true ALLOW_FAILURE=true
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
3.0.2 / 2018-07-19
|
||||
==================
|
||||
* [Fix] Prevent merging `__proto__` property (#48)
|
||||
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`
|
||||
* [Tests] up to `node` `v10.7`, `v9.11`, `v8.11`, `v7.10`, `v6.14`, `v4.9`; use `nvm install-latest-npm`
|
||||
|
||||
3.0.1 / 2017-04-27
|
||||
==================
|
||||
* [Fix] deep extending should work with a non-object (#46)
|
||||
* [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`
|
||||
* [Tests] up to `node` `v7.9`, `v6.10`, `v4.8`; improve matrix
|
||||
* [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG.
|
||||
* [Docs] Add example to readme (#34)
|
||||
|
||||
3.0.0 / 2015-07-01
|
||||
==================
|
||||
* [Possible breaking change] Use global "strict" directive (#32)
|
||||
* [Tests] `int` is an ES3 reserved word
|
||||
* [Tests] Test up to `io.js` `v2.3`
|
||||
* [Tests] Add `npm run eslint`
|
||||
* [Dev Deps] Update `covert`, `jscs`
|
||||
|
||||
2.0.1 / 2015-04-25
|
||||
==================
|
||||
* Use an inline `isArray` check, for ES3 browsers. (#27)
|
||||
* Some old browsers fail when an identifier is `toString`
|
||||
* Test latest `node` and `io.js` versions on `travis-ci`; speed up builds
|
||||
* Add license info to package.json (#25)
|
||||
* Update `tape`, `jscs`
|
||||
* Adding a CHANGELOG
|
||||
|
||||
2.0.0 / 2014-10-01
|
||||
==================
|
||||
* Increase code coverage to 100%; run code coverage as part of tests
|
||||
* Add `npm run lint`; Run linter as part of tests
|
||||
* Remove nodeType and setInterval checks in isPlainObject
|
||||
* Updating `tape`, `jscs`, `covert`
|
||||
* General style and README cleanup
|
||||
|
||||
1.3.0 / 2014-06-20
|
||||
==================
|
||||
* Add component.json for browser support (#18)
|
||||
* Use SVG for badges in README (#16)
|
||||
* Updating `tape`, `covert`
|
||||
* Updating travis-ci to work with multiple node versions
|
||||
* Fix `deep === false` bug (returning target as {}) (#14)
|
||||
* Fixing constructor checks in isPlainObject
|
||||
* Adding additional test coverage
|
||||
* Adding `npm run coverage`
|
||||
* Add LICENSE (#13)
|
||||
* Adding a warning about `false`, per #11
|
||||
* General style and whitespace cleanup
|
||||
|
||||
1.2.1 / 2013-09-14
|
||||
==================
|
||||
* Fixing hasOwnProperty bugs that would only have shown up in specific browsers. Fixes #8
|
||||
* Updating `tape`
|
||||
|
||||
1.2.0 / 2013-09-02
|
||||
==================
|
||||
* Updating the README: add badges
|
||||
* Adding a missing variable reference.
|
||||
* Using `tape` instead of `buster` for tests; add more tests (#7)
|
||||
* Adding node 0.10 to Travis CI (#6)
|
||||
* Enabling "npm test" and cleaning up package.json (#5)
|
||||
* Add Travis CI.
|
||||
|
||||
1.1.3 / 2012-12-06
|
||||
==================
|
||||
* Added unit tests.
|
||||
* Ensure extend function is named. (Looks nicer in a stack trace.)
|
||||
* README cleanup.
|
||||
|
||||
1.1.1 / 2012-11-07
|
||||
==================
|
||||
* README cleanup.
|
||||
* Added installation instructions.
|
||||
* Added a missing semicolon
|
||||
|
||||
1.0.0 / 2012-04-08
|
||||
==================
|
||||
* Initial commit
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Stefan Thomas
|
||||
|
||||
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.
|
||||
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
[![Build Status][travis-svg]][travis-url]
|
||||
[![dependency status][deps-svg]][deps-url]
|
||||
[![dev dependency status][dev-deps-svg]][dev-deps-url]
|
||||
|
||||
# extend() for Node.js <sup>[![Version Badge][npm-version-png]][npm-url]</sup>
|
||||
|
||||
`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true.
|
||||
|
||||
Notes:
|
||||
|
||||
* Since Node.js >= 4,
|
||||
[`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
|
||||
now offers the same functionality natively (but without the "deep copy" option).
|
||||
See [ECMAScript 2015 (ES6) in Node.js](https://nodejs.org/en/docs/es6).
|
||||
* Some native implementations of `Object.assign` in both Node.js and many
|
||||
browsers (since NPM modules are for the browser too) may not be fully
|
||||
spec-compliant.
|
||||
Check [`object.assign`](https://www.npmjs.com/package/object.assign) module for
|
||||
a compliant candidate.
|
||||
|
||||
## Installation
|
||||
|
||||
This package is available on [npm][npm-url] as: `extend`
|
||||
|
||||
``` sh
|
||||
npm install extend
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
**Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)**
|
||||
|
||||
*Extend one object with one or more others, returning the modified object.*
|
||||
|
||||
**Example:**
|
||||
|
||||
``` js
|
||||
var extend = require('extend');
|
||||
extend(targetObject, object1, object2);
|
||||
```
|
||||
|
||||
Keep in mind that the target object will be modified, and will be returned from extend().
|
||||
|
||||
If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s).
|
||||
Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over.
|
||||
Warning: passing `false` as the first argument is not supported.
|
||||
|
||||
### Arguments
|
||||
|
||||
* `deep` *Boolean* (optional)
|
||||
If set, the merge becomes recursive (i.e. deep copy).
|
||||
* `target` *Object*
|
||||
The object to extend.
|
||||
* `object1` *Object*
|
||||
The object that will be merged into the first.
|
||||
* `objectN` *Object* (Optional)
|
||||
More objects to merge into the first.
|
||||
|
||||
## License
|
||||
|
||||
`node-extend` is licensed under the [MIT License][mit-license-url].
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
All credit to the jQuery authors for perfecting this amazing utility.
|
||||
|
||||
Ported to Node.js by [Stefan Thomas][github-justmoon] with contributions by [Jonathan Buchanan][github-insin] and [Jordan Harband][github-ljharb].
|
||||
|
||||
[travis-svg]: https://travis-ci.org/justmoon/node-extend.svg
|
||||
[travis-url]: https://travis-ci.org/justmoon/node-extend
|
||||
[npm-url]: https://npmjs.org/package/extend
|
||||
[mit-license-url]: http://opensource.org/licenses/MIT
|
||||
[github-justmoon]: https://github.com/justmoon
|
||||
[github-insin]: https://github.com/insin
|
||||
[github-ljharb]: https://github.com/ljharb
|
||||
[npm-version-png]: http://versionbadg.es/justmoon/node-extend.svg
|
||||
[deps-svg]: https://david-dm.org/justmoon/node-extend.svg
|
||||
[deps-url]: https://david-dm.org/justmoon/node-extend
|
||||
[dev-deps-svg]: https://david-dm.org/justmoon/node-extend/dev-status.svg
|
||||
[dev-deps-url]: https://david-dm.org/justmoon/node-extend#info=devDependencies
|
||||
|
||||
Generated
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "extend",
|
||||
"author": "Stefan Thomas <justmoon@members.fsf.org> (http://www.justmoon.net)",
|
||||
"version": "3.0.0",
|
||||
"description": "Port of jQuery.extend for node.js and the browser.",
|
||||
"scripts": [
|
||||
"index.js"
|
||||
],
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Jordan Harband",
|
||||
"url": "https://github.com/ljharb"
|
||||
}
|
||||
],
|
||||
"keywords": [
|
||||
"extend",
|
||||
"clone",
|
||||
"merge"
|
||||
],
|
||||
"repository" : {
|
||||
"type": "git",
|
||||
"url": "https://github.com/justmoon/node-extend.git"
|
||||
},
|
||||
"dependencies": {
|
||||
},
|
||||
"devDependencies": {
|
||||
"tape" : "~3.0.0",
|
||||
"covert": "~0.4.0",
|
||||
"jscs": "~1.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
'use strict';
|
||||
|
||||
var hasOwn = Object.prototype.hasOwnProperty;
|
||||
var toStr = Object.prototype.toString;
|
||||
var defineProperty = Object.defineProperty;
|
||||
var gOPD = Object.getOwnPropertyDescriptor;
|
||||
|
||||
var isArray = function isArray(arr) {
|
||||
if (typeof Array.isArray === 'function') {
|
||||
return Array.isArray(arr);
|
||||
}
|
||||
|
||||
return toStr.call(arr) === '[object Array]';
|
||||
};
|
||||
|
||||
var isPlainObject = function isPlainObject(obj) {
|
||||
if (!obj || toStr.call(obj) !== '[object Object]') {
|
||||
return false;
|
||||
}
|
||||
|
||||
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
|
||||
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
|
||||
// Not own constructor property must be Object
|
||||
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Own properties are enumerated firstly, so to speed up,
|
||||
// if last one is own, then all properties are own.
|
||||
var key;
|
||||
for (key in obj) { /**/ }
|
||||
|
||||
return typeof key === 'undefined' || hasOwn.call(obj, key);
|
||||
};
|
||||
|
||||
// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
|
||||
var setProperty = function setProperty(target, options) {
|
||||
if (defineProperty && options.name === '__proto__') {
|
||||
defineProperty(target, options.name, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
value: options.newValue,
|
||||
writable: true
|
||||
});
|
||||
} else {
|
||||
target[options.name] = options.newValue;
|
||||
}
|
||||
};
|
||||
|
||||
// Return undefined instead of __proto__ if '__proto__' is not an own property
|
||||
var getProperty = function getProperty(obj, name) {
|
||||
if (name === '__proto__') {
|
||||
if (!hasOwn.call(obj, name)) {
|
||||
return void 0;
|
||||
} else if (gOPD) {
|
||||
// In early versions of node, obj['__proto__'] is buggy when obj has
|
||||
// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
|
||||
return gOPD(obj, name).value;
|
||||
}
|
||||
}
|
||||
|
||||
return obj[name];
|
||||
};
|
||||
|
||||
module.exports = function extend() {
|
||||
var options, name, src, copy, copyIsArray, clone;
|
||||
var target = arguments[0];
|
||||
var i = 1;
|
||||
var length = arguments.length;
|
||||
var deep = false;
|
||||
|
||||
// Handle a deep copy situation
|
||||
if (typeof target === 'boolean') {
|
||||
deep = target;
|
||||
target = arguments[1] || {};
|
||||
// skip the boolean and the target
|
||||
i = 2;
|
||||
}
|
||||
if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
|
||||
target = {};
|
||||
}
|
||||
|
||||
for (; i < length; ++i) {
|
||||
options = arguments[i];
|
||||
// Only deal with non-null/undefined values
|
||||
if (options != null) {
|
||||
// Extend the base object
|
||||
for (name in options) {
|
||||
src = getProperty(target, name);
|
||||
copy = getProperty(options, name);
|
||||
|
||||
// Prevent never-ending loop
|
||||
if (target !== copy) {
|
||||
// Recurse if we're merging plain objects or arrays
|
||||
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
|
||||
if (copyIsArray) {
|
||||
copyIsArray = false;
|
||||
clone = src && isArray(src) ? src : [];
|
||||
} else {
|
||||
clone = src && isPlainObject(src) ? src : {};
|
||||
}
|
||||
|
||||
// Never move original objects, clone them
|
||||
setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
|
||||
|
||||
// Don't bring in undefined values
|
||||
} else if (typeof copy !== 'undefined') {
|
||||
setProperty(target, { name: name, newValue: copy });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return the modified object
|
||||
return target;
|
||||
};
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"_from": "extend@~3.0.2",
|
||||
"_id": "extend@3.0.2",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
|
||||
"_location": "/request/extend",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "extend@~3.0.2",
|
||||
"name": "extend",
|
||||
"escapedName": "extend",
|
||||
"rawSpec": "~3.0.2",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "~3.0.2"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/request"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
|
||||
"_shasum": "f8b1136b4071fbd8eb140aff858b1019ec2915fa",
|
||||
"_spec": "extend@~3.0.2",
|
||||
"_where": "/home/kevin/Documents/Sites/anissabensalah.net/user/themes/anissabensalah/node_modules/request",
|
||||
"author": {
|
||||
"name": "Stefan Thomas",
|
||||
"email": "justmoon@members.fsf.org",
|
||||
"url": "http://www.justmoon.net"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/justmoon/node-extend/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Jordan Harband",
|
||||
"url": "https://github.com/ljharb"
|
||||
}
|
||||
],
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "Port of jQuery.extend for node.js and the browser",
|
||||
"devDependencies": {
|
||||
"@ljharb/eslint-config": "^12.2.1",
|
||||
"covert": "^1.1.0",
|
||||
"eslint": "^4.19.1",
|
||||
"jscs": "^3.0.7",
|
||||
"tape": "^4.9.1"
|
||||
},
|
||||
"homepage": "https://github.com/justmoon/node-extend#readme",
|
||||
"keywords": [
|
||||
"extend",
|
||||
"clone",
|
||||
"merge"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index",
|
||||
"name": "extend",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/justmoon/node-extend.git"
|
||||
},
|
||||
"scripts": {
|
||||
"coverage": "covert test/index.js",
|
||||
"coverage-quiet": "covert test/index.js --quiet",
|
||||
"eslint": "eslint *.js */*.js",
|
||||
"jscs": "jscs *.js */*.js",
|
||||
"lint": "npm run jscs && npm run eslint",
|
||||
"posttest": "npm run coverage-quiet",
|
||||
"pretest": "npm run lint",
|
||||
"test": "npm run tests-only",
|
||||
"tests-only": "node test"
|
||||
},
|
||||
"version": "3.0.2"
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Feross Aboukhadijeh
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Generated
Vendored
+584
@@ -0,0 +1,584 @@
|
||||
# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
|
||||
|
||||
[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg
|
||||
[travis-url]: https://travis-ci.org/feross/safe-buffer
|
||||
[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg
|
||||
[npm-url]: https://npmjs.org/package/safe-buffer
|
||||
[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg
|
||||
[downloads-url]: https://npmjs.org/package/safe-buffer
|
||||
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
|
||||
[standard-url]: https://standardjs.com
|
||||
|
||||
#### Safer Node.js Buffer API
|
||||
|
||||
**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`,
|
||||
`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.**
|
||||
|
||||
**Uses the built-in implementation when available.**
|
||||
|
||||
## install
|
||||
|
||||
```
|
||||
npm install safe-buffer
|
||||
```
|
||||
|
||||
## usage
|
||||
|
||||
The goal of this package is to provide a safe replacement for the node.js `Buffer`.
|
||||
|
||||
It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to
|
||||
the top of your node.js modules:
|
||||
|
||||
```js
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
|
||||
// Existing buffer code will continue to work without issues:
|
||||
|
||||
new Buffer('hey', 'utf8')
|
||||
new Buffer([1, 2, 3], 'utf8')
|
||||
new Buffer(obj)
|
||||
new Buffer(16) // create an uninitialized buffer (potentially unsafe)
|
||||
|
||||
// But you can use these new explicit APIs to make clear what you want:
|
||||
|
||||
Buffer.from('hey', 'utf8') // convert from many types to a Buffer
|
||||
Buffer.alloc(16) // create a zero-filled buffer (safe)
|
||||
Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
|
||||
```
|
||||
|
||||
## api
|
||||
|
||||
### Class Method: Buffer.from(array)
|
||||
<!-- YAML
|
||||
added: v3.0.0
|
||||
-->
|
||||
|
||||
* `array` {Array}
|
||||
|
||||
Allocates a new `Buffer` using an `array` of octets.
|
||||
|
||||
```js
|
||||
const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
|
||||
// creates a new Buffer containing ASCII bytes
|
||||
// ['b','u','f','f','e','r']
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `array` is not an `Array`.
|
||||
|
||||
### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
|
||||
a `new ArrayBuffer()`
|
||||
* `byteOffset` {Number} Default: `0`
|
||||
* `length` {Number} Default: `arrayBuffer.length - byteOffset`
|
||||
|
||||
When passed a reference to the `.buffer` property of a `TypedArray` instance,
|
||||
the newly created `Buffer` will share the same allocated memory as the
|
||||
TypedArray.
|
||||
|
||||
```js
|
||||
const arr = new Uint16Array(2);
|
||||
arr[0] = 5000;
|
||||
arr[1] = 4000;
|
||||
|
||||
const buf = Buffer.from(arr.buffer); // shares the memory with arr;
|
||||
|
||||
console.log(buf);
|
||||
// Prints: <Buffer 88 13 a0 0f>
|
||||
|
||||
// changing the TypedArray changes the Buffer also
|
||||
arr[1] = 6000;
|
||||
|
||||
console.log(buf);
|
||||
// Prints: <Buffer 88 13 70 17>
|
||||
```
|
||||
|
||||
The optional `byteOffset` and `length` arguments specify a memory range within
|
||||
the `arrayBuffer` that will be shared by the `Buffer`.
|
||||
|
||||
```js
|
||||
const ab = new ArrayBuffer(10);
|
||||
const buf = Buffer.from(ab, 0, 2);
|
||||
console.log(buf.length);
|
||||
// Prints: 2
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.
|
||||
|
||||
### Class Method: Buffer.from(buffer)
|
||||
<!-- YAML
|
||||
added: v3.0.0
|
||||
-->
|
||||
|
||||
* `buffer` {Buffer}
|
||||
|
||||
Copies the passed `buffer` data onto a new `Buffer` instance.
|
||||
|
||||
```js
|
||||
const buf1 = Buffer.from('buffer');
|
||||
const buf2 = Buffer.from(buf1);
|
||||
|
||||
buf1[0] = 0x61;
|
||||
console.log(buf1.toString());
|
||||
// 'auffer'
|
||||
console.log(buf2.toString());
|
||||
// 'buffer' (copy is not changed)
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `buffer` is not a `Buffer`.
|
||||
|
||||
### Class Method: Buffer.from(str[, encoding])
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `str` {String} String to encode.
|
||||
* `encoding` {String} Encoding to use, Default: `'utf8'`
|
||||
|
||||
Creates a new `Buffer` containing the given JavaScript string `str`. If
|
||||
provided, the `encoding` parameter identifies the character encoding.
|
||||
If not provided, `encoding` defaults to `'utf8'`.
|
||||
|
||||
```js
|
||||
const buf1 = Buffer.from('this is a tést');
|
||||
console.log(buf1.toString());
|
||||
// prints: this is a tést
|
||||
console.log(buf1.toString('ascii'));
|
||||
// prints: this is a tC)st
|
||||
|
||||
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
|
||||
console.log(buf2.toString());
|
||||
// prints: this is a tést
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `str` is not a string.
|
||||
|
||||
### Class Method: Buffer.alloc(size[, fill[, encoding]])
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `size` {Number}
|
||||
* `fill` {Value} Default: `undefined`
|
||||
* `encoding` {String} Default: `utf8`
|
||||
|
||||
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
|
||||
`Buffer` will be *zero-filled*.
|
||||
|
||||
```js
|
||||
const buf = Buffer.alloc(5);
|
||||
console.log(buf);
|
||||
// <Buffer 00 00 00 00 00>
|
||||
```
|
||||
|
||||
The `size` must be less than or equal to the value of
|
||||
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
|
||||
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
|
||||
be created if a `size` less than or equal to 0 is specified.
|
||||
|
||||
If `fill` is specified, the allocated `Buffer` will be initialized by calling
|
||||
`buf.fill(fill)`. See [`buf.fill()`][] for more information.
|
||||
|
||||
```js
|
||||
const buf = Buffer.alloc(5, 'a');
|
||||
console.log(buf);
|
||||
// <Buffer 61 61 61 61 61>
|
||||
```
|
||||
|
||||
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
|
||||
initialized by calling `buf.fill(fill, encoding)`. For example:
|
||||
|
||||
```js
|
||||
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
|
||||
console.log(buf);
|
||||
// <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
|
||||
```
|
||||
|
||||
Calling `Buffer.alloc(size)` can be significantly slower than the alternative
|
||||
`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
|
||||
contents will *never contain sensitive data*.
|
||||
|
||||
A `TypeError` will be thrown if `size` is not a number.
|
||||
|
||||
### Class Method: Buffer.allocUnsafe(size)
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `size` {Number}
|
||||
|
||||
Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
|
||||
be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
|
||||
architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
|
||||
thrown. A zero-length Buffer will be created if a `size` less than or equal to
|
||||
0 is specified.
|
||||
|
||||
The underlying memory for `Buffer` instances created in this way is *not
|
||||
initialized*. The contents of the newly created `Buffer` are unknown and
|
||||
*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
|
||||
`Buffer` instances to zeroes.
|
||||
|
||||
```js
|
||||
const buf = Buffer.allocUnsafe(5);
|
||||
console.log(buf);
|
||||
// <Buffer 78 e0 82 02 01>
|
||||
// (octets will be different, every time)
|
||||
buf.fill(0);
|
||||
console.log(buf);
|
||||
// <Buffer 00 00 00 00 00>
|
||||
```
|
||||
|
||||
A `TypeError` will be thrown if `size` is not a number.
|
||||
|
||||
Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
|
||||
size `Buffer.poolSize` that is used as a pool for the fast allocation of new
|
||||
`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated
|
||||
`new Buffer(size)` constructor) only when `size` is less than or equal to
|
||||
`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default
|
||||
value of `Buffer.poolSize` is `8192` but can be modified.
|
||||
|
||||
Use of this pre-allocated internal memory pool is a key difference between
|
||||
calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
|
||||
Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer
|
||||
pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
|
||||
Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The
|
||||
difference is subtle but can be important when an application requires the
|
||||
additional performance that `Buffer.allocUnsafe(size)` provides.
|
||||
|
||||
### Class Method: Buffer.allocUnsafeSlow(size)
|
||||
<!-- YAML
|
||||
added: v5.10.0
|
||||
-->
|
||||
|
||||
* `size` {Number}
|
||||
|
||||
Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
|
||||
`size` must be less than or equal to the value of
|
||||
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
|
||||
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
|
||||
be created if a `size` less than or equal to 0 is specified.
|
||||
|
||||
The underlying memory for `Buffer` instances created in this way is *not
|
||||
initialized*. The contents of the newly created `Buffer` are unknown and
|
||||
*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
|
||||
`Buffer` instances to zeroes.
|
||||
|
||||
When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
|
||||
allocations under 4KB are, by default, sliced from a single pre-allocated
|
||||
`Buffer`. This allows applications to avoid the garbage collection overhead of
|
||||
creating many individually allocated Buffers. This approach improves both
|
||||
performance and memory usage by eliminating the need to track and cleanup as
|
||||
many `Persistent` objects.
|
||||
|
||||
However, in the case where a developer may need to retain a small chunk of
|
||||
memory from a pool for an indeterminate amount of time, it may be appropriate
|
||||
to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then
|
||||
copy out the relevant bits.
|
||||
|
||||
```js
|
||||
// need to keep around a few small chunks of memory
|
||||
const store = [];
|
||||
|
||||
socket.on('readable', () => {
|
||||
const data = socket.read();
|
||||
// allocate for retained data
|
||||
const sb = Buffer.allocUnsafeSlow(10);
|
||||
// copy the data into the new allocation
|
||||
data.copy(sb, 0, 0, 10);
|
||||
store.push(sb);
|
||||
});
|
||||
```
|
||||
|
||||
Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after*
|
||||
a developer has observed undue memory retention in their applications.
|
||||
|
||||
A `TypeError` will be thrown if `size` is not a number.
|
||||
|
||||
### All the Rest
|
||||
|
||||
The rest of the `Buffer` API is exactly the same as in node.js.
|
||||
[See the docs](https://nodejs.org/api/buffer.html).
|
||||
|
||||
|
||||
## Related links
|
||||
|
||||
- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)
|
||||
- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4)
|
||||
|
||||
## Why is `Buffer` unsafe?
|
||||
|
||||
Today, the node.js `Buffer` constructor is overloaded to handle many different argument
|
||||
types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),
|
||||
`ArrayBuffer`, and also `Number`.
|
||||
|
||||
The API is optimized for convenience: you can throw any type at it, and it will try to do
|
||||
what you want.
|
||||
|
||||
Because the Buffer constructor is so powerful, you often see code like this:
|
||||
|
||||
```js
|
||||
// Convert UTF-8 strings to hex
|
||||
function toHex (str) {
|
||||
return new Buffer(str).toString('hex')
|
||||
}
|
||||
```
|
||||
|
||||
***But what happens if `toHex` is called with a `Number` argument?***
|
||||
|
||||
### Remote Memory Disclosure
|
||||
|
||||
If an attacker can make your program call the `Buffer` constructor with a `Number`
|
||||
argument, then they can make it allocate uninitialized memory from the node.js process.
|
||||
This could potentially disclose TLS private keys, user data, or database passwords.
|
||||
|
||||
When the `Buffer` constructor is passed a `Number` argument, it returns an
|
||||
**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like
|
||||
this, you **MUST** overwrite the contents before returning it to the user.
|
||||
|
||||
From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size):
|
||||
|
||||
> `new Buffer(size)`
|
||||
>
|
||||
> - `size` Number
|
||||
>
|
||||
> The underlying memory for `Buffer` instances created in this way is not initialized.
|
||||
> **The contents of a newly created `Buffer` are unknown and could contain sensitive
|
||||
> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.
|
||||
|
||||
(Emphasis our own.)
|
||||
|
||||
Whenever the programmer intended to create an uninitialized `Buffer` you often see code
|
||||
like this:
|
||||
|
||||
```js
|
||||
var buf = new Buffer(16)
|
||||
|
||||
// Immediately overwrite the uninitialized buffer with data from another buffer
|
||||
for (var i = 0; i < buf.length; i++) {
|
||||
buf[i] = otherBuf[i]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Would this ever be a problem in real code?
|
||||
|
||||
Yes. It's surprisingly common to forget to check the type of your variables in a
|
||||
dynamically-typed language like JavaScript.
|
||||
|
||||
Usually the consequences of assuming the wrong type is that your program crashes with an
|
||||
uncaught exception. But the failure mode for forgetting to check the type of arguments to
|
||||
the `Buffer` constructor is more catastrophic.
|
||||
|
||||
Here's an example of a vulnerable service that takes a JSON payload and converts it to
|
||||
hex:
|
||||
|
||||
```js
|
||||
// Take a JSON payload {str: "some string"} and convert it to hex
|
||||
var server = http.createServer(function (req, res) {
|
||||
var data = ''
|
||||
req.setEncoding('utf8')
|
||||
req.on('data', function (chunk) {
|
||||
data += chunk
|
||||
})
|
||||
req.on('end', function () {
|
||||
var body = JSON.parse(data)
|
||||
res.end(new Buffer(body.str).toString('hex'))
|
||||
})
|
||||
})
|
||||
|
||||
server.listen(8080)
|
||||
```
|
||||
|
||||
In this example, an http client just has to send:
|
||||
|
||||
```json
|
||||
{
|
||||
"str": 1000
|
||||
}
|
||||
```
|
||||
|
||||
and it will get back 1,000 bytes of uninitialized memory from the server.
|
||||
|
||||
This is a very serious bug. It's similar in severity to the
|
||||
[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process
|
||||
memory by remote attackers.
|
||||
|
||||
|
||||
### Which real-world packages were vulnerable?
|
||||
|
||||
#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)
|
||||
|
||||
[Mathias Buus](https://github.com/mafintosh) and I
|
||||
([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages,
|
||||
[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow
|
||||
anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get
|
||||
them to reveal 20 bytes at a time of uninitialized memory from the node.js process.
|
||||
|
||||
Here's
|
||||
[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8)
|
||||
that fixed it. We released a new fixed version, created a
|
||||
[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all
|
||||
vulnerable versions on npm so users will get a warning to upgrade to a newer version.
|
||||
|
||||
#### [`ws`](https://www.npmjs.com/package/ws)
|
||||
|
||||
That got us wondering if there were other vulnerable packages. Sure enough, within a short
|
||||
period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the
|
||||
most popular WebSocket implementation in node.js.
|
||||
|
||||
If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as
|
||||
expected, then uninitialized server memory would be disclosed to the remote peer.
|
||||
|
||||
These were the vulnerable methods:
|
||||
|
||||
```js
|
||||
socket.send(number)
|
||||
socket.ping(number)
|
||||
socket.pong(number)
|
||||
```
|
||||
|
||||
Here's a vulnerable socket server with some echo functionality:
|
||||
|
||||
```js
|
||||
server.on('connection', function (socket) {
|
||||
socket.on('message', function (message) {
|
||||
message = JSON.parse(message)
|
||||
if (message.type === 'echo') {
|
||||
socket.send(message.data) // send back the user's message
|
||||
}
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
`socket.send(number)` called on the server, will disclose server memory.
|
||||
|
||||
Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue
|
||||
was fixed, with a more detailed explanation. Props to
|
||||
[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the
|
||||
[Node Security Project disclosure](https://nodesecurity.io/advisories/67).
|
||||
|
||||
|
||||
### What's the solution?
|
||||
|
||||
It's important that node.js offers a fast way to get memory otherwise performance-critical
|
||||
applications would needlessly get a lot slower.
|
||||
|
||||
But we need a better way to *signal our intent* as programmers. **When we want
|
||||
uninitialized memory, we should request it explicitly.**
|
||||
|
||||
Sensitive functionality should not be packed into a developer-friendly API that loosely
|
||||
accepts many different types. This type of API encourages the lazy practice of passing
|
||||
variables in without checking the type very carefully.
|
||||
|
||||
#### A new API: `Buffer.allocUnsafe(number)`
|
||||
|
||||
The functionality of creating buffers with uninitialized memory should be part of another
|
||||
API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that
|
||||
frequently gets user input of all sorts of different types passed into it.
|
||||
|
||||
```js
|
||||
var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory!
|
||||
|
||||
// Immediately overwrite the uninitialized buffer with data from another buffer
|
||||
for (var i = 0; i < buf.length; i++) {
|
||||
buf[i] = otherBuf[i]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### How do we fix node.js core?
|
||||
|
||||
We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as
|
||||
`semver-major`) which defends against one case:
|
||||
|
||||
```js
|
||||
var str = 16
|
||||
new Buffer(str, 'utf8')
|
||||
```
|
||||
|
||||
In this situation, it's implied that the programmer intended the first argument to be a
|
||||
string, since they passed an encoding as a second argument. Today, node.js will allocate
|
||||
uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not
|
||||
what the programmer intended.
|
||||
|
||||
But this is only a partial solution, since if the programmer does `new Buffer(variable)`
|
||||
(without an `encoding` parameter) there's no way to know what they intended. If `variable`
|
||||
is sometimes a number, then uninitialized memory will sometimes be returned.
|
||||
|
||||
### What's the real long-term fix?
|
||||
|
||||
We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when
|
||||
we need uninitialized memory. But that would break 1000s of packages.
|
||||
|
||||
~~We believe the best solution is to:~~
|
||||
|
||||
~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~
|
||||
|
||||
~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~
|
||||
|
||||
#### Update
|
||||
|
||||
We now support adding three new APIs:
|
||||
|
||||
- `Buffer.from(value)` - convert from any type to a buffer
|
||||
- `Buffer.alloc(size)` - create a zero-filled buffer
|
||||
- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size
|
||||
|
||||
This solves the core problem that affected `ws` and `bittorrent-dht` which is
|
||||
`Buffer(variable)` getting tricked into taking a number argument.
|
||||
|
||||
This way, existing code continues working and the impact on the npm ecosystem will be
|
||||
minimal. Over time, npm maintainers can migrate performance-critical code to use
|
||||
`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`.
|
||||
|
||||
|
||||
### Conclusion
|
||||
|
||||
We think there's a serious design issue with the `Buffer` API as it exists today. It
|
||||
promotes insecure software by putting high-risk functionality into a convenient API
|
||||
with friendly "developer ergonomics".
|
||||
|
||||
This wasn't merely a theoretical exercise because we found the issue in some of the
|
||||
most popular npm packages.
|
||||
|
||||
Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of
|
||||
`buffer`.
|
||||
|
||||
```js
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
```
|
||||
|
||||
Eventually, we hope that node.js core can switch to this new, safer behavior. We believe
|
||||
the impact on the ecosystem would be minimal since it's not a breaking change.
|
||||
Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while
|
||||
older, insecure packages would magically become safe from this attack vector.
|
||||
|
||||
|
||||
## links
|
||||
|
||||
- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514)
|
||||
- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67)
|
||||
- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68)
|
||||
|
||||
|
||||
## credit
|
||||
|
||||
The original issues in `bittorrent-dht`
|
||||
([disclosure](https://nodesecurity.io/advisories/68)) and
|
||||
`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by
|
||||
[Mathias Buus](https://github.com/mafintosh) and
|
||||
[Feross Aboukhadijeh](http://feross.org/).
|
||||
|
||||
Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues
|
||||
and for his work running the [Node Security Project](https://nodesecurity.io/).
|
||||
|
||||
Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and
|
||||
auditing the code.
|
||||
|
||||
|
||||
## license
|
||||
|
||||
MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)
|
||||
Generated
Vendored
+187
@@ -0,0 +1,187 @@
|
||||
declare module "safe-buffer" {
|
||||
export class Buffer {
|
||||
length: number
|
||||
write(string: string, offset?: number, length?: number, encoding?: string): number;
|
||||
toString(encoding?: string, start?: number, end?: number): string;
|
||||
toJSON(): { type: 'Buffer', data: any[] };
|
||||
equals(otherBuffer: Buffer): boolean;
|
||||
compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
|
||||
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
|
||||
slice(start?: number, end?: number): Buffer;
|
||||
writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUInt8(offset: number, noAssert?: boolean): number;
|
||||
readUInt16LE(offset: number, noAssert?: boolean): number;
|
||||
readUInt16BE(offset: number, noAssert?: boolean): number;
|
||||
readUInt32LE(offset: number, noAssert?: boolean): number;
|
||||
readUInt32BE(offset: number, noAssert?: boolean): number;
|
||||
readInt8(offset: number, noAssert?: boolean): number;
|
||||
readInt16LE(offset: number, noAssert?: boolean): number;
|
||||
readInt16BE(offset: number, noAssert?: boolean): number;
|
||||
readInt32LE(offset: number, noAssert?: boolean): number;
|
||||
readInt32BE(offset: number, noAssert?: boolean): number;
|
||||
readFloatLE(offset: number, noAssert?: boolean): number;
|
||||
readFloatBE(offset: number, noAssert?: boolean): number;
|
||||
readDoubleLE(offset: number, noAssert?: boolean): number;
|
||||
readDoubleBE(offset: number, noAssert?: boolean): number;
|
||||
swap16(): Buffer;
|
||||
swap32(): Buffer;
|
||||
swap64(): Buffer;
|
||||
writeUInt8(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt8(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
|
||||
fill(value: any, offset?: number, end?: number): this;
|
||||
indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
|
||||
lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
|
||||
includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
|
||||
|
||||
/**
|
||||
* Allocates a new buffer containing the given {str}.
|
||||
*
|
||||
* @param str String to store in buffer.
|
||||
* @param encoding encoding to use, optional. Default is 'utf8'
|
||||
*/
|
||||
constructor (str: string, encoding?: string);
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
*/
|
||||
constructor (size: number);
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
*/
|
||||
constructor (array: Uint8Array);
|
||||
/**
|
||||
* Produces a Buffer backed by the same allocated memory as
|
||||
* the given {ArrayBuffer}.
|
||||
*
|
||||
*
|
||||
* @param arrayBuffer The ArrayBuffer with which to share memory.
|
||||
*/
|
||||
constructor (arrayBuffer: ArrayBuffer);
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
*/
|
||||
constructor (array: any[]);
|
||||
/**
|
||||
* Copies the passed {buffer} data onto a new {Buffer} instance.
|
||||
*
|
||||
* @param buffer The buffer to copy.
|
||||
*/
|
||||
constructor (buffer: Buffer);
|
||||
prototype: Buffer;
|
||||
/**
|
||||
* Allocates a new Buffer using an {array} of octets.
|
||||
*
|
||||
* @param array
|
||||
*/
|
||||
static from(array: any[]): Buffer;
|
||||
/**
|
||||
* When passed a reference to the .buffer property of a TypedArray instance,
|
||||
* the newly created Buffer will share the same allocated memory as the TypedArray.
|
||||
* The optional {byteOffset} and {length} arguments specify a memory range
|
||||
* within the {arrayBuffer} that will be shared by the Buffer.
|
||||
*
|
||||
* @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
|
||||
* @param byteOffset
|
||||
* @param length
|
||||
*/
|
||||
static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
|
||||
/**
|
||||
* Copies the passed {buffer} data onto a new Buffer instance.
|
||||
*
|
||||
* @param buffer
|
||||
*/
|
||||
static from(buffer: Buffer): Buffer;
|
||||
/**
|
||||
* Creates a new Buffer containing the given JavaScript string {str}.
|
||||
* If provided, the {encoding} parameter identifies the character encoding.
|
||||
* If not provided, {encoding} defaults to 'utf8'.
|
||||
*
|
||||
* @param str
|
||||
*/
|
||||
static from(str: string, encoding?: string): Buffer;
|
||||
/**
|
||||
* Returns true if {obj} is a Buffer
|
||||
*
|
||||
* @param obj object to test.
|
||||
*/
|
||||
static isBuffer(obj: any): obj is Buffer;
|
||||
/**
|
||||
* Returns true if {encoding} is a valid encoding argument.
|
||||
* Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
|
||||
*
|
||||
* @param encoding string to test.
|
||||
*/
|
||||
static isEncoding(encoding: string): boolean;
|
||||
/**
|
||||
* Gives the actual byte length of a string. encoding defaults to 'utf8'.
|
||||
* This is not the same as String.prototype.length since that returns the number of characters in a string.
|
||||
*
|
||||
* @param string string to test.
|
||||
* @param encoding encoding used to evaluate (defaults to 'utf8')
|
||||
*/
|
||||
static byteLength(string: string, encoding?: string): number;
|
||||
/**
|
||||
* Returns a buffer which is the result of concatenating all the buffers in the list together.
|
||||
*
|
||||
* If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
|
||||
* If the list has exactly one item, then the first item of the list is returned.
|
||||
* If the list has more than one item, then a new Buffer is created.
|
||||
*
|
||||
* @param list An array of Buffer objects to concatenate
|
||||
* @param totalLength Total length of the buffers when concatenated.
|
||||
* If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
|
||||
*/
|
||||
static concat(list: Buffer[], totalLength?: number): Buffer;
|
||||
/**
|
||||
* The same as buf1.compare(buf2).
|
||||
*/
|
||||
static compare(buf1: Buffer, buf2: Buffer): number;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
* @param fill if specified, buffer will be initialized by calling buf.fill(fill).
|
||||
* If parameter is omitted, buffer will be filled with zeros.
|
||||
* @param encoding encoding used for call to buf.fill while initalizing
|
||||
*/
|
||||
static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents
|
||||
* of the newly created Buffer are unknown and may contain sensitive data.
|
||||
*
|
||||
* @param size count of octets to allocate
|
||||
*/
|
||||
static allocUnsafe(size: number): Buffer;
|
||||
/**
|
||||
* Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents
|
||||
* of the newly created Buffer are unknown and may contain sensitive data.
|
||||
*
|
||||
* @param size count of octets to allocate
|
||||
*/
|
||||
static allocUnsafeSlow(size: number): Buffer;
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
/* eslint-disable node/no-deprecated-api */
|
||||
var buffer = require('buffer')
|
||||
var Buffer = buffer.Buffer
|
||||
|
||||
// alternative to using Object.keys for old browsers
|
||||
function copyProps (src, dst) {
|
||||
for (var key in src) {
|
||||
dst[key] = src[key]
|
||||
}
|
||||
}
|
||||
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
|
||||
module.exports = buffer
|
||||
} else {
|
||||
// Copy properties from require('buffer')
|
||||
copyProps(buffer, exports)
|
||||
exports.Buffer = SafeBuffer
|
||||
}
|
||||
|
||||
function SafeBuffer (arg, encodingOrOffset, length) {
|
||||
return Buffer(arg, encodingOrOffset, length)
|
||||
}
|
||||
|
||||
// Copy static methods from Buffer
|
||||
copyProps(Buffer, SafeBuffer)
|
||||
|
||||
SafeBuffer.from = function (arg, encodingOrOffset, length) {
|
||||
if (typeof arg === 'number') {
|
||||
throw new TypeError('Argument must not be a number')
|
||||
}
|
||||
return Buffer(arg, encodingOrOffset, length)
|
||||
}
|
||||
|
||||
SafeBuffer.alloc = function (size, fill, encoding) {
|
||||
if (typeof size !== 'number') {
|
||||
throw new TypeError('Argument must be a number')
|
||||
}
|
||||
var buf = Buffer(size)
|
||||
if (fill !== undefined) {
|
||||
if (typeof encoding === 'string') {
|
||||
buf.fill(fill, encoding)
|
||||
} else {
|
||||
buf.fill(fill)
|
||||
}
|
||||
} else {
|
||||
buf.fill(0)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
SafeBuffer.allocUnsafe = function (size) {
|
||||
if (typeof size !== 'number') {
|
||||
throw new TypeError('Argument must be a number')
|
||||
}
|
||||
return Buffer(size)
|
||||
}
|
||||
|
||||
SafeBuffer.allocUnsafeSlow = function (size) {
|
||||
if (typeof size !== 'number') {
|
||||
throw new TypeError('Argument must be a number')
|
||||
}
|
||||
return buffer.SlowBuffer(size)
|
||||
}
|
||||
Generated
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"_from": "safe-buffer@^5.1.2",
|
||||
"_id": "safe-buffer@5.1.2",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||
"_location": "/request/safe-buffer",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "safe-buffer@^5.1.2",
|
||||
"name": "safe-buffer",
|
||||
"escapedName": "safe-buffer",
|
||||
"rawSpec": "^5.1.2",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^5.1.2"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/request"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||
"_shasum": "991ec69d296e0313747d59bdfd2b745c35f8828d",
|
||||
"_spec": "safe-buffer@^5.1.2",
|
||||
"_where": "/home/kevin/Documents/Sites/anissabensalah.net/user/themes/anissabensalah/node_modules/request",
|
||||
"author": {
|
||||
"name": "Feross Aboukhadijeh",
|
||||
"email": "feross@feross.org",
|
||||
"url": "http://feross.org"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/feross/safe-buffer/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "Safer Node.js Buffer API",
|
||||
"devDependencies": {
|
||||
"standard": "*",
|
||||
"tape": "^4.0.0"
|
||||
},
|
||||
"homepage": "https://github.com/feross/safe-buffer",
|
||||
"keywords": [
|
||||
"buffer",
|
||||
"buffer allocate",
|
||||
"node security",
|
||||
"safe",
|
||||
"safe-buffer",
|
||||
"security",
|
||||
"uninitialized"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "safe-buffer",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/feross/safe-buffer.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "standard && tape test/*.js"
|
||||
},
|
||||
"types": "index.d.ts",
|
||||
"version": "5.1.2"
|
||||
}
|
||||
+41
-46
@@ -1,34 +1,28 @@
|
||||
{
|
||||
"_args": [
|
||||
[
|
||||
"request@2.79.0",
|
||||
"/mnt/data/Sites/anissabensalah.net/user/themes/anissabensalah"
|
||||
]
|
||||
],
|
||||
"_development": true,
|
||||
"_from": "request@2.79.0",
|
||||
"_id": "request@2.79.0",
|
||||
"_from": "request@^2.88.0",
|
||||
"_id": "request@2.88.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-Tf5b9r6LjNw3/Pk+BLZVd3InEN4=",
|
||||
"_integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==",
|
||||
"_location": "/request",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "version",
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "request@2.79.0",
|
||||
"raw": "request@^2.88.0",
|
||||
"name": "request",
|
||||
"escapedName": "request",
|
||||
"rawSpec": "2.79.0",
|
||||
"rawSpec": "^2.88.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "2.79.0"
|
||||
"fetchSpec": "^2.88.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/node-gyp",
|
||||
"/node-sass"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/request/-/request-2.79.0.tgz",
|
||||
"_spec": "2.79.0",
|
||||
"_where": "/mnt/data/Sites/anissabensalah.net/user/themes/anissabensalah",
|
||||
"_resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz",
|
||||
"_shasum": "9c2fca4f7d35b592efe57c7f0a55e81052124fef",
|
||||
"_spec": "request@^2.88.0",
|
||||
"_where": "/home/kevin/Documents/Sites/anissabensalah.net/user/themes/anissabensalah/node_modules/node-sass",
|
||||
"author": {
|
||||
"name": "Mikeal Rogers",
|
||||
"email": "mikeal.rogers@gmail.com"
|
||||
@@ -36,40 +30,41 @@
|
||||
"bugs": {
|
||||
"url": "http://github.com/request/request/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"aws-sign2": "~0.6.0",
|
||||
"aws4": "^1.2.1",
|
||||
"caseless": "~0.11.0",
|
||||
"combined-stream": "~1.0.5",
|
||||
"extend": "~3.0.0",
|
||||
"aws-sign2": "~0.7.0",
|
||||
"aws4": "^1.8.0",
|
||||
"caseless": "~0.12.0",
|
||||
"combined-stream": "~1.0.6",
|
||||
"extend": "~3.0.2",
|
||||
"forever-agent": "~0.6.1",
|
||||
"form-data": "~2.1.1",
|
||||
"har-validator": "~2.0.6",
|
||||
"hawk": "~3.1.3",
|
||||
"http-signature": "~1.1.0",
|
||||
"form-data": "~2.3.2",
|
||||
"har-validator": "~5.1.0",
|
||||
"http-signature": "~1.2.0",
|
||||
"is-typedarray": "~1.0.0",
|
||||
"isstream": "~0.1.2",
|
||||
"json-stringify-safe": "~5.0.1",
|
||||
"mime-types": "~2.1.7",
|
||||
"oauth-sign": "~0.8.1",
|
||||
"qs": "~6.3.0",
|
||||
"stringstream": "~0.0.4",
|
||||
"tough-cookie": "~2.3.0",
|
||||
"tunnel-agent": "~0.4.1",
|
||||
"uuid": "^3.0.0"
|
||||
"mime-types": "~2.1.19",
|
||||
"oauth-sign": "~0.9.0",
|
||||
"performance-now": "^2.1.0",
|
||||
"qs": "~6.5.2",
|
||||
"safe-buffer": "^5.1.2",
|
||||
"tough-cookie": "~2.4.3",
|
||||
"tunnel-agent": "^0.6.0",
|
||||
"uuid": "^3.3.2"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Simplified HTTP request client.",
|
||||
"devDependencies": {
|
||||
"bluebird": "^3.2.1",
|
||||
"browserify": "^13.0.1",
|
||||
"browserify-istanbul": "^2.0.0",
|
||||
"buffer-equal": "^1.0.0",
|
||||
"codecov": "^1.0.1",
|
||||
"coveralls": "^2.11.4",
|
||||
"eslint": "^2.5.3",
|
||||
"codecov": "^3.0.4",
|
||||
"coveralls": "^3.0.2",
|
||||
"function-bind": "^1.0.2",
|
||||
"istanbul": "^0.4.0",
|
||||
"karma": "^1.1.1",
|
||||
"karma": "^3.0.0",
|
||||
"karma-browserify": "^5.0.1",
|
||||
"karma-cli": "^1.0.0",
|
||||
"karma-coverage": "^1.0.0",
|
||||
@@ -78,6 +73,7 @@
|
||||
"phantomjs-prebuilt": "^2.1.3",
|
||||
"rimraf": "^2.2.8",
|
||||
"server-destroy": "^1.0.1",
|
||||
"standard": "^9.0.0",
|
||||
"tape": "^4.6.0",
|
||||
"taper": "^0.5.0"
|
||||
},
|
||||
@@ -91,12 +87,17 @@
|
||||
],
|
||||
"greenkeeper": {
|
||||
"ignore": [
|
||||
"eslint",
|
||||
"hawk",
|
||||
"har-validator"
|
||||
]
|
||||
},
|
||||
"homepage": "https://github.com/request/request#readme",
|
||||
"keywords": [
|
||||
"http",
|
||||
"simple",
|
||||
"util",
|
||||
"utility"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"main": "index.js",
|
||||
"name": "request",
|
||||
@@ -105,17 +106,11 @@
|
||||
"url": "git+https://github.com/request/request.git"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint lib/ *.js tests/ && echo Lint passed.",
|
||||
"lint": "standard",
|
||||
"test": "npm run lint && npm run test-ci && npm run test-browser",
|
||||
"test-browser": "node tests/browser/start.js",
|
||||
"test-ci": "taper tests/test-*.js",
|
||||
"test-cov": "istanbul cover tape tests/test-*.js"
|
||||
},
|
||||
"tags": [
|
||||
"http",
|
||||
"simple",
|
||||
"util",
|
||||
"utility"
|
||||
],
|
||||
"version": "2.79.0"
|
||||
"version": "2.88.0"
|
||||
}
|
||||
|
||||
+206
-130
@@ -1,46 +1,46 @@
|
||||
'use strict'
|
||||
|
||||
var http = require('http')
|
||||
, https = require('https')
|
||||
, url = require('url')
|
||||
, util = require('util')
|
||||
, stream = require('stream')
|
||||
, zlib = require('zlib')
|
||||
, hawk = require('hawk')
|
||||
, aws2 = require('aws-sign2')
|
||||
, aws4 = require('aws4')
|
||||
, httpSignature = require('http-signature')
|
||||
, mime = require('mime-types')
|
||||
, stringstream = require('stringstream')
|
||||
, caseless = require('caseless')
|
||||
, ForeverAgent = require('forever-agent')
|
||||
, FormData = require('form-data')
|
||||
, extend = require('extend')
|
||||
, isstream = require('isstream')
|
||||
, isTypedArray = require('is-typedarray').strict
|
||||
, helpers = require('./lib/helpers')
|
||||
, cookies = require('./lib/cookies')
|
||||
, getProxyFromURI = require('./lib/getProxyFromURI')
|
||||
, Querystring = require('./lib/querystring').Querystring
|
||||
, Har = require('./lib/har').Har
|
||||
, Auth = require('./lib/auth').Auth
|
||||
, OAuth = require('./lib/oauth').OAuth
|
||||
, Multipart = require('./lib/multipart').Multipart
|
||||
, Redirect = require('./lib/redirect').Redirect
|
||||
, Tunnel = require('./lib/tunnel').Tunnel
|
||||
var https = require('https')
|
||||
var url = require('url')
|
||||
var util = require('util')
|
||||
var stream = require('stream')
|
||||
var zlib = require('zlib')
|
||||
var aws2 = require('aws-sign2')
|
||||
var aws4 = require('aws4')
|
||||
var httpSignature = require('http-signature')
|
||||
var mime = require('mime-types')
|
||||
var caseless = require('caseless')
|
||||
var ForeverAgent = require('forever-agent')
|
||||
var FormData = require('form-data')
|
||||
var extend = require('extend')
|
||||
var isstream = require('isstream')
|
||||
var isTypedArray = require('is-typedarray').strict
|
||||
var helpers = require('./lib/helpers')
|
||||
var cookies = require('./lib/cookies')
|
||||
var getProxyFromURI = require('./lib/getProxyFromURI')
|
||||
var Querystring = require('./lib/querystring').Querystring
|
||||
var Har = require('./lib/har').Har
|
||||
var Auth = require('./lib/auth').Auth
|
||||
var OAuth = require('./lib/oauth').OAuth
|
||||
var hawk = require('./lib/hawk')
|
||||
var Multipart = require('./lib/multipart').Multipart
|
||||
var Redirect = require('./lib/redirect').Redirect
|
||||
var Tunnel = require('./lib/tunnel').Tunnel
|
||||
var now = require('performance-now')
|
||||
var Buffer = require('safe-buffer').Buffer
|
||||
|
||||
var safeStringify = helpers.safeStringify
|
||||
, isReadStream = helpers.isReadStream
|
||||
, toBase64 = helpers.toBase64
|
||||
, defer = helpers.defer
|
||||
, copy = helpers.copy
|
||||
, version = helpers.version
|
||||
, globalCookieJar = cookies.jar()
|
||||
|
||||
var isReadStream = helpers.isReadStream
|
||||
var toBase64 = helpers.toBase64
|
||||
var defer = helpers.defer
|
||||
var copy = helpers.copy
|
||||
var version = helpers.version
|
||||
var globalCookieJar = cookies.jar()
|
||||
|
||||
var globalPool = {}
|
||||
|
||||
function filterForNonReserved(reserved, options) {
|
||||
function filterForNonReserved (reserved, options) {
|
||||
// Filter out properties that are not reserved.
|
||||
// Reserved values are passed in at call site.
|
||||
|
||||
@@ -54,7 +54,7 @@ function filterForNonReserved(reserved, options) {
|
||||
return object
|
||||
}
|
||||
|
||||
function filterOutReservedFunctions(reserved, options) {
|
||||
function filterOutReservedFunctions (reserved, options) {
|
||||
// Filter out properties that are functions and are reserved.
|
||||
// Reserved values are passed in at call site.
|
||||
|
||||
@@ -67,11 +67,10 @@ function filterOutReservedFunctions(reserved, options) {
|
||||
}
|
||||
}
|
||||
return object
|
||||
|
||||
}
|
||||
|
||||
// Return a simpler request object to allow serialization
|
||||
function requestToJSON() {
|
||||
function requestToJSON () {
|
||||
var self = this
|
||||
return {
|
||||
uri: self.uri,
|
||||
@@ -81,7 +80,7 @@ function requestToJSON() {
|
||||
}
|
||||
|
||||
// Return a simpler response object to allow serialization
|
||||
function responseToJSON() {
|
||||
function responseToJSON () {
|
||||
var self = this
|
||||
return {
|
||||
statusCode: self.statusCode,
|
||||
@@ -132,7 +131,7 @@ util.inherits(Request, stream.Stream)
|
||||
|
||||
// Debugging
|
||||
Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
|
||||
function debug() {
|
||||
function debug () {
|
||||
if (Request.debug) {
|
||||
console.error('REQUEST %s', util.format.apply(util, arguments))
|
||||
}
|
||||
@@ -256,7 +255,7 @@ Request.prototype.init = function (options) {
|
||||
self.rejectUnauthorized = false
|
||||
}
|
||||
|
||||
if (!self.uri.pathname) {self.uri.pathname = '/'}
|
||||
if (!self.uri.pathname) { self.uri.pathname = '/' }
|
||||
|
||||
if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
|
||||
// Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
|
||||
@@ -288,11 +287,12 @@ Request.prototype.init = function (options) {
|
||||
self.setHost = false
|
||||
if (!self.hasHeader('host')) {
|
||||
var hostHeaderName = self.originalHostHeaderName || 'host'
|
||||
self.setHeader(hostHeaderName, self.uri.hostname)
|
||||
self.setHeader(hostHeaderName, self.uri.host)
|
||||
// Drop :port suffix from Host header if known protocol.
|
||||
if (self.uri.port) {
|
||||
if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
|
||||
!(self.uri.port === 443 && self.uri.protocol === 'https:') ) {
|
||||
self.setHeader(hostHeaderName, self.getHeader('host') + (':' + self.uri.port) )
|
||||
if ((self.uri.port === '80' && self.uri.protocol === 'http:') ||
|
||||
(self.uri.port === '443' && self.uri.protocol === 'https:')) {
|
||||
self.setHeader(hostHeaderName, self.uri.hostname)
|
||||
}
|
||||
}
|
||||
self.setHost = true
|
||||
@@ -301,8 +301,7 @@ Request.prototype.init = function (options) {
|
||||
self.jar(self._jar || options.jar)
|
||||
|
||||
if (!self.uri.port) {
|
||||
if (self.uri.protocol === 'http:') {self.uri.port = 80}
|
||||
else if (self.uri.protocol === 'https:') {self.uri.port = 443}
|
||||
if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 }
|
||||
}
|
||||
|
||||
if (self.proxy && !self.tunnel) {
|
||||
@@ -389,12 +388,12 @@ Request.prototype.init = function (options) {
|
||||
}
|
||||
|
||||
if (self.uri.auth && !self.hasHeader('authorization')) {
|
||||
var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
|
||||
var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) })
|
||||
self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
|
||||
}
|
||||
|
||||
if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
|
||||
var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
|
||||
var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) })
|
||||
var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
|
||||
self.setHeader('proxy-authorization', authHeader)
|
||||
}
|
||||
@@ -412,23 +411,23 @@ Request.prototype.init = function (options) {
|
||||
|
||||
if (options.time) {
|
||||
self.timing = true
|
||||
|
||||
// NOTE: elapsedTime is deprecated in favor of .timings
|
||||
self.elapsedTime = self.elapsedTime || 0
|
||||
}
|
||||
|
||||
function setContentLength () {
|
||||
if (isTypedArray(self.body)) {
|
||||
self.body = new Buffer(self.body)
|
||||
self.body = Buffer.from(self.body)
|
||||
}
|
||||
|
||||
if (!self.hasHeader('content-length')) {
|
||||
var length
|
||||
if (typeof self.body === 'string') {
|
||||
length = Buffer.byteLength(self.body)
|
||||
}
|
||||
else if (Array.isArray(self.body)) {
|
||||
length = self.body.reduce(function (a, b) {return a + b.length}, 0)
|
||||
}
|
||||
else {
|
||||
} else if (Array.isArray(self.body)) {
|
||||
length = self.body.reduce(function (a, b) { return a + b.length }, 0)
|
||||
} else {
|
||||
length = self.body.length
|
||||
}
|
||||
|
||||
@@ -450,8 +449,8 @@ Request.prototype.init = function (options) {
|
||||
}
|
||||
|
||||
var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
|
||||
, defaultModules = {'http:':http, 'https:':https}
|
||||
, httpModules = self.httpModules || {}
|
||||
var defaultModules = {'http:': http, 'https:': https}
|
||||
var httpModules = self.httpModules || {}
|
||||
|
||||
self.httpModule = httpModules[protocol] || defaultModules[protocol]
|
||||
|
||||
@@ -516,9 +515,9 @@ Request.prototype.init = function (options) {
|
||||
}
|
||||
}
|
||||
|
||||
// self.on('pipe', function () {
|
||||
// console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
|
||||
// })
|
||||
// self.on('pipe', function () {
|
||||
// console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
|
||||
// })
|
||||
})
|
||||
|
||||
defer(function () {
|
||||
@@ -530,8 +529,7 @@ Request.prototype.init = function (options) {
|
||||
if (self._form) {
|
||||
if (!self._auth.hasAuth) {
|
||||
self._form.pipe(self)
|
||||
}
|
||||
else if (self._auth.hasAuth && self._auth.sentAuth) {
|
||||
} else if (self._auth.hasAuth && self._auth.sentAuth) {
|
||||
self._form.pipe(self)
|
||||
}
|
||||
}
|
||||
@@ -582,7 +580,6 @@ Request.prototype.init = function (options) {
|
||||
|
||||
self.ntick = true
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
Request.prototype.getNewAgent = function () {
|
||||
@@ -713,6 +710,16 @@ Request.prototype.start = function () {
|
||||
// this is usually called on the first write(), end() or on nextTick()
|
||||
var self = this
|
||||
|
||||
if (self.timing) {
|
||||
// All timings will be relative to this request's startTime. In order to do this,
|
||||
// we need to capture the wall-clock start time (via Date), immediately followed
|
||||
// by the high-resolution timer (via now()). While these two won't be set
|
||||
// at the _exact_ same time, they should be close enough to be able to calculate
|
||||
// high-resolution, monotonically non-decreasing timestamps relative to startTime.
|
||||
var startTime = new Date().getTime()
|
||||
var startTimeNow = now()
|
||||
}
|
||||
|
||||
if (self._aborted) {
|
||||
return
|
||||
}
|
||||
@@ -748,7 +755,12 @@ Request.prototype.start = function () {
|
||||
}
|
||||
|
||||
if (self.timing) {
|
||||
self.startTime = new Date().getTime()
|
||||
self.startTime = startTime
|
||||
self.startTimeNow = startTimeNow
|
||||
|
||||
// Timing values will all be relative to startTime (by comparing to startTimeNow
|
||||
// so we have an accurate clock)
|
||||
self.timings = {}
|
||||
}
|
||||
|
||||
var timeout
|
||||
@@ -762,11 +774,37 @@ Request.prototype.start = function () {
|
||||
|
||||
self.req.on('response', self.onRequestResponse.bind(self))
|
||||
self.req.on('error', self.onRequestError.bind(self))
|
||||
self.req.on('drain', function() {
|
||||
self.req.on('drain', function () {
|
||||
self.emit('drain')
|
||||
})
|
||||
self.req.on('socket', function(socket) {
|
||||
var setReqTimeout = function() {
|
||||
|
||||
self.req.on('socket', function (socket) {
|
||||
// `._connecting` was the old property which was made public in node v6.1.0
|
||||
var isConnecting = socket._connecting || socket.connecting
|
||||
if (self.timing) {
|
||||
self.timings.socket = now() - self.startTimeNow
|
||||
|
||||
if (isConnecting) {
|
||||
var onLookupTiming = function () {
|
||||
self.timings.lookup = now() - self.startTimeNow
|
||||
}
|
||||
|
||||
var onConnectTiming = function () {
|
||||
self.timings.connect = now() - self.startTimeNow
|
||||
}
|
||||
|
||||
socket.once('lookup', onLookupTiming)
|
||||
socket.once('connect', onConnectTiming)
|
||||
|
||||
// clean up timing event listeners if needed on error
|
||||
self.req.once('error', function () {
|
||||
socket.removeListener('lookup', onLookupTiming)
|
||||
socket.removeListener('connect', onConnectTiming)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var setReqTimeout = function () {
|
||||
// This timeout sets the amount of time to wait *between* bytes sent
|
||||
// from the server once connected.
|
||||
//
|
||||
@@ -782,15 +820,13 @@ Request.prototype.start = function () {
|
||||
}
|
||||
})
|
||||
}
|
||||
// `._connecting` was the old property which was made public in node v6.1.0
|
||||
var isConnecting = socket._connecting || socket.connecting
|
||||
if (timeout !== undefined) {
|
||||
// Only start the connection timer if we're actually connecting a new
|
||||
// socket, otherwise if we're already connected (because this is a
|
||||
// keep-alive connection) do not bother. This is important since we won't
|
||||
// get a 'connect' event for an already connected socket.
|
||||
if (isConnecting) {
|
||||
var onReqSockConnect = function() {
|
||||
var onReqSockConnect = function () {
|
||||
socket.removeListener('connect', onReqSockConnect)
|
||||
clearTimeout(self.timeoutTimer)
|
||||
self.timeoutTimer = null
|
||||
@@ -799,7 +835,7 @@ Request.prototype.start = function () {
|
||||
|
||||
socket.on('connect', onReqSockConnect)
|
||||
|
||||
self.req.on('error', function(err) {
|
||||
self.req.on('error', function (err) { // eslint-disable-line handle-callback-err
|
||||
socket.removeListener('connect', onReqSockConnect)
|
||||
})
|
||||
|
||||
@@ -831,8 +867,8 @@ Request.prototype.onRequestError = function (error) {
|
||||
if (self._aborted) {
|
||||
return
|
||||
}
|
||||
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
|
||||
&& self.agent.addRequestNoreuse) {
|
||||
if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
|
||||
self.agent.addRequestNoreuse) {
|
||||
self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
|
||||
self.start()
|
||||
self.req.end()
|
||||
@@ -847,12 +883,52 @@ Request.prototype.onRequestError = function (error) {
|
||||
|
||||
Request.prototype.onRequestResponse = function (response) {
|
||||
var self = this
|
||||
|
||||
if (self.timing) {
|
||||
self.timings.response = now() - self.startTimeNow
|
||||
}
|
||||
|
||||
debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
|
||||
response.on('end', function() {
|
||||
response.on('end', function () {
|
||||
if (self.timing) {
|
||||
self.elapsedTime += (new Date().getTime() - self.startTime)
|
||||
debug('elapsed time', self.elapsedTime)
|
||||
self.timings.end = now() - self.startTimeNow
|
||||
response.timingStart = self.startTime
|
||||
|
||||
// fill in the blanks for any periods that didn't trigger, such as
|
||||
// no lookup or connect due to keep alive
|
||||
if (!self.timings.socket) {
|
||||
self.timings.socket = 0
|
||||
}
|
||||
if (!self.timings.lookup) {
|
||||
self.timings.lookup = self.timings.socket
|
||||
}
|
||||
if (!self.timings.connect) {
|
||||
self.timings.connect = self.timings.lookup
|
||||
}
|
||||
if (!self.timings.response) {
|
||||
self.timings.response = self.timings.connect
|
||||
}
|
||||
|
||||
debug('elapsed time', self.timings.end)
|
||||
|
||||
// elapsedTime includes all redirects
|
||||
self.elapsedTime += Math.round(self.timings.end)
|
||||
|
||||
// NOTE: elapsedTime is deprecated in favor of .timings
|
||||
response.elapsedTime = self.elapsedTime
|
||||
|
||||
// timings is just for the final fetch
|
||||
response.timings = self.timings
|
||||
|
||||
// pre-calculate phase timings as well
|
||||
response.timingPhases = {
|
||||
wait: self.timings.socket,
|
||||
dns: self.timings.lookup - self.timings.socket,
|
||||
tcp: self.timings.connect - self.timings.lookup,
|
||||
firstByte: self.timings.response - self.timings.connect,
|
||||
download: self.timings.end - self.timings.response,
|
||||
total: self.timings.end
|
||||
}
|
||||
}
|
||||
debug('response end', self.uri.href, response.statusCode, response.headers)
|
||||
})
|
||||
@@ -869,8 +945,8 @@ Request.prototype.onRequestResponse = function (response) {
|
||||
|
||||
// XXX This is different on 0.10, because SSL is strict by default
|
||||
if (self.httpModule === https &&
|
||||
self.strictSSL && (!response.hasOwnProperty('socket') ||
|
||||
!response.socket.authorized)) {
|
||||
self.strictSSL && (!response.hasOwnProperty('socket') ||
|
||||
!response.socket.authorized)) {
|
||||
debug('strict ssl error', self.uri.href)
|
||||
var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
|
||||
self.emit('error', new Error('SSL Error: ' + sslErr))
|
||||
@@ -895,7 +971,7 @@ Request.prototype.onRequestResponse = function (response) {
|
||||
|
||||
var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
|
||||
var addCookie = function (cookie) {
|
||||
//set the cookie if it's domain in the href's domain.
|
||||
// set the cookie if it's domain in the href's domain.
|
||||
try {
|
||||
targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
|
||||
} catch (e) {
|
||||
@@ -931,13 +1007,13 @@ Request.prototype.onRequestResponse = function (response) {
|
||||
|
||||
var noBody = function (code) {
|
||||
return (
|
||||
self.method === 'HEAD'
|
||||
self.method === 'HEAD' ||
|
||||
// Informational
|
||||
|| (code >= 100 && code < 200)
|
||||
(code >= 100 && code < 200) ||
|
||||
// No Content
|
||||
|| code === 204
|
||||
code === 204 ||
|
||||
// Not Modified
|
||||
|| code === 304
|
||||
code === 304
|
||||
)
|
||||
}
|
||||
|
||||
@@ -946,11 +1022,20 @@ Request.prototype.onRequestResponse = function (response) {
|
||||
var contentEncoding = response.headers['content-encoding'] || 'identity'
|
||||
contentEncoding = contentEncoding.trim().toLowerCase()
|
||||
|
||||
// Be more lenient with decoding compressed responses, since (very rarely)
|
||||
// servers send slightly invalid gzip responses that are still accepted
|
||||
// by common browsers.
|
||||
// Always using Z_SYNC_FLUSH is what cURL does.
|
||||
var zlibOptions = {
|
||||
flush: zlib.Z_SYNC_FLUSH,
|
||||
finishFlush: zlib.Z_SYNC_FLUSH
|
||||
}
|
||||
|
||||
if (contentEncoding === 'gzip') {
|
||||
responseContent = zlib.createGunzip()
|
||||
responseContent = zlib.createGunzip(zlibOptions)
|
||||
response.pipe(responseContent)
|
||||
} else if (contentEncoding === 'deflate') {
|
||||
responseContent = zlib.createInflate()
|
||||
responseContent = zlib.createInflate(zlibOptions)
|
||||
response.pipe(responseContent)
|
||||
} else {
|
||||
// Since previous versions didn't check for Content-Encoding header,
|
||||
@@ -967,13 +1052,8 @@ Request.prototype.onRequestResponse = function (response) {
|
||||
if (self.encoding) {
|
||||
if (self.dests.length !== 0) {
|
||||
console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
|
||||
} else if (responseContent.setEncoding) {
|
||||
responseContent.setEncoding(self.encoding)
|
||||
} else {
|
||||
// Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
|
||||
// zlib streams.
|
||||
// If/When support for 0.9.4 is dropped, this should be unnecessary.
|
||||
responseContent = responseContent.pipe(stringstream(self.encoding))
|
||||
responseContent.setEncoding(self.encoding)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -992,6 +1072,8 @@ Request.prototype.onRequestResponse = function (response) {
|
||||
responseContent.on('data', function (chunk) {
|
||||
if (self.timing && !self.responseStarted) {
|
||||
self.responseStartTime = (new Date()).getTime()
|
||||
|
||||
// NOTE: responseStartTime is deprecated in favor of .timings
|
||||
response.responseStartTime = self.responseStartTime
|
||||
}
|
||||
self._destdata = true
|
||||
@@ -1003,13 +1085,11 @@ Request.prototype.onRequestResponse = function (response) {
|
||||
responseContent.on('error', function (error) {
|
||||
self.emit('error', error)
|
||||
})
|
||||
responseContent.on('close', function () {self.emit('close')})
|
||||
responseContent.on('close', function () { self.emit('close') })
|
||||
|
||||
if (self.callback) {
|
||||
self.readResponseBody(response)
|
||||
}
|
||||
//if no callback
|
||||
else {
|
||||
} else { // if no callback
|
||||
self.on('end', function () {
|
||||
if (self._aborted) {
|
||||
debug('aborted', self.uri.href)
|
||||
@@ -1024,10 +1104,10 @@ Request.prototype.onRequestResponse = function (response) {
|
||||
|
||||
Request.prototype.readResponseBody = function (response) {
|
||||
var self = this
|
||||
debug('reading response\'s body')
|
||||
debug("reading response's body")
|
||||
var buffers = []
|
||||
, bufferLength = 0
|
||||
, strings = []
|
||||
var bufferLength = 0
|
||||
var strings = []
|
||||
|
||||
self.on('data', function (chunk) {
|
||||
if (!Buffer.isBuffer(chunk)) {
|
||||
@@ -1076,7 +1156,7 @@ Request.prototype.readResponseBody = function (response) {
|
||||
}
|
||||
debug('emitting complete', self.uri.href)
|
||||
if (typeof response.body === 'undefined' && !self._json) {
|
||||
response.body = self.encoding === null ? new Buffer(0) : ''
|
||||
response.body = self.encoding === null ? Buffer.alloc(0) : ''
|
||||
}
|
||||
self.emit('complete', response, response.body)
|
||||
})
|
||||
@@ -1088,8 +1168,7 @@ Request.prototype.abort = function () {
|
||||
|
||||
if (self.req) {
|
||||
self.req.abort()
|
||||
}
|
||||
else if (self.response) {
|
||||
} else if (self.response) {
|
||||
self.response.destroy()
|
||||
}
|
||||
|
||||
@@ -1105,8 +1184,7 @@ Request.prototype.pipeDest = function (dest) {
|
||||
var ctname = response.caseless.has('content-type')
|
||||
if (dest.setHeader) {
|
||||
dest.setHeader(ctname, response.headers[ctname])
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
dest.headers[ctname] = response.headers[ctname]
|
||||
}
|
||||
}
|
||||
@@ -1177,7 +1255,7 @@ Request.prototype.form = function (form) {
|
||||
}
|
||||
// create form-data object
|
||||
self._form = new FormData()
|
||||
self._form.on('error', function(err) {
|
||||
self._form.on('error', function (err) {
|
||||
err.message = 'form-data: ' + err.message
|
||||
self.emit('error', err)
|
||||
self.abort()
|
||||
@@ -1252,8 +1330,8 @@ Request.prototype.getHeader = function (name, headers) {
|
||||
Request.prototype.enableUnixSocket = function () {
|
||||
// Get the socket & request paths from the URL
|
||||
var unixParts = this.uri.path.split(':')
|
||||
, host = unixParts[0]
|
||||
, path = unixParts[1]
|
||||
var host = unixParts[0]
|
||||
var path = unixParts[1]
|
||||
// Apply unix properties to request
|
||||
this.socketPath = host
|
||||
this.uri.pathname = path
|
||||
@@ -1263,7 +1341,6 @@ Request.prototype.enableUnixSocket = function () {
|
||||
this.uri.isUnix = true
|
||||
}
|
||||
|
||||
|
||||
Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
|
||||
var self = this
|
||||
|
||||
@@ -1279,17 +1356,18 @@ Request.prototype.aws = function (opts, now) {
|
||||
return self
|
||||
}
|
||||
|
||||
if (opts.sign_version == 4 || opts.sign_version == '4') {
|
||||
if (opts.sign_version === 4 || opts.sign_version === '4') {
|
||||
// use aws4
|
||||
var options = {
|
||||
host: self.uri.host,
|
||||
path: self.uri.path,
|
||||
method: self.method,
|
||||
headers: {
|
||||
'content-type': self.getHeader('content-type') || ''
|
||||
},
|
||||
headers: self.headers,
|
||||
body: self.body
|
||||
}
|
||||
if (opts.service) {
|
||||
options.service = opts.service
|
||||
}
|
||||
var signRes = aws4.sign(options, {
|
||||
accessKeyId: opts.key,
|
||||
secretAccessKey: opts.secret,
|
||||
@@ -1300,20 +1378,19 @@ Request.prototype.aws = function (opts, now) {
|
||||
if (signRes.headers['X-Amz-Security-Token']) {
|
||||
self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
|
||||
}
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
// default: use aws-sign2
|
||||
var date = new Date()
|
||||
self.setHeader('date', date.toUTCString())
|
||||
var auth =
|
||||
{ key: opts.key
|
||||
, secret: opts.secret
|
||||
, verb: self.method.toUpperCase()
|
||||
, date: date
|
||||
, contentType: self.getHeader('content-type') || ''
|
||||
, md5: self.getHeader('content-md5') || ''
|
||||
, amazonHeaders: aws2.canonicalizeHeaders(self.headers)
|
||||
}
|
||||
var auth = {
|
||||
key: opts.key,
|
||||
secret: opts.secret,
|
||||
verb: self.method.toUpperCase(),
|
||||
date: date,
|
||||
contentType: self.getHeader('content-type') || '',
|
||||
md5: self.getHeader('content-md5') || '',
|
||||
amazonHeaders: aws2.canonicalizeHeaders(self.headers)
|
||||
}
|
||||
var path = self.uri.path
|
||||
if (opts.bucket && path) {
|
||||
auth.resource = '/' + opts.bucket + path
|
||||
@@ -1333,10 +1410,10 @@ Request.prototype.aws = function (opts, now) {
|
||||
Request.prototype.httpSignature = function (opts) {
|
||||
var self = this
|
||||
httpSignature.signRequest({
|
||||
getHeader: function(header) {
|
||||
getHeader: function (header) {
|
||||
return self.getHeader(header, self.headers)
|
||||
},
|
||||
setHeader: function(header, value) {
|
||||
setHeader: function (header, value) {
|
||||
self.setHeader(header, value)
|
||||
},
|
||||
method: self.method,
|
||||
@@ -1348,7 +1425,7 @@ Request.prototype.httpSignature = function (opts) {
|
||||
}
|
||||
Request.prototype.hawk = function (opts) {
|
||||
var self = this
|
||||
self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
|
||||
self.setHeader('Authorization', hawk.header(self.uri, self.method, opts))
|
||||
}
|
||||
Request.prototype.oauth = function (_oauth) {
|
||||
var self = this
|
||||
@@ -1373,13 +1450,13 @@ Request.prototype.jar = function (jar) {
|
||||
} else {
|
||||
var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
|
||||
var urihref = self.uri.href
|
||||
//fetch cookie in the Specified host
|
||||
// fetch cookie in the Specified host
|
||||
if (targetCookieJar) {
|
||||
cookies = targetCookieJar.getCookieString(urihref)
|
||||
}
|
||||
}
|
||||
|
||||
//if need cookie and cookie is not empty
|
||||
// if need cookie and cookie is not empty
|
||||
if (cookies && cookies.length) {
|
||||
if (self.originalCookieHeader) {
|
||||
// Don't overwrite existing Cookie header
|
||||
@@ -1392,7 +1469,6 @@ Request.prototype.jar = function (jar) {
|
||||
return self
|
||||
}
|
||||
|
||||
|
||||
// Stream API
|
||||
Request.prototype.pipe = function (dest, opts) {
|
||||
var self = this
|
||||
@@ -1415,7 +1491,7 @@ Request.prototype.pipe = function (dest, opts) {
|
||||
}
|
||||
Request.prototype.write = function () {
|
||||
var self = this
|
||||
if (self._aborted) {return}
|
||||
if (self._aborted) { return }
|
||||
|
||||
if (!self._started) {
|
||||
self.start()
|
||||
@@ -1426,7 +1502,7 @@ Request.prototype.write = function () {
|
||||
}
|
||||
Request.prototype.end = function (chunk) {
|
||||
var self = this
|
||||
if (self._aborted) {return}
|
||||
if (self._aborted) { return }
|
||||
|
||||
if (chunk) {
|
||||
self.write(chunk)
|
||||
|
||||
Reference in New Issue
Block a user