superagent.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  1. ;(function(){
  2. /**
  3. * Require the given path.
  4. *
  5. * @param {String} path
  6. * @return {Object} exports
  7. * @api public
  8. */
  9. function require(path, parent, orig) {
  10. var resolved = require.resolve(path);
  11. // lookup failed
  12. if (null == resolved) {
  13. orig = orig || path;
  14. parent = parent || 'root';
  15. var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
  16. err.path = orig;
  17. err.parent = parent;
  18. err.require = true;
  19. throw err;
  20. }
  21. var module = require.modules[resolved];
  22. // perform real require()
  23. // by invoking the module's
  24. // registered function
  25. if (!module._resolving && !module.exports) {
  26. var mod = {};
  27. mod.exports = {};
  28. mod.client = mod.component = true;
  29. module._resolving = true;
  30. module.call(this, mod.exports, require.relative(resolved), mod);
  31. delete module._resolving;
  32. module.exports = mod.exports;
  33. }
  34. return module.exports;
  35. }
  36. /**
  37. * Registered modules.
  38. */
  39. require.modules = {};
  40. /**
  41. * Registered aliases.
  42. */
  43. require.aliases = {};
  44. /**
  45. * Resolve `path`.
  46. *
  47. * Lookup:
  48. *
  49. * - PATH/index.js
  50. * - PATH.js
  51. * - PATH
  52. *
  53. * @param {String} path
  54. * @return {String} path or null
  55. * @api private
  56. */
  57. require.resolve = function(path) {
  58. if (path.charAt(0) === '/') path = path.slice(1);
  59. var paths = [
  60. path,
  61. path + '.js',
  62. path + '.json',
  63. path + '/index.js',
  64. path + '/index.json'
  65. ];
  66. for (var i = 0; i < paths.length; i++) {
  67. var path = paths[i];
  68. if (require.modules.hasOwnProperty(path)) return path;
  69. if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
  70. }
  71. };
  72. /**
  73. * Normalize `path` relative to the current path.
  74. *
  75. * @param {String} curr
  76. * @param {String} path
  77. * @return {String}
  78. * @api private
  79. */
  80. require.normalize = function(curr, path) {
  81. var segs = [];
  82. if ('.' != path.charAt(0)) return path;
  83. curr = curr.split('/');
  84. path = path.split('/');
  85. for (var i = 0; i < path.length; ++i) {
  86. if ('..' == path[i]) {
  87. curr.pop();
  88. } else if ('.' != path[i] && '' != path[i]) {
  89. segs.push(path[i]);
  90. }
  91. }
  92. return curr.concat(segs).join('/');
  93. };
  94. /**
  95. * Register module at `path` with callback `definition`.
  96. *
  97. * @param {String} path
  98. * @param {Function} definition
  99. * @api private
  100. */
  101. require.register = function(path, definition) {
  102. require.modules[path] = definition;
  103. };
  104. /**
  105. * Alias a module definition.
  106. *
  107. * @param {String} from
  108. * @param {String} to
  109. * @api private
  110. */
  111. require.alias = function(from, to) {
  112. if (!require.modules.hasOwnProperty(from)) {
  113. throw new Error('Failed to alias "' + from + '", it does not exist');
  114. }
  115. require.aliases[to] = from;
  116. };
  117. /**
  118. * Return a require function relative to the `parent` path.
  119. *
  120. * @param {String} parent
  121. * @return {Function}
  122. * @api private
  123. */
  124. require.relative = function(parent) {
  125. var p = require.normalize(parent, '..');
  126. /**
  127. * lastIndexOf helper.
  128. */
  129. function lastIndexOf(arr, obj) {
  130. var i = arr.length;
  131. while (i--) {
  132. if (arr[i] === obj) return i;
  133. }
  134. return -1;
  135. }
  136. /**
  137. * The relative require() itself.
  138. */
  139. function localRequire(path) {
  140. var resolved = localRequire.resolve(path);
  141. return require(resolved, parent, path);
  142. }
  143. /**
  144. * Resolve relative to the parent.
  145. */
  146. localRequire.resolve = function(path) {
  147. var c = path.charAt(0);
  148. if ('/' == c) return path.slice(1);
  149. if ('.' == c) return require.normalize(p, path);
  150. // resolve deps by returning
  151. // the dep in the nearest "deps"
  152. // directory
  153. var segs = parent.split('/');
  154. var i = lastIndexOf(segs, 'deps') + 1;
  155. if (!i) i = 0;
  156. path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
  157. return path;
  158. };
  159. /**
  160. * Check if module is defined at `path`.
  161. */
  162. localRequire.exists = function(path) {
  163. return require.modules.hasOwnProperty(localRequire.resolve(path));
  164. };
  165. return localRequire;
  166. };
  167. require.register("component-emitter/index.js", function(exports, require, module){
  168. /**
  169. * Expose `Emitter`.
  170. */
  171. module.exports = Emitter;
  172. /**
  173. * Initialize a new `Emitter`.
  174. *
  175. * @api public
  176. */
  177. function Emitter(obj) {
  178. if (obj) return mixin(obj);
  179. };
  180. /**
  181. * Mixin the emitter properties.
  182. *
  183. * @param {Object} obj
  184. * @return {Object}
  185. * @api private
  186. */
  187. function mixin(obj) {
  188. for (var key in Emitter.prototype) {
  189. obj[key] = Emitter.prototype[key];
  190. }
  191. return obj;
  192. }
  193. /**
  194. * Listen on the given `event` with `fn`.
  195. *
  196. * @param {String} event
  197. * @param {Function} fn
  198. * @return {Emitter}
  199. * @api public
  200. */
  201. Emitter.prototype.on =
  202. Emitter.prototype.addEventListener = function(event, fn){
  203. this._callbacks = this._callbacks || {};
  204. (this._callbacks[event] = this._callbacks[event] || [])
  205. .push(fn);
  206. return this;
  207. };
  208. /**
  209. * Adds an `event` listener that will be invoked a single
  210. * time then automatically removed.
  211. *
  212. * @param {String} event
  213. * @param {Function} fn
  214. * @return {Emitter}
  215. * @api public
  216. */
  217. Emitter.prototype.once = function(event, fn){
  218. var self = this;
  219. this._callbacks = this._callbacks || {};
  220. function on() {
  221. self.off(event, on);
  222. fn.apply(this, arguments);
  223. }
  224. on.fn = fn;
  225. this.on(event, on);
  226. return this;
  227. };
  228. /**
  229. * Remove the given callback for `event` or all
  230. * registered callbacks.
  231. *
  232. * @param {String} event
  233. * @param {Function} fn
  234. * @return {Emitter}
  235. * @api public
  236. */
  237. Emitter.prototype.off =
  238. Emitter.prototype.removeListener =
  239. Emitter.prototype.removeAllListeners =
  240. Emitter.prototype.removeEventListener = function(event, fn){
  241. this._callbacks = this._callbacks || {};
  242. // all
  243. if (0 == arguments.length) {
  244. this._callbacks = {};
  245. return this;
  246. }
  247. // specific event
  248. var callbacks = this._callbacks[event];
  249. if (!callbacks) return this;
  250. // remove all handlers
  251. if (1 == arguments.length) {
  252. delete this._callbacks[event];
  253. return this;
  254. }
  255. // remove specific handler
  256. var cb;
  257. for (var i = 0; i < callbacks.length; i++) {
  258. cb = callbacks[i];
  259. if (cb === fn || cb.fn === fn) {
  260. callbacks.splice(i, 1);
  261. break;
  262. }
  263. }
  264. return this;
  265. };
  266. /**
  267. * Emit `event` with the given args.
  268. *
  269. * @param {String} event
  270. * @param {Mixed} ...
  271. * @return {Emitter}
  272. */
  273. Emitter.prototype.emit = function(event){
  274. this._callbacks = this._callbacks || {};
  275. var args = [].slice.call(arguments, 1)
  276. , callbacks = this._callbacks[event];
  277. if (callbacks) {
  278. callbacks = callbacks.slice(0);
  279. for (var i = 0, len = callbacks.length; i < len; ++i) {
  280. callbacks[i].apply(this, args);
  281. }
  282. }
  283. return this;
  284. };
  285. /**
  286. * Return array of callbacks for `event`.
  287. *
  288. * @param {String} event
  289. * @return {Array}
  290. * @api public
  291. */
  292. Emitter.prototype.listeners = function(event){
  293. this._callbacks = this._callbacks || {};
  294. return this._callbacks[event] || [];
  295. };
  296. /**
  297. * Check if this emitter has `event` handlers.
  298. *
  299. * @param {String} event
  300. * @return {Boolean}
  301. * @api public
  302. */
  303. Emitter.prototype.hasListeners = function(event){
  304. return !! this.listeners(event).length;
  305. };
  306. });
  307. require.register("component-reduce/index.js", function(exports, require, module){
  308. /**
  309. * Reduce `arr` with `fn`.
  310. *
  311. * @param {Array} arr
  312. * @param {Function} fn
  313. * @param {Mixed} initial
  314. *
  315. * TODO: combatible error handling?
  316. */
  317. module.exports = function(arr, fn, initial){
  318. var idx = 0;
  319. var len = arr.length;
  320. var curr = arguments.length == 3
  321. ? initial
  322. : arr[idx++];
  323. while (idx < len) {
  324. curr = fn.call(null, curr, arr[idx], ++idx, arr);
  325. }
  326. return curr;
  327. };
  328. });
  329. require.register("superagent/lib/client.js", function(exports, require, module){
  330. /**
  331. * Module dependencies.
  332. */
  333. var Emitter = require('emitter');
  334. var reduce = require('reduce');
  335. /**
  336. * Root reference for iframes.
  337. */
  338. var root = 'undefined' == typeof window
  339. ? this
  340. : window;
  341. /**
  342. * Noop.
  343. */
  344. function noop(){};
  345. /**
  346. * Check if `obj` is a host object,
  347. * we don't want to serialize these :)
  348. *
  349. * TODO: future proof, move to compoent land
  350. *
  351. * @param {Object} obj
  352. * @return {Boolean}
  353. * @api private
  354. */
  355. function isHost(obj) {
  356. var str = {}.toString.call(obj);
  357. switch (str) {
  358. case '[object File]':
  359. case '[object Blob]':
  360. case '[object FormData]':
  361. return true;
  362. default:
  363. return false;
  364. }
  365. }
  366. /**
  367. * Determine XHR.
  368. */
  369. function getXHR() {
  370. if (root.XMLHttpRequest
  371. && ('file:' != root.location.protocol || !root.ActiveXObject)) {
  372. return new XMLHttpRequest;
  373. } else {
  374. try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
  375. try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
  376. try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
  377. try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
  378. }
  379. return false;
  380. }
  381. /**
  382. * Removes leading and trailing whitespace, added to support IE.
  383. *
  384. * @param {String} s
  385. * @return {String}
  386. * @api private
  387. */
  388. var trim = ''.trim
  389. ? function(s) { return s.trim(); }
  390. : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
  391. /**
  392. * Check if `obj` is an object.
  393. *
  394. * @param {Object} obj
  395. * @return {Boolean}
  396. * @api private
  397. */
  398. function isObject(obj) {
  399. return obj === Object(obj);
  400. }
  401. /**
  402. * Serialize the given `obj`.
  403. *
  404. * @param {Object} obj
  405. * @return {String}
  406. * @api private
  407. */
  408. function serialize(obj) {
  409. if (!isObject(obj)) return obj;
  410. var pairs = [];
  411. for (var key in obj) {
  412. if (null != obj[key]) {
  413. pairs.push(encodeURIComponent(key)
  414. + '=' + encodeURIComponent(obj[key]));
  415. }
  416. }
  417. return pairs.join('&');
  418. }
  419. /**
  420. * Expose serialization method.
  421. */
  422. request.serializeObject = serialize;
  423. /**
  424. * Parse the given x-www-form-urlencoded `str`.
  425. *
  426. * @param {String} str
  427. * @return {Object}
  428. * @api private
  429. */
  430. function parseString(str) {
  431. var obj = {};
  432. var pairs = str.split('&');
  433. var parts;
  434. var pair;
  435. for (var i = 0, len = pairs.length; i < len; ++i) {
  436. pair = pairs[i];
  437. parts = pair.split('=');
  438. obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
  439. }
  440. return obj;
  441. }
  442. /**
  443. * Expose parser.
  444. */
  445. request.parseString = parseString;
  446. /**
  447. * Default MIME type map.
  448. *
  449. * superagent.types.xml = 'application/xml';
  450. *
  451. */
  452. request.types = {
  453. html: 'text/html',
  454. json: 'application/json',
  455. xml: 'application/xml',
  456. urlencoded: 'application/x-www-form-urlencoded',
  457. 'form': 'application/x-www-form-urlencoded',
  458. 'form-data': 'application/x-www-form-urlencoded'
  459. };
  460. /**
  461. * Default serialization map.
  462. *
  463. * superagent.serialize['application/xml'] = function(obj){
  464. * return 'generated xml here';
  465. * };
  466. *
  467. */
  468. request.serialize = {
  469. 'application/x-www-form-urlencoded': serialize,
  470. 'application/json': JSON.stringify
  471. };
  472. /**
  473. * Default parsers.
  474. *
  475. * superagent.parse['application/xml'] = function(str){
  476. * return { object parsed from str };
  477. * };
  478. *
  479. */
  480. request.parse = {
  481. 'application/x-www-form-urlencoded': parseString,
  482. 'application/json': JSON.parse
  483. };
  484. /**
  485. * Parse the given header `str` into
  486. * an object containing the mapped fields.
  487. *
  488. * @param {String} str
  489. * @return {Object}
  490. * @api private
  491. */
  492. function parseHeader(str) {
  493. var lines = str.split(/\r?\n/);
  494. var fields = {};
  495. var index;
  496. var line;
  497. var field;
  498. var val;
  499. lines.pop(); // trailing CRLF
  500. for (var i = 0, len = lines.length; i < len; ++i) {
  501. line = lines[i];
  502. index = line.indexOf(':');
  503. field = line.slice(0, index).toLowerCase();
  504. val = trim(line.slice(index + 1));
  505. fields[field] = val;
  506. }
  507. return fields;
  508. }
  509. /**
  510. * Return the mime type for the given `str`.
  511. *
  512. * @param {String} str
  513. * @return {String}
  514. * @api private
  515. */
  516. function type(str){
  517. return str.split(/ *; */).shift();
  518. };
  519. /**
  520. * Return header field parameters.
  521. *
  522. * @param {String} str
  523. * @return {Object}
  524. * @api private
  525. */
  526. function params(str){
  527. return reduce(str.split(/ *; */), function(obj, str){
  528. var parts = str.split(/ *= */)
  529. , key = parts.shift()
  530. , val = parts.shift();
  531. if (key && val) obj[key] = val;
  532. return obj;
  533. }, {});
  534. };
  535. /**
  536. * Initialize a new `Response` with the given `xhr`.
  537. *
  538. * - set flags (.ok, .error, etc)
  539. * - parse header
  540. *
  541. * Examples:
  542. *
  543. * Aliasing `superagent` as `request` is nice:
  544. *
  545. * request = superagent;
  546. *
  547. * We can use the promise-like API, or pass callbacks:
  548. *
  549. * request.get('/').end(function(res){});
  550. * request.get('/', function(res){});
  551. *
  552. * Sending data can be chained:
  553. *
  554. * request
  555. * .post('/user')
  556. * .send({ name: 'tj' })
  557. * .end(function(res){});
  558. *
  559. * Or passed to `.send()`:
  560. *
  561. * request
  562. * .post('/user')
  563. * .send({ name: 'tj' }, function(res){});
  564. *
  565. * Or passed to `.post()`:
  566. *
  567. * request
  568. * .post('/user', { name: 'tj' })
  569. * .end(function(res){});
  570. *
  571. * Or further reduced to a single call for simple cases:
  572. *
  573. * request
  574. * .post('/user', { name: 'tj' }, function(res){});
  575. *
  576. * @param {XMLHTTPRequest} xhr
  577. * @param {Object} options
  578. * @api private
  579. */
  580. function Response(req, options) {
  581. options = options || {};
  582. this.req = req;
  583. this.xhr = this.req.xhr;
  584. this.text = this.req.method !='HEAD'
  585. ? this.xhr.responseText
  586. : null;
  587. this.setStatusProperties(this.xhr.status);
  588. this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
  589. // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
  590. // getResponseHeader still works. so we get content-type even if getting
  591. // other headers fails.
  592. this.header['content-type'] = this.xhr.getResponseHeader('content-type');
  593. this.setHeaderProperties(this.header);
  594. this.body = this.req.method != 'HEAD'
  595. ? this.parseBody(this.text)
  596. : null;
  597. }
  598. /**
  599. * Get case-insensitive `field` value.
  600. *
  601. * @param {String} field
  602. * @return {String}
  603. * @api public
  604. */
  605. Response.prototype.get = function(field){
  606. return this.header[field.toLowerCase()];
  607. };
  608. /**
  609. * Set header related properties:
  610. *
  611. * - `.type` the content type without params
  612. *
  613. * A response of "Content-Type: text/plain; charset=utf-8"
  614. * will provide you with a `.type` of "text/plain".
  615. *
  616. * @param {Object} header
  617. * @api private
  618. */
  619. Response.prototype.setHeaderProperties = function(header){
  620. // content-type
  621. var ct = this.header['content-type'] || '';
  622. this.type = type(ct);
  623. // params
  624. var obj = params(ct);
  625. for (var key in obj) this[key] = obj[key];
  626. };
  627. /**
  628. * Parse the given body `str`.
  629. *
  630. * Used for auto-parsing of bodies. Parsers
  631. * are defined on the `superagent.parse` object.
  632. *
  633. * @param {String} str
  634. * @return {Mixed}
  635. * @api private
  636. */
  637. Response.prototype.parseBody = function(str){
  638. var parse = request.parse[this.type];
  639. return parse && str && str.length
  640. ? parse(str)
  641. : null;
  642. };
  643. /**
  644. * Set flags such as `.ok` based on `status`.
  645. *
  646. * For example a 2xx response will give you a `.ok` of __true__
  647. * whereas 5xx will be __false__ and `.error` will be __true__. The
  648. * `.clientError` and `.serverError` are also available to be more
  649. * specific, and `.statusType` is the class of error ranging from 1..5
  650. * sometimes useful for mapping respond colors etc.
  651. *
  652. * "sugar" properties are also defined for common cases. Currently providing:
  653. *
  654. * - .noContent
  655. * - .badRequest
  656. * - .unauthorized
  657. * - .notAcceptable
  658. * - .notFound
  659. *
  660. * @param {Number} status
  661. * @api private
  662. */
  663. Response.prototype.setStatusProperties = function(status){
  664. var type = status / 100 | 0;
  665. // status / class
  666. this.status = status;
  667. this.statusType = type;
  668. // basics
  669. this.info = 1 == type;
  670. this.ok = 2 == type;
  671. this.clientError = 4 == type;
  672. this.serverError = 5 == type;
  673. this.error = (4 == type || 5 == type)
  674. ? this.toError()
  675. : false;
  676. // sugar
  677. this.accepted = 202 == status;
  678. this.noContent = 204 == status || 1223 == status;
  679. this.badRequest = 400 == status;
  680. this.unauthorized = 401 == status;
  681. this.notAcceptable = 406 == status;
  682. this.notFound = 404 == status;
  683. this.forbidden = 403 == status;
  684. };
  685. /**
  686. * Return an `Error` representative of this response.
  687. *
  688. * @return {Error}
  689. * @api public
  690. */
  691. Response.prototype.toError = function(){
  692. var req = this.req;
  693. var method = req.method;
  694. var url = req.url;
  695. var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
  696. var err = new Error(msg);
  697. err.status = this.status;
  698. err.method = method;
  699. err.url = url;
  700. return err;
  701. };
  702. /**
  703. * Expose `Response`.
  704. */
  705. request.Response = Response;
  706. /**
  707. * Initialize a new `Request` with the given `method` and `url`.
  708. *
  709. * @param {String} method
  710. * @param {String} url
  711. * @api public
  712. */
  713. function Request(method, url) {
  714. var self = this;
  715. Emitter.call(this);
  716. this._query = this._query || [];
  717. this.method = method;
  718. this.url = url;
  719. this.header = {};
  720. this._header = {};
  721. this.on('end', function(){
  722. var err = null;
  723. var res = null;
  724. try {
  725. res = new Response(self);
  726. } catch(e) {
  727. err = new Error('Parser is unable to parse the response');
  728. err.parse = true;
  729. err.original = e;
  730. }
  731. self.callback(err, res);
  732. });
  733. }
  734. /**
  735. * Mixin `Emitter`.
  736. */
  737. Emitter(Request.prototype);
  738. /**
  739. * Allow for extension
  740. */
  741. Request.prototype.use = function(fn) {
  742. fn(this);
  743. return this;
  744. }
  745. /**
  746. * Set timeout to `ms`.
  747. *
  748. * @param {Number} ms
  749. * @return {Request} for chaining
  750. * @api public
  751. */
  752. Request.prototype.timeout = function(ms){
  753. this._timeout = ms;
  754. return this;
  755. };
  756. /**
  757. * Clear previous timeout.
  758. *
  759. * @return {Request} for chaining
  760. * @api public
  761. */
  762. Request.prototype.clearTimeout = function(){
  763. this._timeout = 0;
  764. clearTimeout(this._timer);
  765. return this;
  766. };
  767. /**
  768. * Abort the request, and clear potential timeout.
  769. *
  770. * @return {Request}
  771. * @api public
  772. */
  773. Request.prototype.abort = function(){
  774. if (this.aborted) return;
  775. this.aborted = true;
  776. this.xhr.abort();
  777. this.clearTimeout();
  778. this.emit('abort');
  779. return this;
  780. };
  781. /**
  782. * Set header `field` to `val`, or multiple fields with one object.
  783. *
  784. * Examples:
  785. *
  786. * req.get('/')
  787. * .set('Accept', 'application/json')
  788. * .set('X-API-Key', 'foobar')
  789. * .end(callback);
  790. *
  791. * req.get('/')
  792. * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
  793. * .end(callback);
  794. *
  795. * @param {String|Object} field
  796. * @param {String} val
  797. * @return {Request} for chaining
  798. * @api public
  799. */
  800. Request.prototype.set = function(field, val){
  801. if (isObject(field)) {
  802. for (var key in field) {
  803. this.set(key, field[key]);
  804. }
  805. return this;
  806. }
  807. this._header[field.toLowerCase()] = val;
  808. this.header[field] = val;
  809. return this;
  810. };
  811. /**
  812. * Remove header `field`.
  813. *
  814. * Example:
  815. *
  816. * req.get('/')
  817. * .unset('User-Agent')
  818. * .end(callback);
  819. *
  820. * @param {String} field
  821. * @return {Request} for chaining
  822. * @api public
  823. */
  824. Request.prototype.unset = function(field){
  825. delete this._header[field.toLowerCase()];
  826. delete this.header[field];
  827. return this;
  828. };
  829. /**
  830. * Get case-insensitive header `field` value.
  831. *
  832. * @param {String} field
  833. * @return {String}
  834. * @api private
  835. */
  836. Request.prototype.getHeader = function(field){
  837. return this._header[field.toLowerCase()];
  838. };
  839. /**
  840. * Set Content-Type to `type`, mapping values from `request.types`.
  841. *
  842. * Examples:
  843. *
  844. * superagent.types.xml = 'application/xml';
  845. *
  846. * request.post('/')
  847. * .type('xml')
  848. * .send(xmlstring)
  849. * .end(callback);
  850. *
  851. * request.post('/')
  852. * .type('application/xml')
  853. * .send(xmlstring)
  854. * .end(callback);
  855. *
  856. * @param {String} type
  857. * @return {Request} for chaining
  858. * @api public
  859. */
  860. Request.prototype.type = function(type){
  861. this.set('Content-Type', request.types[type] || type);
  862. return this;
  863. };
  864. /**
  865. * Set Accept to `type`, mapping values from `request.types`.
  866. *
  867. * Examples:
  868. *
  869. * superagent.types.json = 'application/json';
  870. *
  871. * request.get('/agent')
  872. * .accept('json')
  873. * .end(callback);
  874. *
  875. * request.get('/agent')
  876. * .accept('application/json')
  877. * .end(callback);
  878. *
  879. * @param {String} accept
  880. * @return {Request} for chaining
  881. * @api public
  882. */
  883. Request.prototype.accept = function(type){
  884. this.set('Accept', request.types[type] || type);
  885. return this;
  886. };
  887. /**
  888. * Set Authorization field value with `user` and `pass`.
  889. *
  890. * @param {String} user
  891. * @param {String} pass
  892. * @return {Request} for chaining
  893. * @api public
  894. */
  895. Request.prototype.auth = function(user, pass){
  896. var str = btoa(user + ':' + pass);
  897. this.set('Authorization', 'Basic ' + str);
  898. return this;
  899. };
  900. /**
  901. * Add query-string `val`.
  902. *
  903. * Examples:
  904. *
  905. * request.get('/shoes')
  906. * .query('size=10')
  907. * .query({ color: 'blue' })
  908. *
  909. * @param {Object|String} val
  910. * @return {Request} for chaining
  911. * @api public
  912. */
  913. Request.prototype.query = function(val){
  914. if ('string' != typeof val) val = serialize(val);
  915. if (val) this._query.push(val);
  916. return this;
  917. };
  918. /**
  919. * Write the field `name` and `val` for "multipart/form-data"
  920. * request bodies.
  921. *
  922. * ``` js
  923. * request.post('/upload')
  924. * .field('foo', 'bar')
  925. * .end(callback);
  926. * ```
  927. *
  928. * @param {String} name
  929. * @param {String|Blob|File} val
  930. * @return {Request} for chaining
  931. * @api public
  932. */
  933. Request.prototype.field = function(name, val){
  934. if (!this._formData) this._formData = new FormData();
  935. this._formData.append(name, val);
  936. return this;
  937. };
  938. /**
  939. * Queue the given `file` as an attachment to the specified `field`,
  940. * with optional `filename`.
  941. *
  942. * ``` js
  943. * request.post('/upload')
  944. * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
  945. * .end(callback);
  946. * ```
  947. *
  948. * @param {String} field
  949. * @param {Blob|File} file
  950. * @param {String} filename
  951. * @return {Request} for chaining
  952. * @api public
  953. */
  954. Request.prototype.attach = function(field, file, filename){
  955. if (!this._formData) this._formData = new FormData();
  956. this._formData.append(field, file, filename);
  957. return this;
  958. };
  959. /**
  960. * Send `data`, defaulting the `.type()` to "json" when
  961. * an object is given.
  962. *
  963. * Examples:
  964. *
  965. * // querystring
  966. * request.get('/search')
  967. * .end(callback)
  968. *
  969. * // multiple data "writes"
  970. * request.get('/search')
  971. * .send({ search: 'query' })
  972. * .send({ range: '1..5' })
  973. * .send({ order: 'desc' })
  974. * .end(callback)
  975. *
  976. * // manual json
  977. * request.post('/user')
  978. * .type('json')
  979. * .send('{"name":"tj"})
  980. * .end(callback)
  981. *
  982. * // auto json
  983. * request.post('/user')
  984. * .send({ name: 'tj' })
  985. * .end(callback)
  986. *
  987. * // manual x-www-form-urlencoded
  988. * request.post('/user')
  989. * .type('form')
  990. * .send('name=tj')
  991. * .end(callback)
  992. *
  993. * // auto x-www-form-urlencoded
  994. * request.post('/user')
  995. * .type('form')
  996. * .send({ name: 'tj' })
  997. * .end(callback)
  998. *
  999. * // defaults to x-www-form-urlencoded
  1000. * request.post('/user')
  1001. * .send('name=tobi')
  1002. * .send('species=ferret')
  1003. * .end(callback)
  1004. *
  1005. * @param {String|Object} data
  1006. * @return {Request} for chaining
  1007. * @api public
  1008. */
  1009. Request.prototype.send = function(data){
  1010. var obj = isObject(data);
  1011. var type = this.getHeader('Content-Type');
  1012. // merge
  1013. if (obj && isObject(this._data)) {
  1014. for (var key in data) {
  1015. this._data[key] = data[key];
  1016. }
  1017. } else if ('string' == typeof data) {
  1018. if (!type) this.type('form');
  1019. type = this.getHeader('Content-Type');
  1020. if ('application/x-www-form-urlencoded' == type) {
  1021. this._data = this._data
  1022. ? this._data + '&' + data
  1023. : data;
  1024. } else {
  1025. this._data = (this._data || '') + data;
  1026. }
  1027. } else {
  1028. this._data = data;
  1029. }
  1030. if (!obj) return this;
  1031. if (!type) this.type('json');
  1032. return this;
  1033. };
  1034. /**
  1035. * Invoke the callback with `err` and `res`
  1036. * and handle arity check.
  1037. *
  1038. * @param {Error} err
  1039. * @param {Response} res
  1040. * @api private
  1041. */
  1042. Request.prototype.callback = function(err, res){
  1043. var fn = this._callback;
  1044. this.clearTimeout();
  1045. if (2 == fn.length) return fn(err, res);
  1046. if (err) return this.emit('error', err);
  1047. fn(res);
  1048. };
  1049. /**
  1050. * Invoke callback with x-domain error.
  1051. *
  1052. * @api private
  1053. */
  1054. Request.prototype.crossDomainError = function(){
  1055. var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
  1056. err.crossDomain = true;
  1057. this.callback(err);
  1058. };
  1059. /**
  1060. * Invoke callback with timeout error.
  1061. *
  1062. * @api private
  1063. */
  1064. Request.prototype.timeoutError = function(){
  1065. var timeout = this._timeout;
  1066. var err = new Error('timeout of ' + timeout + 'ms exceeded');
  1067. err.timeout = timeout;
  1068. this.callback(err);
  1069. };
  1070. /**
  1071. * Enable transmission of cookies with x-domain requests.
  1072. *
  1073. * Note that for this to work the origin must not be
  1074. * using "Access-Control-Allow-Origin" with a wildcard,
  1075. * and also must set "Access-Control-Allow-Credentials"
  1076. * to "true".
  1077. *
  1078. * @api public
  1079. */
  1080. Request.prototype.withCredentials = function(){
  1081. this._withCredentials = true;
  1082. return this;
  1083. };
  1084. /**
  1085. * Initiate request, invoking callback `fn(res)`
  1086. * with an instanceof `Response`.
  1087. *
  1088. * @param {Function} fn
  1089. * @return {Request} for chaining
  1090. * @api public
  1091. */
  1092. Request.prototype.end = function(fn){
  1093. var self = this;
  1094. var xhr = this.xhr = getXHR();
  1095. var query = this._query.join('&');
  1096. var timeout = this._timeout;
  1097. var data = this._formData || this._data;
  1098. // store callback
  1099. this._callback = fn || noop;
  1100. // state change
  1101. xhr.onreadystatechange = function(){
  1102. if (4 != xhr.readyState) return;
  1103. if (0 == xhr.status) {
  1104. if (self.aborted) return self.timeoutError();
  1105. return self.crossDomainError();
  1106. }
  1107. self.emit('end');
  1108. };
  1109. // progress
  1110. if (xhr.upload) {
  1111. xhr.upload.onprogress = function(e){
  1112. e.percent = e.loaded / e.total * 100;
  1113. self.emit('progress', e);
  1114. };
  1115. }
  1116. // timeout
  1117. if (timeout && !this._timer) {
  1118. this._timer = setTimeout(function(){
  1119. self.abort();
  1120. }, timeout);
  1121. }
  1122. // querystring
  1123. if (query) {
  1124. query = request.serializeObject(query);
  1125. this.url += ~this.url.indexOf('?')
  1126. ? '&' + query
  1127. : '?' + query;
  1128. }
  1129. // initiate request
  1130. xhr.open(this.method, this.url, true);
  1131. // CORS
  1132. if (this._withCredentials) xhr.withCredentials = true;
  1133. // body
  1134. if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
  1135. // serialize stuff
  1136. var serialize = request.serialize[this.getHeader('Content-Type')];
  1137. if (serialize) data = serialize(data);
  1138. }
  1139. // set header fields
  1140. for (var field in this.header) {
  1141. if (null == this.header[field]) continue;
  1142. xhr.setRequestHeader(field, this.header[field]);
  1143. }
  1144. // send stuff
  1145. this.emit('request', this);
  1146. xhr.send(data);
  1147. return this;
  1148. };
  1149. /**
  1150. * Expose `Request`.
  1151. */
  1152. request.Request = Request;
  1153. /**
  1154. * Issue a request:
  1155. *
  1156. * Examples:
  1157. *
  1158. * request('GET', '/users').end(callback)
  1159. * request('/users').end(callback)
  1160. * request('/users', callback)
  1161. *
  1162. * @param {String} method
  1163. * @param {String|Function} url or callback
  1164. * @return {Request}
  1165. * @api public
  1166. */
  1167. function request(method, url) {
  1168. // callback
  1169. if ('function' == typeof url) {
  1170. return new Request('GET', method).end(url);
  1171. }
  1172. // url first
  1173. if (1 == arguments.length) {
  1174. return new Request('GET', method);
  1175. }
  1176. return new Request(method, url);
  1177. }
  1178. /**
  1179. * GET `url` with optional callback `fn(res)`.
  1180. *
  1181. * @param {String} url
  1182. * @param {Mixed|Function} data or fn
  1183. * @param {Function} fn
  1184. * @return {Request}
  1185. * @api public
  1186. */
  1187. request.get = function(url, data, fn){
  1188. var req = request('GET', url);
  1189. if ('function' == typeof data) fn = data, data = null;
  1190. if (data) req.query(data);
  1191. if (fn) req.end(fn);
  1192. return req;
  1193. };
  1194. /**
  1195. * HEAD `url` with optional callback `fn(res)`.
  1196. *
  1197. * @param {String} url
  1198. * @param {Mixed|Function} data or fn
  1199. * @param {Function} fn
  1200. * @return {Request}
  1201. * @api public
  1202. */
  1203. request.head = function(url, data, fn){
  1204. var req = request('HEAD', url);
  1205. if ('function' == typeof data) fn = data, data = null;
  1206. if (data) req.send(data);
  1207. if (fn) req.end(fn);
  1208. return req;
  1209. };
  1210. /**
  1211. * DELETE `url` with optional callback `fn(res)`.
  1212. *
  1213. * @param {String} url
  1214. * @param {Function} fn
  1215. * @return {Request}
  1216. * @api public
  1217. */
  1218. request.del = function(url, fn){
  1219. var req = request('DELETE', url);
  1220. if (fn) req.end(fn);
  1221. return req;
  1222. };
  1223. /**
  1224. * PATCH `url` with optional `data` and callback `fn(res)`.
  1225. *
  1226. * @param {String} url
  1227. * @param {Mixed} data
  1228. * @param {Function} fn
  1229. * @return {Request}
  1230. * @api public
  1231. */
  1232. request.patch = function(url, data, fn){
  1233. var req = request('PATCH', url);
  1234. if ('function' == typeof data) fn = data, data = null;
  1235. if (data) req.send(data);
  1236. if (fn) req.end(fn);
  1237. return req;
  1238. };
  1239. /**
  1240. * POST `url` with optional `data` and callback `fn(res)`.
  1241. *
  1242. * @param {String} url
  1243. * @param {Mixed} data
  1244. * @param {Function} fn
  1245. * @return {Request}
  1246. * @api public
  1247. */
  1248. request.post = function(url, data, fn){
  1249. var req = request('POST', url);
  1250. if ('function' == typeof data) fn = data, data = null;
  1251. if (data) req.send(data);
  1252. if (fn) req.end(fn);
  1253. return req;
  1254. };
  1255. /**
  1256. * PUT `url` with optional `data` and callback `fn(res)`.
  1257. *
  1258. * @param {String} url
  1259. * @param {Mixed|Function} data or fn
  1260. * @param {Function} fn
  1261. * @return {Request}
  1262. * @api public
  1263. */
  1264. request.put = function(url, data, fn){
  1265. var req = request('PUT', url);
  1266. if ('function' == typeof data) fn = data, data = null;
  1267. if (data) req.send(data);
  1268. if (fn) req.end(fn);
  1269. return req;
  1270. };
  1271. /**
  1272. * Expose `request`.
  1273. */
  1274. module.exports = request;
  1275. });
  1276. require.alias("component-emitter/index.js", "superagent/deps/emitter/index.js");
  1277. require.alias("component-emitter/index.js", "emitter/index.js");
  1278. require.alias("component-reduce/index.js", "superagent/deps/reduce/index.js");
  1279. require.alias("component-reduce/index.js", "reduce/index.js");
  1280. require.alias("superagent/lib/client.js", "superagent/index.js");if (typeof exports == "object") {
  1281. module.exports = require("superagent");
  1282. } else if (typeof define == "function" && define.amd) {
  1283. define([], function(){ return require("superagent"); });
  1284. } else {
  1285. this["superagent"] = require("superagent");
  1286. }})();