superagent 3.7.0 → 3.8.2

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.
package/superagent.js CHANGED
@@ -1,4 +1,26 @@
1
1
  (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.superagent = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2
+ function Agent() {
3
+ this._defaults = [];
4
+ }
5
+
6
+ ["use", "on", "once", "set", "query", "type", "accept", "auth", "withCredentials", "sortQuery", "retry", "ok", "redirects",
7
+ "timeout", "buffer", "serialize", "parse", "ca", "key", "pfx", "cert"].forEach(function(fn) {
8
+ /** Default setting for all requests from this agent */
9
+ Agent.prototype[fn] = function(/*varargs*/) {
10
+ this._defaults.push({fn:fn, arguments:arguments});
11
+ return this;
12
+ }
13
+ });
14
+
15
+ Agent.prototype._setDefaults = function(req) {
16
+ this._defaults.forEach(function(def) {
17
+ req[def.fn].apply(req, def.arguments);
18
+ });
19
+ };
20
+
21
+ module.exports = Agent;
22
+
23
+ },{}],2:[function(require,module,exports){
2
24
  'use strict';
3
25
 
4
26
  /**
@@ -15,7 +37,7 @@ function isObject(obj) {
15
37
 
16
38
  module.exports = isObject;
17
39
 
18
- },{}],2:[function(require,module,exports){
40
+ },{}],3:[function(require,module,exports){
19
41
  'use strict';
20
42
 
21
43
  /**
@@ -161,19 +183,60 @@ RequestBase.prototype.timeout = function timeout(options){
161
183
  * Failed requests will be retried 'count' times if timeout or err.code >= 500.
162
184
  *
163
185
  * @param {Number} count
186
+ * @param {Function} [fn]
164
187
  * @return {Request} for chaining
165
188
  * @api public
166
189
  */
167
190
 
168
- RequestBase.prototype.retry = function retry(count){
191
+ RequestBase.prototype.retry = function retry(count, fn){
169
192
  // Default to 1 if no count passed or true
170
193
  if (arguments.length === 0 || count === true) count = 1;
171
194
  if (count <= 0) count = 0;
172
195
  this._maxRetries = count;
173
196
  this._retries = 0;
197
+ this._retryCallback = fn;
174
198
  return this;
175
199
  };
176
200
 
201
+ var ERROR_CODES = [
202
+ 'ECONNRESET',
203
+ 'ETIMEDOUT',
204
+ 'EADDRINFO',
205
+ 'ESOCKETTIMEDOUT'
206
+ ];
207
+
208
+ /**
209
+ * Determine if a request should be retried.
210
+ * (Borrowed from segmentio/superagent-retry)
211
+ *
212
+ * @param {Error} err
213
+ * @param {Response} [res]
214
+ * @returns {Boolean}
215
+ */
216
+ RequestBase.prototype._shouldRetry = function(err, res) {
217
+ if (!this._maxRetries || this._retries++ >= this._maxRetries) {
218
+ return false;
219
+ }
220
+ if (this._retryCallback) {
221
+ try {
222
+ var override = this._retryCallback(err, res);
223
+ if (override === true) return true;
224
+ if (override === false) return false;
225
+ // undefined falls back to defaults
226
+ } catch(e) {
227
+ console.error(e);
228
+ }
229
+ }
230
+ if (res && res.status && res.status >= 500 && res.status != 501) return true;
231
+ if (err) {
232
+ if (err.code && ~ERROR_CODES.indexOf(err.code)) return true;
233
+ // Superagent timeout
234
+ if (err.timeout && err.code == 'ECONNABORTED') return true;
235
+ if (err.crossDomain) return true;
236
+ }
237
+ return false;
238
+ };
239
+
177
240
  /**
178
241
  * Retry request
179
242
  *
@@ -182,6 +245,7 @@ RequestBase.prototype.retry = function retry(count){
182
245
  */
183
246
 
184
247
  RequestBase.prototype._retry = function() {
248
+
185
249
  this.clearTimeout();
186
250
 
187
251
  // node
@@ -210,14 +274,15 @@ RequestBase.prototype.then = function then(resolve, reject) {
210
274
  if (this._endCalled) {
211
275
  console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises");
212
276
  }
213
- this._fullfilledPromise = new Promise(function(innerResolve, innerReject){
214
- self.end(function(err, res){
215
- if (err) innerReject(err); else innerResolve(res);
277
+ this._fullfilledPromise = new Promise(function(innerResolve, innerReject) {
278
+ self.end(function(err, res) {
279
+ if (err) innerReject(err);
280
+ else innerResolve(res);
216
281
  });
217
282
  });
218
283
  }
219
284
  return this._fullfilledPromise.then(resolve, reject);
220
- }
285
+ };
221
286
 
222
287
  RequestBase.prototype.catch = function(cb) {
223
288
  return this.then(undefined, cb);
@@ -230,7 +295,7 @@ RequestBase.prototype.catch = function(cb) {
230
295
  RequestBase.prototype.use = function use(fn) {
231
296
  fn(this);
232
297
  return this;
233
- }
298
+ };
234
299
 
235
300
  RequestBase.prototype.ok = function(cb) {
236
301
  if ('function' !== typeof cb) throw Error("Callback required");
@@ -250,7 +315,6 @@ RequestBase.prototype._isResponseOK = function(res) {
250
315
  return res.status >= 200 && res.status < 300;
251
316
  };
252
317
 
253
-
254
318
  /**
255
319
  * Get request header `field`.
256
320
  * Case-insensitive.
@@ -349,9 +413,8 @@ RequestBase.prototype.unset = function(field){
349
413
  * @api public
350
414
  */
351
415
  RequestBase.prototype.field = function(name, val) {
352
-
353
416
  // name should be either a string or an object.
354
- if (null === name || undefined === name) {
417
+ if (null === name || undefined === name) {
355
418
  throw new Error('.field(name, val) name can not be empty');
356
419
  }
357
420
 
@@ -402,6 +465,24 @@ RequestBase.prototype.abort = function(){
402
465
  return this;
403
466
  };
404
467
 
468
+ RequestBase.prototype._auth = function(user, pass, options, base64Encoder) {
469
+ switch (options.type) {
470
+ case 'basic':
471
+ this.set('Authorization', 'Basic ' + base64Encoder(user + ':' + pass));
472
+ break;
473
+
474
+ case 'auto':
475
+ this.username = user;
476
+ this.password = pass;
477
+ break;
478
+
479
+ case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
480
+ this.set('Authorization', 'Bearer ' + user);
481
+ break;
482
+ }
483
+ return this;
484
+ };
485
+
405
486
  /**
406
487
  * Enable transmission of cookies with x-domain requests.
407
488
  *
@@ -413,9 +494,9 @@ RequestBase.prototype.abort = function(){
413
494
  * @api public
414
495
  */
415
496
 
416
- RequestBase.prototype.withCredentials = function(on){
497
+ RequestBase.prototype.withCredentials = function(on) {
417
498
  // This is browser-only functionality. Node side is no-op.
418
- if(on==undefined) on = true;
499
+ if (on == undefined) on = true;
419
500
  this._withCredentials = on;
420
501
  return this;
421
502
  };
@@ -457,16 +538,15 @@ RequestBase.prototype.maxResponseSize = function(n){
457
538
  * @api public
458
539
  */
459
540
 
460
- RequestBase.prototype.toJSON = function(){
541
+ RequestBase.prototype.toJSON = function() {
461
542
  return {
462
543
  method: this.method,
463
544
  url: this.url,
464
545
  data: this._data,
465
- headers: this._header
546
+ headers: this._header,
466
547
  };
467
548
  };
468
549
 
469
-
470
550
  /**
471
551
  * Send `data` as the request body, defaulting the `.type()` to "json" when
472
552
  * an object is given.
@@ -554,7 +634,6 @@ RequestBase.prototype.send = function(data){
554
634
  return this;
555
635
  };
556
636
 
557
-
558
637
  /**
559
638
  * Sort `querystring` by the sort function
560
639
  *
@@ -652,9 +731,9 @@ RequestBase.prototype._setTimeouts = function() {
652
731
  self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
653
732
  }, this._responseTimeout);
654
733
  }
655
- }
734
+ };
656
735
 
657
- },{"./is-object":1}],3:[function(require,module,exports){
736
+ },{"./is-object":2}],4:[function(require,module,exports){
658
737
  'use strict';
659
738
 
660
739
  /**
@@ -702,8 +781,8 @@ function mixin(obj) {
702
781
  * @api public
703
782
  */
704
783
 
705
- ResponseBase.prototype.get = function(field){
706
- return this.header[field.toLowerCase()];
784
+ ResponseBase.prototype.get = function(field) {
785
+ return this.header[field.toLowerCase()];
707
786
  };
708
787
 
709
788
  /**
@@ -790,34 +869,7 @@ ResponseBase.prototype._setStatusProperties = function(status){
790
869
  this.notFound = 404 == status;
791
870
  };
792
871
 
793
- },{"./utils":5}],4:[function(require,module,exports){
794
- 'use strict';
795
-
796
- var ERROR_CODES = [
797
- 'ECONNRESET',
798
- 'ETIMEDOUT',
799
- 'EADDRINFO',
800
- 'ESOCKETTIMEDOUT'
801
- ];
802
-
803
- /**
804
- * Determine if a request should be retried.
805
- * (Borrowed from segmentio/superagent-retry)
806
- *
807
- * @param {Error} err
808
- * @param {Response} [res]
809
- * @returns {Boolean}
810
- */
811
- module.exports = function shouldRetry(err, res) {
812
- if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true;
813
- if (res && res.status && res.status >= 500) return true;
814
- // Superagent timeout
815
- if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true;
816
- if (err && 'crossDomain' in err) return true;
817
- return false;
818
- };
819
-
820
- },{}],5:[function(require,module,exports){
872
+ },{"./utils":5}],5:[function(require,module,exports){
821
873
  'use strict';
822
874
 
823
875
  /**
@@ -877,12 +929,14 @@ exports.parseLinks = function(str){
877
929
  * @api private
878
930
  */
879
931
 
880
- exports.cleanHeader = function(header, shouldStripCookie){
932
+ exports.cleanHeader = function(header, changesOrigin){
881
933
  delete header['content-type'];
882
934
  delete header['content-length'];
883
935
  delete header['transfer-encoding'];
884
936
  delete header['host'];
885
- if (shouldStripCookie) {
937
+ // secuirty
938
+ if (changesOrigin) {
939
+ delete header['authorization'];
886
940
  delete header['cookie'];
887
941
  }
888
942
  return header;
@@ -1072,7 +1126,7 @@ var Emitter = require('component-emitter');
1072
1126
  var RequestBase = require('./request-base');
1073
1127
  var isObject = require('./is-object');
1074
1128
  var ResponseBase = require('./response-base');
1075
- var shouldRetry = require('./should-retry');
1129
+ var Agent = require('./agent-base');
1076
1130
 
1077
1131
  /**
1078
1132
  * Noop.
@@ -1179,9 +1233,9 @@ function pushEncodedKeyValuePair(pairs, key, val) {
1179
1233
  * Expose serialization method.
1180
1234
  */
1181
1235
 
1182
- request.serializeObject = serialize;
1236
+ request.serializeObject = serialize;
1183
1237
 
1184
- /**
1238
+ /**
1185
1239
  * Parse the given x-www-form-urlencoded `str`.
1186
1240
  *
1187
1241
  * @param {String} str
@@ -1240,12 +1294,12 @@ request.types = {
1240
1294
  *
1241
1295
  */
1242
1296
 
1243
- request.serialize = {
1244
- 'application/x-www-form-urlencoded': serialize,
1245
- 'application/json': JSON.stringify
1246
- };
1297
+ request.serialize = {
1298
+ 'application/x-www-form-urlencoded': serialize,
1299
+ 'application/json': JSON.stringify,
1300
+ };
1247
1301
 
1248
- /**
1302
+ /**
1249
1303
  * Default parsers.
1250
1304
  *
1251
1305
  * superagent.parse['application/xml'] = function(str){
@@ -1256,7 +1310,7 @@ request.types = {
1256
1310
 
1257
1311
  request.parse = {
1258
1312
  'application/x-www-form-urlencoded': parseString,
1259
- 'application/json': JSON.parse
1313
+ 'application/json': JSON.parse,
1260
1314
  };
1261
1315
 
1262
1316
  /**
@@ -1299,7 +1353,9 @@ function parseHeader(str) {
1299
1353
  */
1300
1354
 
1301
1355
  function isJSON(mime) {
1302
- return /[\/+]json\b/.test(mime);
1356
+ // should match /json or +json
1357
+ // but not /json-seq
1358
+ return /[\/+]json($|[^-\w])/.test(mime);
1303
1359
  }
1304
1360
 
1305
1361
  /**
@@ -1359,7 +1415,7 @@ function Response(req) {
1359
1415
  var status = this.xhr.status;
1360
1416
  // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
1361
1417
  if (status === 1223) {
1362
- status = 204;
1418
+ status = 204;
1363
1419
  }
1364
1420
  this._setStatusProperties(status);
1365
1421
  this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
@@ -1391,9 +1447,9 @@ ResponseBase(Response.prototype);
1391
1447
  * @api private
1392
1448
  */
1393
1449
 
1394
- Response.prototype._parseBody = function(str){
1450
+ Response.prototype._parseBody = function(str) {
1395
1451
  var parse = request.parse[this.type];
1396
- if(this.req._parser) {
1452
+ if (this.req._parser) {
1397
1453
  return this.req._parser(this, str);
1398
1454
  }
1399
1455
  if (!parse && isJSON(this.type)) {
@@ -1564,30 +1620,25 @@ Request.prototype.accept = function(type){
1564
1620
  */
1565
1621
 
1566
1622
  Request.prototype.auth = function(user, pass, options){
1567
- if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options
1623
+ if (1 === arguments.length) pass = '';
1624
+ if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options
1568
1625
  options = pass;
1626
+ pass = '';
1569
1627
  }
1570
1628
  if (!options) {
1571
1629
  options = {
1572
1630
  type: 'function' === typeof btoa ? 'basic' : 'auto',
1573
- }
1631
+ };
1574
1632
  }
1575
1633
 
1576
- switch (options.type) {
1577
- case 'basic':
1578
- this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));
1579
- break;
1580
-
1581
- case 'auto':
1582
- this.username = user;
1583
- this.password = pass;
1584
- break;
1634
+ var encoder = function(string) {
1635
+ if ('function' === typeof btoa) {
1636
+ return btoa(string);
1637
+ }
1638
+ throw new Error('Cannot use basic auth, btoa is not a function');
1639
+ };
1585
1640
 
1586
- case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
1587
- this.set('Authorization', 'Bearer ' + user);
1588
- break;
1589
- }
1590
- return this;
1641
+ return this._auth(user, pass, options, encoder);
1591
1642
  };
1592
1643
 
1593
1644
  /**
@@ -1655,8 +1706,7 @@ Request.prototype._getFormData = function(){
1655
1706
  */
1656
1707
 
1657
1708
  Request.prototype.callback = function(err, res){
1658
- // console.log(this._retries, this._maxRetries)
1659
- if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) {
1709
+ if (this._shouldRetry(err, res)) {
1660
1710
  return this._retry();
1661
1711
  }
1662
1712
 
@@ -1738,7 +1788,7 @@ Request.prototype.end = function(fn){
1738
1788
 
1739
1789
  Request.prototype._end = function() {
1740
1790
  var self = this;
1741
- var xhr = this.xhr = request.getXHR();
1791
+ var xhr = (this.xhr = request.getXHR());
1742
1792
  var data = this._formData || this._data;
1743
1793
 
1744
1794
  this._setTimeouts();
@@ -1772,7 +1822,7 @@ Request.prototype._end = function() {
1772
1822
  }
1773
1823
  e.direction = direction;
1774
1824
  self.emit('progress', e);
1775
- }
1825
+ };
1776
1826
  if (this.hasListeners('progress')) {
1777
1827
  try {
1778
1828
  xhr.onprogress = handleProgress.bind(null, 'download');
@@ -1833,6 +1883,23 @@ Request.prototype._end = function() {
1833
1883
  return this;
1834
1884
  };
1835
1885
 
1886
+ request.agent = function() {
1887
+ return new Agent();
1888
+ };
1889
+
1890
+ ["GET", "POST", "OPTIONS", "PATCH", "PUT", "DELETE"].forEach(function(method) {
1891
+ Agent.prototype[method.toLowerCase()] = function(url, fn) {
1892
+ var req = new request.Request(method, url);
1893
+ this._setDefaults(req);
1894
+ if (fn) {
1895
+ req.end(fn);
1896
+ }
1897
+ return req;
1898
+ };
1899
+ });
1900
+
1901
+ Agent.prototype.del = Agent.prototype['delete'];
1902
+
1836
1903
  /**
1837
1904
  * GET `url` with optional callback `fn(res)`.
1838
1905
  *
@@ -1843,9 +1910,9 @@ Request.prototype._end = function() {
1843
1910
  * @api public
1844
1911
  */
1845
1912
 
1846
- request.get = function(url, data, fn){
1913
+ request.get = function(url, data, fn) {
1847
1914
  var req = request('GET', url);
1848
- if ('function' == typeof data) fn = data, data = null;
1915
+ if ('function' == typeof data) (fn = data), (data = null);
1849
1916
  if (data) req.query(data);
1850
1917
  if (fn) req.end(fn);
1851
1918
  return req;
@@ -1861,9 +1928,9 @@ request.get = function(url, data, fn){
1861
1928
  * @api public
1862
1929
  */
1863
1930
 
1864
- request.head = function(url, data, fn){
1931
+ request.head = function(url, data, fn) {
1865
1932
  var req = request('HEAD', url);
1866
- if ('function' == typeof data) fn = data, data = null;
1933
+ if ('function' == typeof data) (fn = data), (data = null);
1867
1934
  if (data) req.query(data);
1868
1935
  if (fn) req.end(fn);
1869
1936
  return req;
@@ -1879,9 +1946,9 @@ request.head = function(url, data, fn){
1879
1946
  * @api public
1880
1947
  */
1881
1948
 
1882
- request.options = function(url, data, fn){
1949
+ request.options = function(url, data, fn) {
1883
1950
  var req = request('OPTIONS', url);
1884
- if ('function' == typeof data) fn = data, data = null;
1951
+ if ('function' == typeof data) (fn = data), (data = null);
1885
1952
  if (data) req.send(data);
1886
1953
  if (fn) req.end(fn);
1887
1954
  return req;
@@ -1897,13 +1964,13 @@ request.options = function(url, data, fn){
1897
1964
  * @api public
1898
1965
  */
1899
1966
 
1900
- function del(url, data, fn){
1967
+ function del(url, data, fn) {
1901
1968
  var req = request('DELETE', url);
1902
- if ('function' == typeof data) fn = data, data = null;
1969
+ if ('function' == typeof data) (fn = data), (data = null);
1903
1970
  if (data) req.send(data);
1904
1971
  if (fn) req.end(fn);
1905
1972
  return req;
1906
- };
1973
+ }
1907
1974
 
1908
1975
  request['del'] = del;
1909
1976
  request['delete'] = del;
@@ -1918,9 +1985,9 @@ request['delete'] = del;
1918
1985
  * @api public
1919
1986
  */
1920
1987
 
1921
- request.patch = function(url, data, fn){
1988
+ request.patch = function(url, data, fn) {
1922
1989
  var req = request('PATCH', url);
1923
- if ('function' == typeof data) fn = data, data = null;
1990
+ if ('function' == typeof data) (fn = data), (data = null);
1924
1991
  if (data) req.send(data);
1925
1992
  if (fn) req.end(fn);
1926
1993
  return req;
@@ -1936,9 +2003,9 @@ request.patch = function(url, data, fn){
1936
2003
  * @api public
1937
2004
  */
1938
2005
 
1939
- request.post = function(url, data, fn){
2006
+ request.post = function(url, data, fn) {
1940
2007
  var req = request('POST', url);
1941
- if ('function' == typeof data) fn = data, data = null;
2008
+ if ('function' == typeof data) (fn = data), (data = null);
1942
2009
  if (data) req.send(data);
1943
2010
  if (fn) req.end(fn);
1944
2011
  return req;
@@ -1954,13 +2021,13 @@ request.post = function(url, data, fn){
1954
2021
  * @api public
1955
2022
  */
1956
2023
 
1957
- request.put = function(url, data, fn){
2024
+ request.put = function(url, data, fn) {
1958
2025
  var req = request('PUT', url);
1959
- if ('function' == typeof data) fn = data, data = null;
2026
+ if ('function' == typeof data) (fn = data), (data = null);
1960
2027
  if (data) req.send(data);
1961
2028
  if (fn) req.end(fn);
1962
2029
  return req;
1963
2030
  };
1964
2031
 
1965
- },{"./is-object":1,"./request-base":2,"./response-base":3,"./should-retry":4,"component-emitter":6}]},{},[7])(7)
2032
+ },{"./agent-base":1,"./is-object":2,"./request-base":3,"./response-base":4,"component-emitter":6}]},{},[7])(7)
1966
2033
  });