@automattic/request-promise-native 2.0.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2020, Nicolai Kamenzky and contributors
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@@ -0,0 +1,130 @@
1
+ <a href="http://promisesaplus.com/">
2
+ <img src="https://promises-aplus.github.io/promises-spec/assets/logo-small.png" align="right" alt="Promises/A+ logo" />
3
+ </a>
4
+
5
+ # request-promise-core
6
+
7
+ [![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square&maxAge=2592000)](https://gitter.im/request/request-promise?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
8
+ [![Build Status](https://img.shields.io/travis/request/promise-core/master.svg?style=flat-square&maxAge=2592000)](https://travis-ci.org/request/promise-core)
9
+ [![Coverage Status](https://img.shields.io/coveralls/request/promise-core.svg?style=flat-square&maxAge=2592000)](https://coveralls.io/r/request/promise-core)
10
+ [![Dependency Status](https://img.shields.io/david/request/promise-core.svg?style=flat-square&maxAge=2592000)](https://david-dm.org/request/promise-core)
11
+ [![Known Vulnerabilities](https://snyk.io/test/npm/promise-core/badge.svg?style=flat-square&maxAge=2592000)](https://snyk.io/test/npm/promise-core)
12
+
13
+
14
+ This package is the core for the following packages:
15
+
16
+ - [`request-promise`](https://github.com/request/request-promise)
17
+ - [`request-promise-any`](https://github.com/request/request-promise-any)
18
+ - [`request-promise-bluebird`](https://github.com/request/request-promise-bluebird)
19
+ - [`request-promise-native`](https://github.com/request/request-promise-native)
20
+
21
+ `request-promise-core` contains the core logic to add Promise support to [`request`](https://github.com/request/request).
22
+
23
+ Please use one of the libraries above. It is only recommended to use this library directly, if you have very specific requirements.
24
+
25
+ ## Installation for `request@^2.34`
26
+
27
+ This module is installed via npm:
28
+
29
+ ```
30
+ npm install --save request
31
+ npm install --save request-promise-core
32
+ ```
33
+
34
+ `request` is defined as a peer-dependency and thus has to be installed separately.
35
+
36
+ ## Usage for `request@^2.34`
37
+
38
+ ``` js
39
+ // 1. Load the request library
40
+
41
+ // Only use a direct require if you are 100% sure that:
42
+ // - Your project does not use request directly. That is without the Promise capabilities by calling require('request').
43
+ // - Any of the installed libraries use request.
44
+ // ...because Request's prototype will be patched in step 2.
45
+ /* var request = require('request'); */
46
+
47
+ // Instead use:
48
+ var stealthyRequire = require('stealthy-require');
49
+ var request = stealthyRequire(require.cache, function () {
50
+ return require('request');
51
+ });
52
+
53
+
54
+ // 2. Add Promise support to request
55
+
56
+ var configure = require('request-promise-core/configure/request2');
57
+
58
+ configure({
59
+ request: request,
60
+ // Pass your favorite ES6-compatible promise implementation
61
+ PromiseImpl: Promise,
62
+ // Expose all methods of the promise instance you want to call on the request(...) call
63
+ expose: [
64
+ 'then', // Allows to use request(...).then(...)
65
+ 'catch', // Allows to use request(...).catch(...)
66
+ 'promise' // Allows to use request(...).promise() which returns the promise instance
67
+ ],
68
+ // Optional: Pass a callback that is called within the Promise constructor
69
+ constructorMixin: function (resolve, reject) {
70
+ // `this` is the request object
71
+ // Additional arguments may be passed depending on the PromiseImpl used
72
+ }
73
+ });
74
+
75
+
76
+ // 3. Use request with its promise capabilities
77
+
78
+ // E.g. crawl a web page:
79
+ request('http://www.google.com')
80
+ .then(function (htmlString) {
81
+ // Process html...
82
+ })
83
+ .catch(function (err) {
84
+ // Crawling failed...
85
+ });
86
+ ```
87
+
88
+ ## Installation and Usage for `request@next`
89
+
90
+ [Request Next](https://github.com/request/request/issues/1982) is still in alpha. However, `request-promise-core` is already designed to be compatible and ships with a configuration helper – `require('request-promise-core/configure/request-next')` – that is [used by `request-promise`](https://github.com/request/request-promise/blob/next/lib/rp.js) in its "next" branch.
91
+
92
+ ## Contributing
93
+
94
+ To set up your development environment:
95
+
96
+ 1. clone the repo to your desktop,
97
+ 2. in the shell `cd` to the main folder,
98
+ 3. hit `npm install`,
99
+ 4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and
100
+ 5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.)
101
+
102
+ `gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`.
103
+
104
+ If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation.
105
+
106
+ ## Change History
107
+
108
+ - 1.1.4 (2020-07-21)
109
+ - Security fix: bumped `lodash` to `^4.17.19` following [this advisory](https://www.npmjs.com/advisories/1523).
110
+ - 1.1.3 (2019-11-03)
111
+ - Security fix: bumped `lodash` to `^4.17.15`. See [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm).
112
+ *(Thanks to @daniel-nagy for pull request [#20](https://github.com/request/promise-core/pull/20) and thanks to @quetzaluz for reporting this in issue [#21](https://github.com/request/promise-core/issues/21).)*
113
+ - 1.1.2 (2019-02-14)
114
+ - Security fix: bumped `lodash` to `^4.17.11`. See [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm).
115
+ *(Thanks to @lucaswillering and @sam-warren-finnair for reporting this in issues [#12](https://github.com/request/promise-core/issues/12) and [#13](https://github.com/request/promise-core/issues/13) and thanks to @Alec321 for pull request [#14](https://github.com/request/promise-core/pull/14).)*
116
+ - 1.1.1 (2016-08-08)
117
+ - Renamed package to `request-promise-core` because there were [too](https://github.com/request/request-promise/issues/137) [many](https://github.com/request/request-promise/issues/141) issues with the scoped package name `@request/promise-core`
118
+ - 1.1.0 (2016-07-30)
119
+ - Added `constructorMixin` option to enable [request/request-promise#123](https://github.com/request/request-promise/pull/123)
120
+ - 1.0.0 (2016-07-15)
121
+ - All tests green, ready for prime time
122
+ - 1.0.0-rc.1 (2016-07-10)
123
+ - Reimplementation of core logic based on `request-promise@3.0.0`
124
+ - Plus `transform2xxOnly` option (fixes [request/request-promise#131](https://github.com/request/request-promise/issues/131))
125
+
126
+ ## License (ISC)
127
+
128
+ In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license.
129
+
130
+ See the [LICENSE file](LICENSE) for details.
@@ -0,0 +1,65 @@
1
+ var core = require('../'),
2
+ isArray = require('lodash/isArray'),
3
+ isFunction = require('lodash/isFunction'),
4
+ isObjectLike = require('lodash/isObjectLike');
5
+
6
+
7
+ module.exports = function (options) {
8
+
9
+ var errorText = 'Please verify options'; // For better minification because this string is repeating
10
+
11
+ if (!isObjectLike(options)) {
12
+ throw new TypeError(errorText);
13
+ }
14
+
15
+ if (!isFunction(options.client)) {
16
+ throw new TypeError(errorText + '.client');
17
+ }
18
+
19
+ if (!isArray(options.expose) || options.expose.length === 0) {
20
+ throw new TypeError(errorText + '.expose');
21
+ }
22
+
23
+ var thenExposed = false;
24
+ for ( var i = 0; i < options.expose.length; i+=1 ) {
25
+ if (options.expose[i] === 'then') {
26
+ thenExposed = true;
27
+ break;
28
+ }
29
+ }
30
+ if (!thenExposed) {
31
+ throw new Error('Please expose "then"');
32
+ }
33
+
34
+
35
+ var plumbing = core({
36
+ PromiseImpl: options.PromiseImpl,
37
+ constructorMixin: options.constructorMixin
38
+ });
39
+
40
+ return function (requestOptions) {
41
+
42
+ var self = {};
43
+
44
+ plumbing.init.call(self, requestOptions);
45
+
46
+ var request = options.client(requestOptions);
47
+
48
+ for ( var k = 0; k < options.expose.length; k+=1 ) {
49
+
50
+ var method = options.expose[k];
51
+
52
+ plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
53
+ request,
54
+ self,
55
+ '_rp_promise',
56
+ method
57
+ );
58
+
59
+ }
60
+
61
+ return request;
62
+
63
+ };
64
+
65
+ };
@@ -0,0 +1,72 @@
1
+ var core = require('../'),
2
+ isArray = require('lodash/isArray'),
3
+ isFunction = require('lodash/isFunction'),
4
+ isObjectLike = require('lodash/isObjectLike');
5
+
6
+
7
+ module.exports = function (options) {
8
+
9
+ var errorText = 'Please verify options'; // For better minification because this string is repeating
10
+
11
+ if (!isObjectLike(options)) {
12
+ throw new TypeError(errorText);
13
+ }
14
+
15
+ if (!isFunction(options.request)) {
16
+ throw new TypeError(errorText + '.request');
17
+ }
18
+
19
+ if (!isArray(options.expose) || options.expose.length === 0) {
20
+ throw new TypeError(errorText + '.expose');
21
+ }
22
+
23
+
24
+ var plumbing = core({
25
+ PromiseImpl: options.PromiseImpl,
26
+ constructorMixin: options.constructorMixin
27
+ });
28
+
29
+
30
+ // Intercepting Request's init method
31
+
32
+ var originalInit = options.request.Request.prototype.init;
33
+
34
+ options.request.Request.prototype.init = function RP$initInterceptor(requestOptions) {
35
+
36
+ // Init may be called again - currently in case of redirects
37
+ if (isObjectLike(requestOptions) && !this._callback && !this._rp_promise) {
38
+
39
+ plumbing.init.call(this, requestOptions);
40
+
41
+ }
42
+
43
+ return originalInit.apply(this, arguments);
44
+
45
+ };
46
+
47
+
48
+ // Exposing the Promise capabilities
49
+
50
+ var thenExposed = false;
51
+ for ( var i = 0; i < options.expose.length; i+=1 ) {
52
+
53
+ var method = options.expose[i];
54
+
55
+ plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
56
+ options.request.Request.prototype,
57
+ null,
58
+ '_rp_promise',
59
+ method
60
+ );
61
+
62
+ if (method === 'then') {
63
+ thenExposed = true;
64
+ }
65
+
66
+ }
67
+
68
+ if (!thenExposed) {
69
+ throw new Error('Please expose "then"');
70
+ }
71
+
72
+ };
@@ -0,0 +1 @@
1
+ module.exports = require('./lib/errors.js');
@@ -0,0 +1,59 @@
1
+ function RequestError(cause, options, response) {
2
+
3
+ this.name = 'RequestError';
4
+ this.message = String(cause);
5
+ this.cause = cause;
6
+ this.error = cause; // legacy attribute
7
+ this.options = options;
8
+ this.response = response;
9
+
10
+ if (Error.captureStackTrace) { // required for non-V8 environments
11
+ Error.captureStackTrace(this);
12
+ }
13
+
14
+ }
15
+ RequestError.prototype = Object.create(Error.prototype);
16
+ RequestError.prototype.constructor = RequestError;
17
+
18
+
19
+ function StatusCodeError(statusCode, body, options, response) {
20
+
21
+ this.name = 'StatusCodeError';
22
+ this.statusCode = statusCode;
23
+ this.message = statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body);
24
+ this.error = body; // legacy attribute
25
+ this.options = options;
26
+ this.response = response;
27
+
28
+ if (Error.captureStackTrace) { // required for non-V8 environments
29
+ Error.captureStackTrace(this);
30
+ }
31
+
32
+ }
33
+ StatusCodeError.prototype = Object.create(Error.prototype);
34
+ StatusCodeError.prototype.constructor = StatusCodeError;
35
+
36
+
37
+ function TransformError(cause, options, response) {
38
+
39
+ this.name = 'TransformError';
40
+ this.message = String(cause);
41
+ this.cause = cause;
42
+ this.error = cause; // legacy attribute
43
+ this.options = options;
44
+ this.response = response;
45
+
46
+ if (Error.captureStackTrace) { // required for non-V8 environments
47
+ Error.captureStackTrace(this);
48
+ }
49
+
50
+ }
51
+ TransformError.prototype = Object.create(Error.prototype);
52
+ TransformError.prototype.constructor = TransformError;
53
+
54
+
55
+ module.exports = {
56
+ RequestError: RequestError,
57
+ StatusCodeError: StatusCodeError,
58
+ TransformError: TransformError
59
+ };
@@ -0,0 +1,165 @@
1
+ var errors = require('./errors.js'),
2
+ isFunction = require('lodash/isFunction'),
3
+ isObjectLike = require('lodash/isObjectLike'),
4
+ isString = require('lodash/isString'),
5
+ isUndefined = require('lodash/isUndefined');
6
+
7
+
8
+ module.exports = function (options) {
9
+
10
+ var errorText = 'Please verify options'; // For better minification because this string is repeating
11
+
12
+ if (!isObjectLike(options)) {
13
+ throw new TypeError(errorText);
14
+ }
15
+
16
+ if (!isFunction(options.PromiseImpl)) {
17
+ throw new TypeError(errorText + '.PromiseImpl');
18
+ }
19
+
20
+ if (!isUndefined(options.constructorMixin) && !isFunction(options.constructorMixin)) {
21
+ throw new TypeError(errorText + '.PromiseImpl');
22
+ }
23
+
24
+ var PromiseImpl = options.PromiseImpl;
25
+ var constructorMixin = options.constructorMixin;
26
+
27
+
28
+ var plumbing = {};
29
+
30
+ plumbing.init = function (requestOptions) {
31
+
32
+ var self = this;
33
+
34
+ self._rp_promise = new PromiseImpl(function (resolve, reject) {
35
+ self._rp_resolve = resolve;
36
+ self._rp_reject = reject;
37
+ if (constructorMixin) {
38
+ constructorMixin.apply(self, arguments); // Using arguments since specific Promise libraries may pass additional parameters
39
+ }
40
+ });
41
+
42
+ self._rp_callbackOrig = requestOptions.callback;
43
+ requestOptions.callback = self.callback = function RP$callback(err, response, body) {
44
+ plumbing.callback.call(self, err, response, body);
45
+ };
46
+
47
+ if (isString(requestOptions.method)) {
48
+ requestOptions.method = requestOptions.method.toUpperCase();
49
+ }
50
+
51
+ requestOptions.transform = requestOptions.transform || plumbing.defaultTransformations[requestOptions.method];
52
+
53
+ self._rp_options = requestOptions;
54
+ self._rp_options.simple = requestOptions.simple !== false;
55
+ self._rp_options.resolveWithFullResponse = requestOptions.resolveWithFullResponse === true;
56
+ self._rp_options.transform2xxOnly = requestOptions.transform2xxOnly === true;
57
+
58
+ };
59
+
60
+ plumbing.defaultTransformations = {
61
+ HEAD: function (body, response, resolveWithFullResponse) {
62
+ return resolveWithFullResponse ? response : response.headers;
63
+ }
64
+ };
65
+
66
+ plumbing.callback = function (err, response, body) {
67
+
68
+ var self = this;
69
+
70
+ var origCallbackThrewException = false, thrownException = null;
71
+
72
+ if (isFunction(self._rp_callbackOrig)) {
73
+ try {
74
+ self._rp_callbackOrig.apply(self, arguments); // TODO: Apply to self mimics behavior of request@2. Is that also right for request@next?
75
+ } catch (e) {
76
+ origCallbackThrewException = true;
77
+ thrownException = e;
78
+ }
79
+ }
80
+
81
+ var is2xx = !err && /^2/.test('' + response.statusCode);
82
+
83
+ if (err) {
84
+
85
+ self._rp_reject(new errors.RequestError(err, self._rp_options, response));
86
+
87
+ } else if (self._rp_options.simple && !is2xx) {
88
+
89
+ if (isFunction(self._rp_options.transform) && self._rp_options.transform2xxOnly === false) {
90
+
91
+ new PromiseImpl(function (resolve) {
92
+ resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
93
+ })
94
+ .then(function (transformedResponse) {
95
+ self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, transformedResponse));
96
+ })
97
+ .catch(function (transformErr) {
98
+ self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
99
+ });
100
+
101
+ } else {
102
+ self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, response));
103
+ }
104
+
105
+ } else {
106
+
107
+ if (isFunction(self._rp_options.transform) && (is2xx || self._rp_options.transform2xxOnly === false)) {
108
+
109
+ new PromiseImpl(function (resolve) {
110
+ resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
111
+ })
112
+ .then(function (transformedResponse) {
113
+ self._rp_resolve(transformedResponse);
114
+ })
115
+ .catch(function (transformErr) {
116
+ self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
117
+ });
118
+
119
+ } else if (self._rp_options.resolveWithFullResponse) {
120
+ self._rp_resolve(response);
121
+ } else {
122
+ self._rp_resolve(body);
123
+ }
124
+
125
+ }
126
+
127
+ if (origCallbackThrewException) {
128
+ throw thrownException;
129
+ }
130
+
131
+ };
132
+
133
+ plumbing.exposePromiseMethod = function (exposeTo, bindTo, promisePropertyKey, methodToExpose, exposeAs) {
134
+
135
+ exposeAs = exposeAs || methodToExpose;
136
+
137
+ if (exposeAs in exposeTo) {
138
+ throw new Error('Unable to expose method "' + exposeAs + '"');
139
+ }
140
+
141
+ exposeTo[exposeAs] = function RP$exposed() {
142
+ var self = bindTo || this;
143
+ return self[promisePropertyKey][methodToExpose].apply(self[promisePropertyKey], arguments);
144
+ };
145
+
146
+ };
147
+
148
+ plumbing.exposePromise = function (exposeTo, bindTo, promisePropertyKey, exposeAs) {
149
+
150
+ exposeAs = exposeAs || 'promise';
151
+
152
+ if (exposeAs in exposeTo) {
153
+ throw new Error('Unable to expose method "' + exposeAs + '"');
154
+ }
155
+
156
+ exposeTo[exposeAs] = function RP$promise() {
157
+ var self = bindTo || this;
158
+ return self[promisePropertyKey];
159
+ };
160
+
161
+ };
162
+
163
+ return plumbing;
164
+
165
+ };