-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundle.js
23313 lines (21435 loc) · 512 KB
/
bundle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 30);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("util");
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = require("stream");
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = require("fs");
/***/ }),
/* 3 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return objectToString(e) === '[object Error]' || e instanceof Error;
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
try {
var util = __webpack_require__(0);
if (typeof util.inherits !== 'function') throw '';
module.exports = util.inherits;
} catch (e) {
module.exports = __webpack_require__(53);
}
/***/ }),
/* 5 */
/***/ (function(module, exports) {
module.exports = require("buffer");
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = require("url");
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Module dependencies.
*/
var debug = __webpack_require__(34)('superagent');
var formidable = __webpack_require__(48);
var FormData = __webpack_require__(16);
var Response = __webpack_require__(73);
var parse = __webpack_require__(6).parse;
var format = __webpack_require__(6).format;
var resolve = __webpack_require__(6).resolve;
var methods = __webpack_require__(17);
var Stream = __webpack_require__(1);
var utils = __webpack_require__(24);
var extend = __webpack_require__(45);
var Part = __webpack_require__(72);
var mime = __webpack_require__(18);
var https = __webpack_require__(26);
var http = __webpack_require__(12);
var fs = __webpack_require__(2);
var qs = __webpack_require__(19);
var zlib = __webpack_require__(28);
var util = __webpack_require__(0);
var pkg = __webpack_require__(78);
var requestBase = __webpack_require__(74);
var isObject = __webpack_require__(23);
/**
* Expose the request function.
*/
var request = exports = module.exports = __webpack_require__(75).bind(null, Request);
/**
* Expose the agent function
*/
exports.agent = __webpack_require__(66);
/**
* Expose `Part`.
*/
exports.Part = Part;
/**
* Noop.
*/
function noop() {};
/**
* Expose `Response`.
*/
exports.Response = Response;
/**
* Define "form" mime type.
*/
mime.define({
'application/x-www-form-urlencoded': ['form', 'urlencoded', 'form-data']
});
/**
* Protocol map.
*/
exports.protocols = {
'http:': http,
'https:': https
};
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
exports.serialize = {
'application/x-www-form-urlencoded': qs.stringify,
'application/json': JSON.stringify
};
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(res, fn){
* fn(null, res);
* };
*
*/
exports.parse = __webpack_require__(68);
/**
* Initialize internal header tracking properties on a request instance.
*
* @param {Object} req the instance
* @api private
*/
function _initHeaders(req) {
var ua = 'node-superagent/' + pkg.version;
req._header = { // coerces header names to lowercase
'user-agent': ua
};
req.header = { // preserves header name case
'User-Agent': ua
};
}
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String|Object} url
* @api public
*/
function Request(method, url) {
Stream.call(this);
var self = this;
if ('string' != typeof url) url = format(url);
this._agent = false;
this._formData = null;
this.method = method;
this.url = url;
_initHeaders(this);
this.writable = true;
this._redirects = 0;
this.redirects(5);
this.cookies = '';
this.qs = {};
this.qsRaw = [];
this._redirectList = [];
this._streamRequest = false;
this.on('end', this.clearTimeout.bind(this));
}
/**
* Inherit from `Stream` (which inherits from `EventEmitter`).
* Mixin `requestBase`.
*/
util.inherits(Request, Stream);
for (var key in requestBase) {
Request.prototype[key] = requestBase[key];
}
/**
* Queue the given `file` as an attachment to the specified `field`,
* with optional `filename`.
*
* ``` js
* request.post('http://localhost/upload')
* .attach(new Buffer('<b>Hello world</b>'), 'hello.html')
* .end(callback);
* ```
*
* A filename may also be used:
*
* ``` js
* request.post('http://localhost/upload')
* .attach('files', 'image.jpg')
* .end(callback);
* ```
*
* @param {String} field
* @param {String|fs.ReadStream|Buffer} file
* @param {String} filename
* @return {Request} for chaining
* @api public
*/
Request.prototype.attach = function (field, file, filename) {
if ('string' == typeof file) {
if (!filename) filename = file;
debug('creating `fs.ReadStream` instance for file: %s', file);
file = fs.createReadStream(file);
} else if (!filename && file.path) {
filename = file.path;
}
this._getFormData().append(field, file, { filename: filename });
return this;
};
Request.prototype._getFormData = function () {
if (!this._formData) {
this._formData = new FormData();
this._formData.on('error', function (err) {
this.emit('error', err);
this.abort();
}.bind(this));
}
return this._formData;
};
/**
* Set the max redirects to `n`.
*
* @param {Number} n
* @return {Request} for chaining
* @api public
*/
Request.prototype.redirects = function (n) {
debug('max redirects %s', n);
this._maxRedirects = n;
return this;
};
/**
* Return a new `Part` for this request.
*
* @return {Part}
* @api public
* @deprecated pass a readable stream in to `Request#attach()` instead
*/
Request.prototype.part = util.deprecate(function () {
return new Part(this);
}, '`Request#part()` is deprecated. ' + 'Pass a readable stream in to `Request#attach()` instead.');
/**
* Gets/sets the `Agent` to use for this HTTP request. The default (if this
* function is not called) is to opt out of connection pooling (`agent: false`).
*
* @param {http.Agent} agent
* @return {http.Agent}
* @api public
*/
Request.prototype.agent = function (agent) {
if (!arguments.length) return this._agent;
this._agent = agent;
return this;
};
/**
* Set _Content-Type_ response header passed through `mime.lookup()`.
*
* Examples:
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('json')
* .send(jsonstring)
* .end(callback);
*
* request.post('/')
* .type('application/json')
* .send(jsonstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
Request.prototype.type = function (type) {
return this.set('Content-Type', ~type.indexOf('/') ? type : mime.lookup(type));
};
/**
* Set _Accept_ response header passed through `mime.lookup()`.
*
* Examples:
*
* superagent.types.json = 'application/json';
*
* request.get('/agent')
* .accept('json')
* .end(callback);
*
* request.get('/agent')
* .accept('application/json')
* .end(callback);
*
* @param {String} accept
* @return {Request} for chaining
* @api public
*/
Request.prototype.accept = function (type) {
return this.set('Accept', ~type.indexOf('/') ? type : mime.lookup(type));
};
/**
* Add query-string `val`.
*
* Examples:
*
* request.get('/shoes')
* .query('size=10')
* .query({ color: 'blue' })
*
* @param {Object|String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.query = function (val) {
if ('string' == typeof val) {
this.qsRaw.push(val);
return this;
}
extend(this.qs, val);
return this;
};
/**
* Send `data` as the request body, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
* // manual json
* request.post('/user')
* .type('json')
* .send('{"name":"tj"}')
* .end(callback)
*
* // auto json
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
* // manual x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
* // auto x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
* // string defaults to x-www-form-urlencoded
* request.post('/user')
* .send('name=tj')
* .send('foo=bar')
* .send('bar=baz')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
Request.prototype.send = function (data) {
var obj = isObject(data);
var type = this._header['content-type'];
// merge
if (obj && isObject(this._data)) {
for (var key in data) {
this._data[key] = data[key];
}
// string
} else if ('string' == typeof data) {
// default to x-www-form-urlencoded
if (!type) this.type('form');
type = this._header['content-type'];
// concat &
if ('application/x-www-form-urlencoded' == type) {
this._data = this._data ? this._data + '&' + data : data;
} else {
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!obj) return this;
// default to json
if (!type) this.type('json');
return this;
};
/**
* Write raw `data` / `encoding` to the socket.
*
* @param {Buffer|String} data
* @param {String} encoding
* @return {Boolean}
* @api public
*/
Request.prototype.write = function (data, encoding) {
var req = this.request();
if (!this._streamRequest) {
this._streamRequest = true;
try {
// ensure querystring is appended before headers are sent
this.appendQueryString(req);
} catch (e) {
return this.emit('error', e);
}
}
return req.write(data, encoding);
};
/**
* Pipe the request body to `stream`.
*
* @param {Stream} stream
* @param {Object} options
* @return {Stream}
* @api public
*/
Request.prototype.pipe = function (stream, options) {
this.piped = true; // HACK...
this.buffer(false);
var self = this;
this.end().req.on('response', function (res) {
// redirect
var redirect = isRedirect(res.statusCode);
if (redirect && self._redirects++ != self._maxRedirects) {
return self.redirect(res).pipe(stream, options);
}
if (self._shouldUnzip(res)) {
res.pipe(zlib.createUnzip()).pipe(stream, options);
} else {
res.pipe(stream, options);
}
res.on('end', function () {
self.emit('end');
});
});
return stream;
};
/**
* Enable / disable buffering.
*
* @return {Boolean} [val]
* @return {Request} for chaining
* @api public
*/
Request.prototype.buffer = function (val) {
this._buffer = false === val ? false : true;
return this;
};
/**
* Abort and clear timeout.
*
* @api public
*/
Request.prototype.abort = function () {
debug('abort %s %s', this.method, this.url);
this._aborted = true;
this.clearTimeout();
this.req.abort();
this.emit('abort');
};
/**
* Redirect to `url
*
* @param {IncomingMessage} res
* @return {Request} for chaining
* @api private
*/
Request.prototype.redirect = function (res) {
var url = res.headers.location;
if (!url) {
return this.callback(new Error('No location header for redirect'), res);
}
debug('redirect %s -> %s', this.url, url);
// location
url = resolve(this.url, url);
// ensure the response is being consumed
// this is required for Node v0.10+
res.resume();
var headers = this.req._headers;
var shouldStripCookie = parse(url).host !== parse(this.url).host;
// implementation of 302 following defacto standard
if (res.statusCode == 301 || res.statusCode == 302) {
// strip Content-* related fields
// in case of POST etc
headers = utils.cleanHeader(this.req._headers, shouldStripCookie);
// force GET
this.method = 'HEAD' == this.method ? 'HEAD' : 'GET';
// clear data
this._data = null;
}
// 303 is always GET
if (res.statusCode == 303) {
// strip Content-* related fields
// in case of POST etc
headers = utils.cleanHeader(this.req._headers, shouldStripCookie);
// force method
this.method = 'GET';
// clear data
this._data = null;
}
// 307 preserves method
// 308 preserves method
delete headers.host;
delete this.req;
delete this._formData;
// remove all add header except User-Agent
_initHeaders(this);
// redirect
this.url = url;
this._redirectList.push(url);
this.emit('redirect', res);
this.qs = {};
this.qsRaw = [];
this.set(headers);
this.end(this._callback);
return this;
};
/**
* Set Authorization field value with `user` and `pass`.
*
* Examples:
*
* .auth('tobi', 'learnboost')
* .auth('tobi:learnboost')
* .auth('tobi')
*
* @param {String} user
* @param {String} pass
* @return {Request} for chaining
* @api public
*/
Request.prototype.auth = function (user, pass) {
if (1 === arguments.length) pass = '';
if (!~user.indexOf(':')) user = user + ':';
var str = new Buffer(user + pass).toString('base64');
return this.set('Authorization', 'Basic ' + str);
};
/**
* Set the certificate authority option for https request.
*
* @param {Buffer | Array} cert
* @return {Request} for chaining
* @api public
*/
Request.prototype.ca = function (cert) {
this._ca = cert;
return this;
};
/**
* Return an http[s] request.
*
* @return {OutgoingMessage}
* @api private
*/
Request.prototype.request = function () {
if (this.req) return this.req;
var self = this;
var options = {};
var data = this._data;
var url = this.url;
// default to http://
if (0 != url.indexOf('http')) url = 'http://' + url;
url = parse(url);
// options
options.method = this.method;
options.port = url.port;
options.path = url.pathname;
options.host = url.hostname;
options.ca = this._ca;
options.agent = this._agent;
// initiate request
var mod = exports.protocols[url.protocol];
// request
var req = this.req = mod.request(options);
if ('HEAD' != options.method) req.setHeader('Accept-Encoding', 'gzip, deflate');
this.protocol = url.protocol;
this.host = url.host;
// expose events
req.on('drain', function () {
self.emit('drain');
});
req.on('error', function (err) {
// flag abortion here for out timeouts
// because node will emit a faux-error "socket hang up"
// when request is aborted before a connection is made
if (self._aborted) return;
// if we've recieved a response then we don't want to let
// an error in the request blow up the response
if (self.response) return;
self.callback(err);
});
// auth
if (url.auth) {
var auth = url.auth.split(':');
this.auth(auth[0], auth[1]);
}
// query
if (url.search) this.query(url.search.substr(1));
// add cookies
if (this.cookies) req.setHeader('Cookie', this.cookies);
for (var key in this.header) {
req.setHeader(key, this.header[key]);
}
return req;
};
/**
* Invoke the callback with `err` and `res`
* and handle arity check.
*
* @param {Error} err
* @param {Response} res
* @api private
*/
Request.prototype.callback = function (err, res) {
// Avoid the error which is emitted from 'socket hang up' to cause the fn undefined error on JS runtime.
var fn = this._callback || noop;
this.clearTimeout();
if (this.called) return console.warn('superagent: double callback bug. Upgrade to v3.2+ to fix this');
this.called = true;
if (err) {
err.response = res;
}
// only emit error event if there is a listener
// otherwise we assume the callback to `.end()` will get the error
if (err && this.listeners('error').length > 0) this.emit('error', err);
if (err) {
return fn(err, res);
}
if (res && res.status >= 200 && res.status < 300) {
return fn(err, res);
}
var msg = 'Unsuccessful HTTP response';
if (res) {
msg = http.STATUS_CODES[res.status] || msg;
}
var new_err = new Error(msg);
new_err.original = err;
new_err.response = res;
new_err.status = res ? res.status : undefined;
fn(err || new_err, res);
};
/**
* Compose querystring to append to req.path
*
* @return {String} querystring
* @api private
*/
Request.prototype.appendQueryString = function (req) {
var querystring = qs.stringify(this.qs, { indices: false });
querystring += (querystring.length && this.qsRaw.length ? '&' : '') + this.qsRaw.join('&');
req.path += querystring.length ? (~req.path.indexOf('?') ? '&' : '?') + querystring : '';
};
/**
* Initiate request, invoking callback `fn(err, res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
/**
* Client API parity, irrelevant in a Node context.
*
* @api public
*/
Request.prototype.withCredentials = function () {
return this;
};
Request.prototype.end = function (fn) {
var self = this;
var data = this._data;
var req = this.request();
var buffer = this._buffer;
var method = this.method;
var timeout = this._timeout;
debug('%s %s', this.method, this.url);
// store callback
this._callback = fn || noop;
// querystring
try {
this.appendQueryString(req);
} catch (e) {
return this.callback(e);
}
// timeout
if (timeout && !this._timer) {
debug('timeout %sms %s %s', timeout, this.method, this.url);
this._timer = setTimeout(function () {
var err = new Error('timeout of ' + timeout + 'ms exceeded');
err.timeout = timeout;
err.code = 'ECONNABORTED';
self.abort();
self.callback(err);
}, timeout);
}
// body
if ('HEAD' != method && !req._headerSent) {
// serialize stuff
if ('string' != typeof data) {
var contentType = req.getHeader('Content-Type');
// Parse out just the content type from the header (ignore the charset)
if (contentType) contentType = contentType.split(';')[0];
var serialize = exports.serialize[contentType];
if (!serialize && isJSON(contentType)) serialize = exports.serialize['application/json'];
if (serialize) data = serialize(data);
}
// content-length
if (data && !req.getHeader('Content-Length')) {
req.setHeader('Content-Length', Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data));
}
}
// response
req.on('response', function (res) {