32. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 10/24/2017 6:38:26 AM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

32.1 Files compared

# Location File Last Modified
1 CHAMP_VA1.zip\CHAMP_VA1\node_modules\gulp-nodemon\node_modules\nodemon\node_modules\chokidar\node_modules\fsevents\node_modules\request request.js Mon Oct 16 21:06:50 2017 UTC
2 CHAMP_VA1.zip\CHAMP_VA1\node_modules\gulp-nodemon\node_modules\nodemon\node_modules\chokidar\node_modules\fsevents\node_modules\request request.js Mon Oct 23 19:37:36 2017 UTC

32.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 3126
Changed 1 4
Inserted 0 0
Removed 0 0

32.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

32.4 Active regular expressions

No regular expressions were active.

32.5 Comparison detail

  1   'use stric t'
  2  
  3   var http =  require(' http')
  4     , https  = require( 'https')
  5     , url =  require('u rl')
  6     , util =  require(' util')
  7     , stream  = require ('stream')
  8     , zlib =  require(' zlib')
  9     , hawk =  require(' hawk')
  10     , aws2 =  require(' aws-sign2' )
  11     , aws4 =  require(' aws4')
  12     , httpSi gnature =  require('h ttp-signat ure')
  13     , mime =  require(' mime-types ')
  14     , string stream = r equire('st ringstream ')
  15     , casele ss = requi re('casele ss')
  16     , Foreve rAgent = r equire('fo rever-agen t')
  17     , FormDa ta = requi re('form-d ata')
  18     , extend  = require ('extend')
  19     , isstre am = requi re('isstre am')
  20     , isType dArray = r equire('is -typedarra y').strict
  21     , helper s = requir e('./lib/h elpers')
  22     , cookie s = requir e('./lib/c ookies')
  23     , getPro xyFromURI  = require( './lib/get ProxyFromU RI')
  24     , Querys tring = re quire('./l ib/queryst ring').Que rystring
  25     , Har =  require('. /lib/har') .Har
  26     , Auth =  require(' ./lib/auth ').Auth
  27     , OAuth  = require( './lib/oau th').OAuth
  28     , Multip art = requ ire('./lib /multipart ').Multipa rt
  29     , Redire ct = requi re('./lib/ redirect') .Redirect
  30     , Tunnel  = require ('./lib/tu nnel').Tun nel
  31     , now =  require('p erformance -now')
  32     , Buffer  = require ('safe-buf fer').Buff er
  33  
  34   var safeSt ringify =  helpers.sa feStringif y
  35     , isRead Stream = h elpers.isR eadStream
  36     , toBase 64 = helpe rs.toBase6 4
  37     , defer  = helpers. defer
  38     , copy =  helpers.c opy
  39     , versio n = helper s.version
  40     , global CookieJar  = cookies. jar()
  41  
  42  
  43   var global Pool = {}
  44  
  45   function f ilterForNo nReserved( reserved,  options) {
  46     // Filte r out prop erties tha t are not  reserved.
  47     // Reser ved values  are passe d in at ca ll site.
  48  
  49     var obje ct = {}
  50     for (var  i in opti ons) {
  51       var no tReserved  = (reserve d.indexOf( i) === -1)
  52       if (no tReserved)  {
  53         obje ct[i] = op tions[i]
  54       }
  55     }
  56     return o bject
  57   }
  58  
  59   function f ilterOutRe servedFunc tions(rese rved, opti ons) {
  60     // Filte r out prop erties tha t are func tions and  are reserv ed.
  61     // Reser ved values  are passe d in at ca ll site.
  62  
  63     var obje ct = {}
  64     for (var  i in opti ons) {
  65       var is Reserved =  !(reserve d.indexOf( i) === -1)
  66       var is Function =  (typeof o ptions[i]  === 'funct ion')
  67       if (!( isReserved  && isFunc tion)) {
  68         obje ct[i] = op tions[i]
  69       }
  70     }
  71     return o bject
  72  
  73   }
  74  
  75   // Return  a simpler  request ob ject to al low serial ization
  76   function r equestToJS ON() {
  77     var self  = this
  78     return {
  79       uri: s elf.uri,
  80       method : self.met hod,
  81       header s: self.he aders
  82     }
  83   }
  84  
  85   // Return  a simpler  response o bject to a llow seria lization
  86   function r esponseToJ SON() {
  87     var self  = this
  88     return {
  89       status Code: self .statusCod e,
  90       body:  self.body,
  91       header s: self.he aders,
  92       reques t: request ToJSON.cal l(self.req uest)
  93     }
  94   }
  95  
  96   function R equest (op tions) {
  97     // if gi ven the me thod prope rty in opt ions, set  property e xplicitMet hod to tru e
  98  
  99     // exten d the Requ est instan ce with an y non-rese rved prope rties
  100     // remov e any rese rved funct ions from  the option s object
  101     // set R equest ins tance to b e readable  and writa ble
  102     // call  init
  103  
  104     var self  = this
  105  
  106     // start  with HAR,  then over ride with  additional  options
  107     if (opti ons.har) {
  108       self._ har = new  Har(self)
  109       option s = self._ har.option s(options)
  110     }
  111  
  112     stream.S tream.call (self)
  113     var rese rved = Obj ect.keys(R equest.pro totype)
  114     var nonR eserved =  filterForN onReserved (reserved,  options)
  115  
  116     extend(s elf, nonRe served)
  117     options  = filterOu tReservedF unctions(r eserved, o ptions)
  118  
  119     self.rea dable = tr ue
  120     self.wri table = tr ue
  121     if (opti ons.method ) {
  122       self.e xplicitMet hod = true
  123     }
  124     self._qs  = new Que rystring(s elf)
  125     self._au th = new A uth(self)
  126     self._oa uth = new  OAuth(self )
  127     self._mu ltipart =  new Multip art(self)
  128     self._re direct = n ew Redirec t(self)
  129     self._tu nnel = new  Tunnel(se lf)
  130     self.ini t(options)
  131   }
  132  
  133   util.inher its(Reques t, stream. Stream)
  134  
  135   // Debuggi ng
  136   Request.de bug = proc ess.env.NO DE_DEBUG & & /\breque st\b/.test (process.e nv.NODE_DE BUG)
  137   function d ebug() {
  138     if (Requ est.debug)  {
  139       consol e.error('R EQUEST %s' , util.for mat.apply( util, argu ments))
  140     }
  141   }
  142   Request.pr ototype.de bug = debu g
  143  
  144   Request.pr ototype.in it = funct ion (optio ns) {
  145     // init( ) contains  all the c ode to set up the req uest objec t.
  146     // the a ctual outg oing reque st is not  started un til start( ) is calle d
  147     // this  function i s called f rom both t he constru ctor and o n redirect .
  148     var self  = this
  149     if (!opt ions) {
  150       option s = {}
  151     }
  152     self.hea ders = sel f.headers  ? copy(sel f.headers)  : {}
  153  
  154     // Delet e headers  with value  undefined  since the y break
  155     // Clien tRequest.O utgoingMes sage.setHe ader in no de 0.12
  156     for (var  headerNam e in self. headers) {
  157       if (ty peof self. headers[he aderName]  === 'undef ined') {
  158         dele te self.he aders[head erName]
  159       }
  160     }
  161  
  162     caseless .httpify(s elf, self. headers)
  163  
  164     if (!sel f.method)  {
  165       self.m ethod = op tions.meth od || 'GET '
  166     }
  167     if (!sel f.localAdd ress) {
  168       self.l ocalAddres s = option s.localAdd ress
  169     }
  170  
  171     self._qs .init(opti ons)
  172  
  173     debug(op tions)
  174     if (!sel f.pool &&  self.pool  !== false)  {
  175       self.p ool = glob alPool
  176     }
  177     self.des ts = self. dests || [ ]
  178     self.__i sRequestRe quest = tr ue
  179  
  180     // Prote ct against  double ca llback
  181     if (!sel f._callbac k && self. callback)  {
  182       self._ callback =  self.call back
  183       self.c allback =  function ( ) {
  184         if ( self._call backCalled ) {
  185           re turn // Pr int a warn ing maybe?
  186         }
  187         self ._callback Called = t rue
  188         self ._callback .apply(sel f, argumen ts)
  189       }
  190       self.o n('error',  self.call back.bind( ))
  191       self.o n('complet e', self.c allback.bi nd(self, n ull))
  192     }
  193  
  194     // Peopl e use this  property  instead al l the time , so suppo rt it
  195     if (!sel f.uri && s elf.url) {
  196       self.u ri = self. url
  197       delete  self.url
  198     }
  199  
  200     // If th ere's a ba seUrl, the n use it a s the base  URL (i.e.  uri must  be
  201     // speci fied as a  relative p ath and is  appended  to baseUrl ).
  202     if (self .baseUrl)  {
  203       if (ty peof self. baseUrl != = 'string' ) {
  204         retu rn self.em it('error' , new Erro r('options .baseUrl m ust be a s tring'))
  205       }
  206  
  207       if (ty peof self. uri !== 's tring') {
  208         retu rn self.em it('error' , new Erro r('options .uri must  be a strin g when usi ng options .baseUrl') )
  209       }
  210  
  211       if (se lf.uri.ind exOf('//')  === 0 ||  self.uri.i ndexOf(':/ /') !== -1 ) {
  212         retu rn self.em it('error' , new Erro r('options .uri must  be a path  when using  options.b aseUrl'))
  213       }
  214  
  215       // Han dle all ca ses to mak e sure tha t there's  only one s lash betwe en
  216       // bas eUrl and u ri.
  217       var ba seUrlEndsW ithSlash =  self.base Url.lastIn dexOf('/')  === self. baseUrl.le ngth - 1
  218       var ur iStartsWit hSlash = s elf.uri.in dexOf('/')  === 0
  219  
  220       if (ba seUrlEndsW ithSlash & & uriStart sWithSlash ) {
  221         self .uri = sel f.baseUrl  + self.uri .slice(1)
  222       } else  if (baseU rlEndsWith Slash || u riStartsWi thSlash) {
  223         self .uri = sel f.baseUrl  + self.uri
  224       } else  if (self. uri === '' ) {
  225         self .uri = sel f.baseUrl
  226       } else  {
  227         self .uri = sel f.baseUrl  + '/' + se lf.uri
  228       }
  229       delete  self.base Url
  230     }
  231  
  232     // A URI  is needed  by this p oint, emit  error if  we haven't  been able  to get on e
  233     if (!sel f.uri) {
  234       return  self.emit ('error',  new Error( 'options.u ri is a re quired arg ument'))
  235     }
  236  
  237     // If a  string URI /URL was g iven, pars e it into  a URL obje ct
  238     if (type of self.ur i === 'str ing') {
  239       self.u ri = url.p arse(self. uri)
  240     }
  241  
  242     // Some  URL object s are not  from a URL  parsed st ring and n eed href a dded
  243     if (!sel f.uri.href ) {
  244       self.u ri.href =  url.format (self.uri)
  245     }
  246  
  247     // DEPRE CATED: War ning for u sers of th e old Unix  Sockets U RL Scheme
  248     if (self .uri.proto col === 'u nix:') {
  249       return  self.emit ('error',  new Error( '`unix://`  URL schem e is no lo nger suppo rted. Plea se use the  format `h ttp://unix :SOCKET:PA TH`'))
  250     }
  251  
  252     // Suppo rt Unix So ckets
  253     if (self .uri.host  === 'unix' ) {
  254       self.e nableUnixS ocket()
  255     }
  256  
  257     if (self .strictSSL  === false ) {
  258       self.r ejectUnaut horized =  false
  259     }
  260  
  261     if (!sel f.uri.path name) {sel f.uri.path name = '/' }
  262  
  263     if (!(se lf.uri.hos t || (self .uri.hostn ame && sel f.uri.port )) && !sel f.uri.isUn ix) {
  264       // Inv alid URI:  it may gen erate lot  of bad err ors, like  'TypeError : Cannot c all method  `indexOf`  of undefi ned' in Co okieJar
  265       // Det ect and re ject it as  soon as p ossible
  266       var fa ultyUri =  url.format (self.uri)
  267       var me ssage = 'I nvalid URI  "' + faul tyUri + '" '
  268       if (Ob ject.keys( options).l ength ===  0) {
  269         // N o option ?  This can  be the sig n of a red irect
  270         // A s this is  a case whe re the use r cannot d o anything  (they did n't call r equest dir ectly with  this URL)
  271         // t hey should  be warned  that it c an be caus ed by a re direction  (can save  some hair)
  272         mess age += '.  This can b e caused b y a crappy  redirecti on.'
  273       }
  274       // Thi s error wa s fatal
  275       self.a bort()
  276       return  self.emit ('error',  new Error( message))
  277     }
  278  
  279     if (!sel f.hasOwnPr operty('pr oxy')) {
  280       self.p roxy = get ProxyFromU RI(self.ur i)
  281     }
  282  
  283     self.tun nel = self ._tunnel.i sEnabled()
  284     if (self .proxy) {
  285       self._ tunnel.set up(options )
  286     }
  287  
  288     self._re direct.onR equest(opt ions)
  289  
  290     self.set Host = fal se
  291     if (!sel f.hasHeade r('host'))  {
  292       var ho stHeaderNa me = self. originalHo stHeaderNa me || 'hos t'
  293       // Whe n used wit h an IPv6  address, ` host` will  provide
  294       // the  correct b racketed f ormat, unl ike using  `hostname`  and
  295       // opt ionally ad ding the ` port` when  necessary .
  296       self.s etHeader(h ostHeaderN ame, self. uri.host)
  297       self.s etHost = t rue
  298     }
  299  
  300     self.jar (self._jar  || option s.jar)
  301  
  302     if (!sel f.uri.port ) {
  303         if (self.u ri.protoco l === 'htt p:') {self .uri.port  PORT }
  304         else if (s elf.uri.pr otocol ===  'https:')  {self.uri .port =  PORT }
  305     }
  306  
  307     if (self .proxy &&  !self.tunn el) {
  308       self.p ort = self .proxy.por t
  309       self.h ost = self .proxy.hos tname
  310     } else {
  311       self.p ort = self .uri.port
  312       self.h ost = self .uri.hostn ame
  313     }
  314  
  315     if (opti ons.form)  {
  316       self.f orm(option s.form)
  317     }
  318  
  319     if (opti ons.formDa ta) {
  320       var fo rmData = o ptions.for mData
  321       var re questForm  = self.for m()
  322       var ap pendFormVa lue = func tion (key,  value) {
  323         if ( value && v alue.hasOw nProperty( 'value') & & value.ha sOwnProper ty('option s')) {
  324           re questForm. append(key , value.va lue, value .options)
  325         } el se {
  326           re questForm. append(key , value)
  327         }
  328       }
  329       for (v ar formKey  in formDa ta) {
  330         if ( formData.h asOwnPrope rty(formKe y)) {
  331           va r formValu e = formDa ta[formKey ]
  332           if  (formValu e instance of Array)  {
  333              for (var j  = 0; j <  formValue. length; j+ +) {
  334                appendFo rmValue(fo rmKey, for mValue[j])
  335              }
  336           }  else {
  337              appendForm Value(form Key, formV alue)
  338           }
  339         }
  340       }
  341     }
  342  
  343     if (opti ons.qs) {
  344       self.q s(options. qs)
  345     }
  346  
  347     if (self .uri.path)  {
  348       self.p ath = self .uri.path
  349     } else {
  350       self.p ath = self .uri.pathn ame + (sel f.uri.sear ch || '')
  351     }
  352  
  353     if (self .path.leng th === 0)  {
  354       self.p ath = '/'
  355     }
  356  
  357     // Auth  must happe n last in  case signi ng is depe ndent on o ther heade rs
  358     if (opti ons.aws) {
  359       self.a ws(options .aws)
  360     }
  361  
  362     if (opti ons.hawk)  {
  363       self.h awk(option s.hawk)
  364     }
  365  
  366     if (opti ons.httpSi gnature) {
  367       self.h ttpSignatu re(options .httpSigna ture)
  368     }
  369  
  370     if (opti ons.auth)  {
  371       if (Ob ject.proto type.hasOw nProperty. call(optio ns.auth, ' username') ) {
  372         opti ons.auth.u ser = opti ons.auth.u sername
  373       }
  374       if (Ob ject.proto type.hasOw nProperty. call(optio ns.auth, ' password') ) {
  375         opti ons.auth.p ass = opti ons.auth.p assword
  376       }
  377  
  378       self.a uth(
  379         opti ons.auth.u ser,
  380         opti ons.auth.p ass,
  381         opti ons.auth.s endImmedia tely,
  382         opti ons.auth.b earer
  383       )
  384     }
  385  
  386     if (self .gzip && ! self.hasHe ader('acce pt-encodin g')) {
  387       self.s etHeader(' accept-enc oding', 'g zip, defla te')
  388     }
  389  
  390     if (self .uri.auth  && !self.h asHeader(' authorizat ion')) {
  391       var ur iAuthPiece s = self.u ri.auth.sp lit(':').m ap(functio n(item) {r eturn self ._qs.unesc ape(item)} )
  392       self.a uth(uriAut hPieces[0] , uriAuthP ieces.slic e(1).join( ':'), true )
  393     }
  394  
  395     if (!sel f.tunnel & & self.pro xy && self .proxy.aut h && !self .hasHeader ('proxy-au thorizatio n')) {
  396       var pr oxyAuthPie ces = self .proxy.aut h.split(': ').map(fun ction(item ) {return  self._qs.u nescape(it em)})
  397       var au thHeader =  'Basic '  + toBase64 (proxyAuth Pieces.joi n(':'))
  398       self.s etHeader(' proxy-auth orization' , authHead er)
  399     }
  400  
  401     if (self .proxy &&  !self.tunn el) {
  402       self.p ath = (sel f.uri.prot ocol + '// ' + self.u ri.host +  self.path)
  403     }
  404  
  405     if (opti ons.json)  {
  406       self.j son(option s.json)
  407     }
  408     if (opti ons.multip art) {
  409       self.m ultipart(o ptions.mul tipart)
  410     }
  411  
  412     if (opti ons.time)  {
  413       self.t iming = tr ue
  414  
  415       // NOT E: elapsed Time is de precated i n favor of  .timings
  416       self.e lapsedTime  = self.el apsedTime  || 0
  417     }
  418  
  419     function  setConten tLength ()  {
  420       if (is TypedArray (self.body )) {
  421         self .body = Bu ffer.from( self.body)
  422       }
  423  
  424       if (!s elf.hasHea der('conte nt-length' )) {
  425         var  length
  426         if ( typeof sel f.body ===  'string')  {
  427           le ngth = Buf fer.byteLe ngth(self. body)
  428         }
  429         else  if (Array .isArray(s elf.body))  {
  430           le ngth = sel f.body.red uce(functi on (a, b)  {return a  + b.length }, 0)
  431         }
  432         else  {
  433           le ngth = sel f.body.len gth
  434         }
  435  
  436         if ( length) {
  437           se lf.setHead er('conten t-length',  length)
  438         } el se {
  439           se lf.emit('e rror', new  Error('Ar gument err or, option s.body.'))
  440         }
  441       }
  442     }
  443     if (self .body && ! isstream(s elf.body))  {
  444       setCon tentLength ()
  445     }
  446  
  447     if (opti ons.oauth)  {
  448       self.o auth(optio ns.oauth)
  449     } else i f (self._o auth.param s && self. hasHeader( 'authoriza tion')) {
  450       self.o auth(self. _oauth.par ams)
  451     }
  452  
  453     var prot ocol = sel f.proxy &&  !self.tun nel ? self .proxy.pro tocol : se lf.uri.pro tocol
  454       , defa ultModules  = {'http: ':http, 'h ttps:':htt ps}
  455       , http Modules =  self.httpM odules ||  {}
  456  
  457     self.htt pModule =  httpModule s[protocol ] || defau ltModules[ protocol]
  458  
  459     if (!sel f.httpModu le) {
  460       return  self.emit ('error',  new Error( 'Invalid p rotocol: '  + protoco l))
  461     }
  462  
  463     if (opti ons.ca) {
  464       self.c a = option s.ca
  465     }
  466  
  467     if (!sel f.agent) {
  468       if (op tions.agen tOptions)  {
  469         self .agentOpti ons = opti ons.agentO ptions
  470       }
  471  
  472       if (op tions.agen tClass) {
  473         self .agentClas s = option s.agentCla ss
  474       } else  if (optio ns.forever ) {
  475         var  v = versio n()
  476         // u se Forever Agent in n ode 0.10-  only
  477         if ( v.major == = 0 && v.m inor <= 10 ) {
  478           se lf.agentCl ass = prot ocol === ' http:' ? F oreverAgen t : Foreve rAgent.SSL
  479         } el se {
  480           se lf.agentCl ass = self .httpModul e.Agent
  481           se lf.agentOp tions = se lf.agentOp tions || { }
  482           se lf.agentOp tions.keep Alive = tr ue
  483         }
  484       } else  {
  485         self .agentClas s = self.h ttpModule. Agent
  486       }
  487     }
  488  
  489     if (self .pool ===  false) {
  490       self.a gent = fal se
  491     } else {
  492       self.a gent = sel f.agent ||  self.getN ewAgent()
  493     }
  494  
  495     self.on( 'pipe', fu nction (sr c) {
  496       if (se lf.ntick & & self._st arted) {
  497         self .emit('err or', new E rror('You  cannot pip e to this  stream aft er the out bound requ est has st arted.'))
  498       }
  499       self.s rc = src
  500       if (is ReadStream (src)) {
  501         if ( !self.hasH eader('con tent-type' )) {
  502           se lf.setHead er('conten t-type', m ime.lookup (src.path) )
  503         }
  504       } else  {
  505         if ( src.header s) {
  506           fo r (var i i n src.head ers) {
  507              if (!self. hasHeader( i)) {
  508                self.set Header(i,  src.header s[i])
  509              }
  510           }
  511         }
  512         if ( self._json  && !self. hasHeader( 'content-t ype')) {
  513           se lf.setHead er('conten t-type', ' applicatio n/json')
  514         }
  515         if ( src.method  && !self. explicitMe thod) {
  516           se lf.method  = src.meth od
  517         }
  518       }
  519  
  520       // sel f.on('pipe ', functio n () {
  521       //   c onsole.err or('You ha ve already  piped to  this strea m. Pipeing  twice is  likely to  break the  request.')
  522       // })
  523     })
  524  
  525     defer(fu nction ()  {
  526       if (se lf._aborte d) {
  527         retu rn
  528       }
  529  
  530       var en d = functi on () {
  531         if ( self._form ) {
  532           if  (!self._a uth.hasAut h) {
  533              self._form .pipe(self )
  534           }
  535           el se if (sel f._auth.ha sAuth && s elf._auth. sentAuth)  {
  536              self._form .pipe(self )
  537           }
  538         }
  539         if ( self._mult ipart && s elf._multi part.chunk ed) {
  540           se lf._multip art.body.p ipe(self)
  541         }
  542         if ( self.body)  {
  543           if  (isstream (self.body )) {
  544              self.body. pipe(self)
  545           }  else {
  546              setContent Length()
  547              if (Array. isArray(se lf.body))  {
  548                self.bod y.forEach( function ( part) {
  549                  self.w rite(part)
  550                })
  551              } else {
  552                self.wri te(self.bo dy)
  553              }
  554              self.end()
  555           }
  556         } el se if (sel f.requestB odyStream)  {
  557           co nsole.warn ('options. requestBod yStream is  deprecate d, please  pass the r equest obj ect to str eam.pipe.' )
  558           se lf.request BodyStream .pipe(self )
  559         } el se if (!se lf.src) {
  560           if  (self._au th.hasAuth  && !self. _auth.sent Auth) {
  561              self.end()
  562              return
  563           }
  564           if  (self.met hod !== 'G ET' && typ eof self.m ethod !==  'undefined ') {
  565              self.setHe ader('cont ent-length ', 0)
  566           }
  567           se lf.end()
  568         }
  569       }
  570  
  571       if (se lf._form & & !self.ha sHeader('c ontent-len gth')) {
  572         // B efore endi ng the req uest, we h ad to comp ute the le ngth of th e whole fo rm, asyncl y
  573         self .setHeader (self._for m.getHeade rs(), true )
  574         self ._form.get Length(fun ction (err , length)  {
  575           if  (!err &&  !isNaN(len gth)) {
  576              self.setHe ader('cont ent-length ', length)
  577           }
  578           en d()
  579         })
  580       } else  {
  581         end( )
  582       }
  583  
  584       self.n tick = tru e
  585     })
  586  
  587   }
  588  
  589   Request.pr ototype.ge tNewAgent  = function  () {
  590     var self  = this
  591     var Agen t = self.a gentClass
  592     var opti ons = {}
  593     if (self .agentOpti ons) {
  594       for (v ar i in se lf.agentOp tions) {
  595         opti ons[i] = s elf.agentO ptions[i]
  596       }
  597     }
  598     if (self .ca) {
  599       option s.ca = sel f.ca
  600     }
  601     if (self .ciphers)  {
  602       option s.ciphers  = self.cip hers
  603     }
  604     if (self .securePro tocol) {
  605       option s.securePr otocol = s elf.secure Protocol
  606     }
  607     if (self .secureOpt ions) {
  608       option s.secureOp tions = se lf.secureO ptions
  609     }
  610     if (type of self.re jectUnauth orized !==  'undefine d') {
  611       option s.rejectUn authorized  = self.re jectUnauth orized
  612     }
  613  
  614     if (self .cert && s elf.key) {
  615       option s.key = se lf.key
  616       option s.cert = s elf.cert
  617     }
  618  
  619     if (self .pfx) {
  620       option s.pfx = se lf.pfx
  621     }
  622  
  623     if (self .passphras e) {
  624       option s.passphra se = self. passphrase
  625     }
  626  
  627     var pool Key = ''
  628  
  629     // diffe rent types  of agents  are in di fferent po ols
  630     if (Agen t !== self .httpModul e.Agent) {
  631       poolKe y += Agent .name
  632     }
  633  
  634     // ca op tion is on ly relevan t if proxy  or destin ation are  https
  635     var prox y = self.p roxy
  636     if (type of proxy = == 'string ') {
  637       proxy  = url.pars e(proxy)
  638     }
  639     var isHt tps = (pro xy && prox y.protocol  === 'http s:') || th is.uri.pro tocol ===  'https:'
  640  
  641     if (isHt tps) {
  642       if (op tions.ca)  {
  643         if ( poolKey) {
  644           po olKey += ' :'
  645         }
  646         pool Key += opt ions.ca
  647       }
  648  
  649       if (ty peof optio ns.rejectU nauthorize d !== 'und efined') {
  650         if ( poolKey) {
  651           po olKey += ' :'
  652         }
  653         pool Key += opt ions.rejec tUnauthori zed
  654       }
  655  
  656       if (op tions.cert ) {
  657         if ( poolKey) {
  658           po olKey += ' :'
  659         }
  660         pool Key += opt ions.cert. toString(' ascii') +  options.ke y.toString ('ascii')
  661       }
  662  
  663       if (op tions.pfx)  {
  664         if ( poolKey) {
  665           po olKey += ' :'
  666         }
  667         pool Key += opt ions.pfx.t oString('a scii')
  668       }
  669  
  670       if (op tions.ciph ers) {
  671         if ( poolKey) {
  672           po olKey += ' :'
  673         }
  674         pool Key += opt ions.ciphe rs
  675       }
  676  
  677       if (op tions.secu reProtocol ) {
  678         if ( poolKey) {
  679           po olKey += ' :'
  680         }
  681         pool Key += opt ions.secur eProtocol
  682       }
  683  
  684       if (op tions.secu reOptions)  {
  685         if ( poolKey) {
  686           po olKey += ' :'
  687         }
  688         pool Key += opt ions.secur eOptions
  689       }
  690     }
  691  
  692     if (self .pool ===  globalPool  && !poolK ey && Obje ct.keys(op tions).len gth === 0  && self.ht tpModule.g lobalAgent ) {
  693       // not  doing any thing spec ial.  Use  the global Agent
  694       return  self.http Module.glo balAgent
  695     }
  696  
  697     // we're  using a s tored agen t.  Make s ure it's p rotocol-sp ecific
  698     poolKey  = self.uri .protocol  + poolKey
  699  
  700     // gener ate a new  agent for  this setti ng if none  yet exist s
  701     if (!sel f.pool[poo lKey]) {
  702       self.p ool[poolKe y] = new A gent(optio ns)
  703       // pro perly set  maxSockets  on new ag ents
  704       if (se lf.pool.ma xSockets)  {
  705         self .pool[pool Key].maxSo ckets = se lf.pool.ma xSockets
  706       }
  707     }
  708  
  709     return s elf.pool[p oolKey]
  710   }
  711  
  712   Request.pr ototype.st art = func tion () {
  713     // start () is call ed once we  are ready  to send t he outgoin g HTTP req uest.
  714     // this  is usually  called on  the first  write(),  end() or o n nextTick ()
  715     var self  = this
  716  
  717     if (self .timing) {
  718       // All  timings w ill be rel ative to t his reques t's startT ime.  In o rder to do  this,
  719       // we  need to ca pture the  wall-clock  start tim e (via Dat e), immedi ately foll owed
  720       // by  the high-r esolution  timer (via  now()).   While thes e two won' t be set
  721       // at  the _exact _ same tim e, they sh ould be cl ose enough  to be abl e to calcu late
  722       // hig h-resoluti on, monoto nically no n-decreasi ng timesta mps relati ve to star tTime.
  723       var st artTime =  new Date() .getTime()
  724       var st artTimeNow  = now()
  725     }
  726  
  727     if (self ._aborted)  {
  728       return
  729     }
  730  
  731     self._st arted = tr ue
  732     self.met hod = self .method ||  'GET'
  733     self.hre f = self.u ri.href
  734  
  735     if (self .src && se lf.src.sta t && self. src.stat.s ize && !se lf.hasHead er('conten t-length') ) {
  736       self.s etHeader(' content-le ngth', sel f.src.stat .size)
  737     }
  738     if (self ._aws) {
  739       self.a ws(self._a ws, true)
  740     }
  741  
  742     // We ha ve a metho d named au th, which  is complet ely differ ent from t he http.re quest
  743     // auth  option.  I f we don't  remove it , we're go nna have a  bad time.
  744     var reqO ptions = c opy(self)
  745     delete r eqOptions. auth
  746  
  747     debug('m ake reques t', self.u ri.href)
  748  
  749     // node  v6.8.0 now  supports  a `timeout ` value in  `http.req uest()`, b ut we
  750     // shoul d delete i t for now  since we h andle time outs manua lly for be tter
  751     // consi stency wit h node ver sions befo re v6.8.0
  752     delete r eqOptions. timeout
  753  
  754     try {
  755       self.r eq = self. httpModule .request(r eqOptions)
  756     } catch  (err) {
  757       self.e mit('error ', err)
  758       return
  759     }
  760  
  761     if (self .timing) {
  762       self.s tartTime =  startTime
  763       self.s tartTimeNo w = startT imeNow
  764  
  765       // Tim ing values  will all  be relativ e to start Time (by c omparing t o startTim eNow
  766       // so  we have an  accurate  clock)
  767       self.t imings = { }
  768     }
  769  
  770     var time out
  771     if (self .timeout & & !self.ti meoutTimer ) {
  772       if (se lf.timeout  < 0) {
  773         time out = 0
  774       } else  if (typeo f self.tim eout === ' number' &&  isFinite( self.timeo ut)) {
  775         time out = self .timeout
  776       }
  777     }
  778  
  779     self.req .on('respo nse', self .onRequest Response.b ind(self))
  780     self.req .on('error ', self.on RequestErr or.bind(se lf))
  781     self.req .on('drain ', functio n() {
  782       self.e mit('drain ')
  783     })
  784     self.req .on('socke t', functi on(socket)  {
  785       // `._ connecting ` was the  old proper ty which w as made pu blic in no de v6.1.0
  786       var is Connecting  = socket. _connectin g || socke t.connecti ng
  787       if (se lf.timing)  {
  788         self .timings.s ocket = no w() - self .startTime Now
  789  
  790         if ( isConnecti ng) {
  791           va r onLookup Timing = f unction()  {
  792              self.timin gs.lookup  = now() -  self.start TimeNow
  793           }
  794  
  795           va r onConnec tTiming =  function()  {
  796              self.timin gs.connect  = now() -  self.star tTimeNow
  797           }
  798  
  799           so cket.once( 'lookup',  onLookupTi ming)
  800           so cket.once( 'connect',  onConnect Timing)
  801  
  802           //  clean up  timing eve nt listene rs if need ed on erro r
  803           se lf.req.onc e('error',  function( ) {
  804              socket.rem oveListene r('lookup' , onLookup Timing)
  805              socket.rem oveListene r('connect ', onConne ctTiming)
  806           })
  807         }
  808       }
  809  
  810       var se tReqTimeou t = functi on() {
  811         // T his timeou t sets the  amount of  time to w ait *betwe en* bytes  sent
  812         // f rom the se rver once  connected.
  813         //
  814         // I n particul ar, it's u seful for  erroring i f the serv er fails t o send
  815         // d ata halfwa y through  streaming  a response .
  816         self .req.setTi meout(time out, funct ion () {
  817           if  (self.req ) {
  818              self.abort ()
  819              var e = ne w Error('E SOCKETTIME DOUT')
  820              e.code = ' ESOCKETTIM EDOUT'
  821              e.connect  = false
  822              self.emit( 'error', e )
  823           }
  824         })
  825       }
  826       if (ti meout !==  undefined)  {
  827         // O nly start  the connec tion timer  if we're  actually c onnecting  a new
  828         // s ocket, oth erwise if  we're alre ady connec ted (becau se this is  a
  829         // k eep-alive  connection ) do not b other. Thi s is impor tant since  we won't
  830         // g et a 'conn ect' event  for an al ready conn ected sock et.
  831         if ( isConnecti ng) {
  832           va r onReqSoc kConnect =  function( ) {
  833              socket.rem oveListene r('connect ', onReqSo ckConnect)
  834              clearTimeo ut(self.ti meoutTimer )
  835              self.timeo utTimer =  null
  836              setReqTime out()
  837           }
  838  
  839           so cket.on('c onnect', o nReqSockCo nnect)
  840  
  841           se lf.req.on( 'error', f unction(er r) {
  842              socket.rem oveListene r('connect ', onReqSo ckConnect)
  843           })
  844  
  845           //  Set a tim eout in me mory - thi s block wi ll throw i f the serv er takes m ore
  846           //  than `tim eout` to w rite the H TTP status  and heade rs (corres ponding to
  847           //  the on('r esponse')  event on t he client) . NB: this  measures  wall-clock
  848           //  time, not  the time  between by tes sent b y the serv er.
  849           se lf.timeout Timer = se tTimeout(f unction ()  {
  850              socket.rem oveListene r('connect ', onReqSo ckConnect)
  851              self.abort ()
  852              var e = ne w Error('E TIMEDOUT')
  853              e.code = ' ETIMEDOUT'
  854              e.connect  = true
  855              self.emit( 'error', e )
  856           },  timeout)
  857         } el se {
  858           //  We're alr eady conne cted
  859           se tReqTimeou t()
  860         }
  861       }
  862       self.e mit('socke t', socket )
  863     })
  864  
  865     self.emi t('request ', self.re q)
  866   }
  867  
  868   Request.pr ototype.on RequestErr or = funct ion (error ) {
  869     var self  = this
  870     if (self ._aborted)  {
  871       return
  872     }
  873     if (self .req && se lf.req._re usedSocket  && error. code === ' ECONNRESET '
  874         && s elf.agent. addRequest Noreuse) {
  875       self.a gent = { a ddRequest:  self.agen t.addReque stNoreuse. bind(self. agent) }
  876       self.s tart()
  877       self.r eq.end()
  878       return
  879     }
  880     if (self .timeout & & self.tim eoutTimer)  {
  881       clearT imeout(sel f.timeoutT imer)
  882       self.t imeoutTime r = null
  883     }
  884     self.emi t('error',  error)
  885   }
  886  
  887   Request.pr ototype.on RequestRes ponse = fu nction (re sponse) {
  888     var self  = this
  889  
  890     if (self .timing) {
  891       self.t imings.res ponse = no w() - self .startTime Now
  892     }
  893  
  894     debug('o nRequestRe sponse', s elf.uri.hr ef, respon se.statusC ode, respo nse.header s)
  895     response .on('end',  function( ) {
  896       if (se lf.timing)  {
  897         self .timings.e nd = now()  - self.st artTimeNow
  898         resp onse.timin gStart = s elf.startT ime
  899  
  900         // f ill in the  blanks fo r any peri ods that d idn't trig ger, such  as
  901         // n o lookup o r connect  due to kee p alive
  902         if ( !self.timi ngs.socket ) {
  903           se lf.timings .socket =  0
  904         }
  905         if ( !self.timi ngs.lookup ) {
  906           se lf.timings .lookup =  self.timin gs.socket
  907         }
  908         if ( !self.timi ngs.connec t) {
  909           se lf.timings .connect =  self.timi ngs.lookup
  910         }
  911         if ( !self.timi ngs.respon se) {
  912           se lf.timings .response  = self.tim ings.conne ct
  913         }
  914  
  915         debu g('elapsed  time', se lf.timings .end)
  916  
  917         // e lapsedTime  includes  all redire cts
  918         self .elapsedTi me += Math .round(sel f.timings. end)
  919  
  920         // N OTE: elaps edTime is  deprecated  in favor  of .timing s
  921         resp onse.elaps edTime = s elf.elapse dTime
  922  
  923         // t imings is  just for t he final f etch
  924         resp onse.timin gs = self. timings
  925  
  926         // p re-calcula te phase t imings as  well
  927         resp onse.timin gPhases =  {
  928           wa it: self.t imings.soc ket,
  929           dn s: self.ti mings.look up - self. timings.so cket,
  930           tc p: self.ti mings.conn ect - self .timings.l ookup,
  931           fi rstByte: s elf.timing s.response  - self.ti mings.conn ect,
  932           do wnload: se lf.timings .end - sel f.timings. response,
  933           to tal: self. timings.en d
  934         }
  935       }
  936       debug( 'response  end', self .uri.href,  response. statusCode , response .headers)
  937     })
  938  
  939     if (self ._aborted)  {
  940       debug( 'aborted',  self.uri. href)
  941       respon se.resume( )
  942       return
  943     }
  944  
  945     self.res ponse = re sponse
  946     response .request =  self
  947     response .toJSON =  responseTo JSON
  948  
  949     // XXX T his is dif ferent on  0.10, beca use SSL is  strict by  default
  950     if (self .httpModul e === http s &&
  951         self .strictSSL  && (!resp onse.hasOw nProperty( 'socket')  ||
  952         !res ponse.sock et.authori zed)) {
  953       debug( 'strict ss l error',  self.uri.h ref)
  954       var ss lErr = res ponse.hasO wnProperty ('socket')  ? respons e.socket.a uthorizati onError :  self.uri.h ref + ' do es not sup port SSL'
  955       self.e mit('error ', new Err or('SSL Er ror: ' + s slErr))
  956       return
  957     }
  958  
  959     // Save  the origin al host be fore any r edirect (i f it chang es, we nee d to
  960     // remov e any auth orization  headers).   Also reme mber the c ase of the  header
  961     // name  because lo ts of brok en servers  expect Ho st instead  of host a nd we
  962     // want  the caller  to be abl e to speci fy this.
  963     self.ori ginalHost  = self.get Header('ho st')
  964     if (!sel f.original HostHeader Name) {
  965       self.o riginalHos tHeaderNam e = self.h asHeader(' host')
  966     }
  967     if (self .setHost)  {
  968       self.r emoveHeade r('host')
  969     }
  970     if (self .timeout & & self.tim eoutTimer)  {
  971       clearT imeout(sel f.timeoutT imer)
  972       self.t imeoutTime r = null
  973     }
  974  
  975     var targ etCookieJa r = (self. _jar && se lf._jar.se tCookie) ?  self._jar  : globalC ookieJar
  976     var addC ookie = fu nction (co okie) {
  977       //set  the cookie  if it's d omain in t he href's  domain.
  978       try {
  979         targ etCookieJa r.setCooki e(cookie,  self.uri.h ref, {igno reError: t rue})
  980       } catc h (e) {
  981         self .emit('err or', e)
  982       }
  983     }
  984  
  985     response .caseless  = caseless (response. headers)
  986  
  987     if (resp onse.casel ess.has('s et-cookie' ) && (!sel f._disable Cookies))  {
  988       var he aderName =  response. caseless.h as('set-co okie')
  989       if (Ar ray.isArra y(response .headers[h eaderName] )) {
  990         resp onse.heade rs[headerN ame].forEa ch(addCook ie)
  991       } else  {
  992         addC ookie(resp onse.heade rs[headerN ame])
  993       }
  994     }
  995  
  996     if (self ._redirect .onRespons e(response )) {
  997       return  // Ignore  the rest  of the res ponse
  998     } else {
  999       // Be  a good str eam and em it end whe n the resp onse is fi nished.
  1000       // Hac k to emit  end on clo se because  of a core  bug that  never fire s end
  1001       respon se.on('clo se', funct ion () {
  1002         if ( !self._end ed) {
  1003           se lf.respons e.emit('en d')
  1004         }
  1005       })
  1006  
  1007       respon se.once('e nd', funct ion () {
  1008         self ._ended =  true
  1009       })
  1010  
  1011       var no Body = fun ction (cod e) {
  1012         retu rn (
  1013           se lf.method  === 'HEAD'
  1014           //  Informati onal
  1015           ||  (code >=  100 && cod e < 200)
  1016           //  No Conten t
  1017           ||  code ===  204
  1018           //  Not Modif ied
  1019           ||  code ===  304
  1020         )
  1021       }
  1022  
  1023       var re sponseCont ent
  1024       if (se lf.gzip &&  !noBody(r esponse.st atusCode))  {
  1025         var  contentEnc oding = re sponse.hea ders['cont ent-encodi ng'] || 'i dentity'
  1026         cont entEncodin g = conten tEncoding. trim().toL owerCase()
  1027  
  1028         // B e more len ient with  decoding c ompressed  responses,  since (ve ry rarely)
  1029         // s ervers sen d slightly  invalid g zip respon ses that a re still a ccepted
  1030         // b y common b rowsers.
  1031         // A lways usin g Z_SYNC_F LUSH is wh at cURL do es.
  1032         var  zlibOption s = {
  1033           fl ush: zlib. Z_SYNC_FLU SH
  1034         , fi nishFlush:  zlib.Z_SY NC_FLUSH
  1035         }
  1036  
  1037         if ( contentEnc oding ===  'gzip') {
  1038           re sponseCont ent = zlib .createGun zip(zlibOp tions)
  1039           re sponse.pip e(response Content)
  1040         } el se if (con tentEncodi ng === 'de flate') {
  1041           re sponseCont ent = zlib .createInf late(zlibO ptions)
  1042           re sponse.pip e(response Content)
  1043         } el se {
  1044           //  Since pre vious vers ions didn' t check fo r Content- Encoding h eader,
  1045           //  ignore an y invalid  values to  preserve b ackwards-c ompatibili ty
  1046           if  (contentE ncoding != = 'identit y') {
  1047              debug('ign oring unre cognized C ontent-Enc oding ' +  contentEnc oding)
  1048           }
  1049           re sponseCont ent = resp onse
  1050         }
  1051       } else  {
  1052         resp onseConten t = respon se
  1053       }
  1054  
  1055       if (se lf.encodin g) {
  1056         if ( self.dests .length != = 0) {
  1057           co nsole.erro r('Ignorin g encoding  parameter  as this s tream is b eing piped  to anothe r stream w hich makes  the encod ing option  invalid.' )
  1058         } el se if (res ponseConte nt.setEnco ding) {
  1059           re sponseCont ent.setEnc oding(self .encoding)
  1060         } el se {
  1061           //  Should on ly occur o n node pre -v0.9.4 (j oyent/node @9b5abe5)  with
  1062           //  zlib stre ams.
  1063           //  If/When s upport for  0.9.4 is  dropped, t his should  be unnece ssary.
  1064           re sponseCont ent = resp onseConten t.pipe(str ingstream( self.encod ing))
  1065         }
  1066       }
  1067  
  1068       if (se lf._paused ) {
  1069         resp onseConten t.pause()
  1070       }
  1071  
  1072       self.r esponseCon tent = res ponseConte nt
  1073  
  1074       self.e mit('respo nse', resp onse)
  1075  
  1076       self.d ests.forEa ch(functio n (dest) {
  1077         self .pipeDest( dest)
  1078       })
  1079  
  1080       respon seContent. on('data',  function  (chunk) {
  1081         if ( self.timin g && !self .responseS tarted) {
  1082           se lf.respons eStartTime  = (new Da te()).getT ime()
  1083  
  1084           //  NOTE: res ponseStart Time is de precated i n favor of  .timings
  1085           re sponse.res ponseStart Time = sel f.response StartTime
  1086         }
  1087         self ._destdata  = true
  1088         self .emit('dat a', chunk)
  1089       })
  1090       respon seContent. once('end' , function  (chunk) {
  1091         self .emit('end ', chunk)
  1092       })
  1093       respon seContent. on('error' , function  (error) {
  1094         self .emit('err or', error )
  1095       })
  1096       respon seContent. on('close' , function  () {self. emit('clos e')})
  1097  
  1098       if (se lf.callbac k) {
  1099         self .readRespo nseBody(re sponse)
  1100       }
  1101       //if n o callback
  1102       else {
  1103         self .on('end',  function  () {
  1104           if  (self._ab orted) {
  1105              debug('abo rted', sel f.uri.href )
  1106              return
  1107           }
  1108           se lf.emit('c omplete',  response)
  1109         })
  1110       }
  1111     }
  1112     debug('f inish init  function' , self.uri .href)
  1113   }
  1114  
  1115   Request.pr ototype.re adResponse Body = fun ction (res ponse) {
  1116     var self  = this
  1117     debug('r eading res ponse\'s b ody')
  1118     var buff ers = []
  1119       , buff erLength =  0
  1120       , stri ngs = []
  1121  
  1122     self.on( 'data', fu nction (ch unk) {
  1123       if (!B uffer.isBu ffer(chunk )) {
  1124         stri ngs.push(c hunk)
  1125       } else  if (chunk .length) {
  1126         buff erLength + = chunk.le ngth
  1127         buff ers.push(c hunk)
  1128       }
  1129     })
  1130     self.on( 'end', fun ction () {
  1131       debug( 'end event ', self.ur i.href)
  1132       if (se lf._aborte d) {
  1133         debu g('aborted ', self.ur i.href)
  1134         // ` buffer` is  defined i n the pare nt scope a nd used in  a closure  it exists  for the l ife of the  request.
  1135         // T his can le ad to leak y behavior  if the us er retains  a referen ce to the  request ob ject.
  1136         buff ers = []
  1137         buff erLength =  0
  1138         retu rn
  1139       }
  1140  
  1141       if (bu fferLength ) {
  1142         debu g('has bod y', self.u ri.href, b ufferLengt h)
  1143         resp onse.body  = Buffer.c oncat(buff ers, buffe rLength)
  1144         if ( self.encod ing !== nu ll) {
  1145           re sponse.bod y = respon se.body.to String(sel f.encoding )
  1146         }
  1147         // ` buffer` is  defined i n the pare nt scope a nd used in  a closure  it exists  for the l ife of the  Request.
  1148         // T his can le ad to leak y behavior  if the us er retains  a referen ce to the  request ob ject.
  1149         buff ers = []
  1150         buff erLength =  0
  1151       } else  if (strin gs.length)  {
  1152         // T he UTF8 BO M [0xEF,0x BB,0xBF] i s converte d to [0xFE ,0xFF] in  the JS UTC 16/UCS2 re presentati on.
  1153         // S trip this  value out  when the e ncoding is  set to 'u tf8', as u pstream co nsumers wo n't expect  it and it  breaks JS ON.parse() .
  1154         if ( self.encod ing === 'u tf8' && st rings[0].l ength > 0  && strings [0][0] ===  '\uFEFF')  {
  1155           st rings[0] =  strings[0 ].substrin g(1)
  1156         }
  1157         resp onse.body  = strings. join('')
  1158       }
  1159  
  1160       if (se lf._json)  {
  1161         try  {
  1162           re sponse.bod y = JSON.p arse(respo nse.body,  self._json Reviver)
  1163         } ca tch (e) {
  1164           de bug('inval id JSON re ceived', s elf.uri.hr ef)
  1165         }
  1166       }
  1167       debug( 'emitting  complete',  self.uri. href)
  1168       if (ty peof respo nse.body = == 'undefi ned' && !s elf._json)  {
  1169         resp onse.body  = self.enc oding ===  null ? Buf fer.alloc( 0) : ''
  1170       }
  1171       self.e mit('compl ete', resp onse, resp onse.body)
  1172     })
  1173   }
  1174  
  1175   Request.pr ototype.ab ort = func tion () {
  1176     var self  = this
  1177     self._ab orted = tr ue
  1178  
  1179     if (self .req) {
  1180       self.r eq.abort()
  1181     }
  1182     else if  (self.resp onse) {
  1183       self.r esponse.de stroy()
  1184     }
  1185  
  1186     self.emi t('abort')
  1187   }
  1188  
  1189   Request.pr ototype.pi peDest = f unction (d est) {
  1190     var self  = this
  1191     var resp onse = sel f.response
  1192     // Calle d after th e response  is receiv ed
  1193     if (dest .headers & & !dest.he adersSent)  {
  1194       if (re sponse.cas eless.has( 'content-t ype')) {
  1195         var  ctname = r esponse.ca seless.has ('content- type')
  1196         if ( dest.setHe ader) {
  1197           de st.setHead er(ctname,  response. headers[ct name])
  1198         }
  1199         else  {
  1200           de st.headers [ctname] =  response. headers[ct name]
  1201         }
  1202       }
  1203  
  1204       if (re sponse.cas eless.has( 'content-l ength')) {
  1205         var  clname = r esponse.ca seless.has ('content- length')
  1206         if ( dest.setHe ader) {
  1207           de st.setHead er(clname,  response. headers[cl name])
  1208         } el se {
  1209           de st.headers [clname] =  response. headers[cl name]
  1210         }
  1211       }
  1212     }
  1213     if (dest .setHeader  && !dest. headersSen t) {
  1214       for (v ar i in re sponse.hea ders) {
  1215         // I f the resp onse conte nt is bein g decoded,  the Conte nt-Encodin g header
  1216         // o f the resp onse doesn 't represe nt the pip ed content , so don't  pass it.
  1217         if ( !self.gzip  || i !==  'content-e ncoding')  {
  1218           de st.setHead er(i, resp onse.heade rs[i])
  1219         }
  1220       }
  1221       dest.s tatusCode  = response .statusCod e
  1222     }
  1223     if (self .pipefilte r) {
  1224       self.p ipefilter( response,  dest)
  1225     }
  1226   }
  1227  
  1228   Request.pr ototype.qs  = functio n (q, clob ber) {
  1229     var self  = this
  1230     var base
  1231     if (!clo bber && se lf.uri.que ry) {
  1232       base =  self._qs. parse(self .uri.query )
  1233     } else {
  1234       base =  {}
  1235     }
  1236  
  1237     for (var  i in q) {
  1238       base[i ] = q[i]
  1239     }
  1240  
  1241     var qs =  self._qs. stringify( base)
  1242  
  1243     if (qs = == '') {
  1244       return  self
  1245     }
  1246  
  1247     self.uri  = url.par se(self.ur i.href.spl it('?')[0]  + '?' + q s)
  1248     self.url  = self.ur i
  1249     self.pat h = self.u ri.path
  1250  
  1251     if (self .uri.host  === 'unix' ) {
  1252       self.e nableUnixS ocket()
  1253     }
  1254  
  1255     return s elf
  1256   }
  1257   Request.pr ototype.fo rm = funct ion (form)  {
  1258     var self  = this
  1259     if (form ) {
  1260       if (!/ ^applicati on\/x-www- form-urlen coded\b/.t est(self.g etHeader(' content-ty pe'))) {
  1261         self .setHeader ('content- type', 'ap plication/ x-www-form -urlencode d')
  1262       }
  1263       self.b ody = (typ eof form = == 'string ')
  1264         ? se lf._qs.rfc 3986(form. toString(' utf8'))
  1265         : se lf._qs.str ingify(for m).toStrin g('utf8')
  1266       return  self
  1267     }
  1268     // creat e form-dat a object
  1269     self._fo rm = new F ormData()
  1270     self._fo rm.on('err or', funct ion(err) {
  1271       err.me ssage = 'f orm-data:  ' + err.me ssage
  1272       self.e mit('error ', err)
  1273       self.a bort()
  1274     })
  1275     return s elf._form
  1276   }
  1277   Request.pr ototype.mu ltipart =  function ( multipart)  {
  1278     var self  = this
  1279  
  1280     self._mu ltipart.on Request(mu ltipart)
  1281  
  1282     if (!sel f._multipa rt.chunked ) {
  1283       self.b ody = self ._multipar t.body
  1284     }
  1285  
  1286     return s elf
  1287   }
  1288   Request.pr ototype.js on = funct ion (val)  {
  1289     var self  = this
  1290  
  1291     if (!sel f.hasHeade r('accept' )) {
  1292       self.s etHeader(' accept', ' applicatio n/json')
  1293     }
  1294  
  1295     if (type of self.js onReplacer  === 'func tion') {
  1296       self._ jsonReplac er = self. jsonReplac er
  1297     }
  1298  
  1299     self._js on = true
  1300     if (type of val ===  'boolean' ) {
  1301       if (se lf.body != = undefine d) {
  1302         if ( !/^applica tion\/x-ww w-form-url encoded\b/ .test(self .getHeader ('content- type'))) {
  1303           se lf.body =  safeString ify(self.b ody, self. _jsonRepla cer)
  1304         } el se {
  1305           se lf.body =  self._qs.r fc3986(sel f.body)
  1306         }
  1307         if ( !self.hasH eader('con tent-type' )) {
  1308           se lf.setHead er('conten t-type', ' applicatio n/json')
  1309         }
  1310       }
  1311     } else {
  1312       self.b ody = safe Stringify( val, self. _jsonRepla cer)
  1313       if (!s elf.hasHea der('conte nt-type'))  {
  1314         self .setHeader ('content- type', 'ap plication/ json')
  1315       }
  1316     }
  1317  
  1318     if (type of self.js onReviver  === 'funct ion') {
  1319       self._ jsonRevive r = self.j sonReviver
  1320     }
  1321  
  1322     return s elf
  1323   }
  1324   Request.pr ototype.ge tHeader =  function ( name, head ers) {
  1325     var self  = this
  1326     var resu lt, re, ma tch
  1327     if (!hea ders) {
  1328       header s = self.h eaders
  1329     }
  1330     Object.k eys(header s).forEach (function  (key) {
  1331       if (ke y.length ! == name.le ngth) {
  1332         retu rn
  1333       }
  1334       re = n ew RegExp( name, 'i')
  1335       match  = key.matc h(re)
  1336       if (ma tch) {
  1337         resu lt = heade rs[key]
  1338       }
  1339     })
  1340     return r esult
  1341   }
  1342   Request.pr ototype.en ableUnixSo cket = fun ction () {
  1343     // Get t he socket  & request  paths from  the URL
  1344     var unix Parts = th is.uri.pat h.split(': ')
  1345       , host  = unixPar ts[0]
  1346       , path  = unixPar ts[1]
  1347     // Apply  unix prop erties to  request
  1348     this.soc ketPath =  host
  1349     this.uri .pathname  = path
  1350     this.uri .path = pa th
  1351     this.uri .host = ho st
  1352     this.uri .hostname  = host
  1353     this.uri .isUnix =  true
  1354   }
  1355  
  1356  
  1357   Request.pr ototype.au th = funct ion (user,  pass, sen dImmediate ly, bearer ) {
  1358     var self  = this
  1359  
  1360     self._au th.onReque st(user, p ass, sendI mmediately , bearer)
  1361  
  1362     return s elf
  1363   }
  1364   Request.pr ototype.aw s = functi on (opts,  now) {
  1365     var self  = this
  1366  
  1367     if (!now ) {
  1368       self._ aws = opts
  1369       return  self
  1370     }
  1371  
  1372     if (opts .sign_vers ion == 4 | | opts.sig n_version  == '4') {
  1373       // use  aws4
  1374       var op tions = {
  1375         host : self.uri .host,
  1376         path : self.uri .path,
  1377         meth od: self.m ethod,
  1378         head ers: {
  1379           'c ontent-typ e': self.g etHeader(' content-ty pe') || ''
  1380         },
  1381         body : self.bod y
  1382       }
  1383       var si gnRes = aw s4.sign(op tions, {
  1384         acce ssKeyId: o pts.key,
  1385         secr etAccessKe y: opts.se cret,
  1386         sess ionToken:  opts.sessi on
  1387       })
  1388       self.s etHeader(' authorizat ion', sign Res.header s.Authoriz ation)
  1389       self.s etHeader(' x-amz-date ', signRes .headers[' X-Amz-Date '])
  1390       if (si gnRes.head ers['X-Amz -Security- Token']) {
  1391         self .setHeader ('x-amz-se curity-tok en', signR es.headers ['X-Amz-Se curity-Tok en'])
  1392       }
  1393     }
  1394     else {
  1395       // def ault: use  aws-sign2
  1396       var da te = new D ate()
  1397       self.s etHeader(' date', dat e.toUTCStr ing())
  1398       var au th =
  1399         { ke y: opts.ke y
  1400         , se cret: opts .secret
  1401         , ve rb: self.m ethod.toUp perCase()
  1402         , da te: date
  1403         , co ntentType:  self.getH eader('con tent-type' ) || ''
  1404         , md 5: self.ge tHeader('c ontent-md5 ') || ''
  1405         , am azonHeader s: aws2.ca nonicalize Headers(se lf.headers )
  1406         }
  1407       var pa th = self. uri.path
  1408       if (op ts.bucket  && path) {
  1409         auth .resource  = '/' + op ts.bucket  + path
  1410       } else  if (opts. bucket &&  !path) {
  1411         auth .resource  = '/' + op ts.bucket
  1412       } else  if (!opts .bucket &&  path) {
  1413         auth .resource  = path
  1414       } else  if (!opts .bucket &&  !path) {
  1415         auth .resource  = '/'
  1416       }
  1417       auth.r esource =  aws2.canon icalizeRes ource(auth .resource)
  1418       self.s etHeader(' authorizat ion', aws2 .authoriza tion(auth) )
  1419     }
  1420  
  1421     return s elf
  1422   }
  1423   Request.pr ototype.ht tpSignatur e = functi on (opts)  {
  1424     var self  = this
  1425     httpSign ature.sign Request({
  1426       getHea der: funct ion(header ) {
  1427         retu rn self.ge tHeader(he ader, self .headers)
  1428       },
  1429       setHea der: funct ion(header , value) {
  1430         self .setHeader (header, v alue)
  1431       },
  1432       method : self.met hod,
  1433       path:  self.path
  1434     }, opts)
  1435     debug('h ttpSignatu re authori zation', s elf.getHea der('autho rization') )
  1436  
  1437     return s elf
  1438   }
  1439   Request.pr ototype.ha wk = funct ion (opts)  {
  1440     var self  = this
  1441     self.set Header('Au thorizatio n', hawk.c lient.head er(self.ur i, self.me thod, opts ).field)
  1442   }
  1443   Request.pr ototype.oa uth = func tion (_oau th) {
  1444     var self  = this
  1445  
  1446     self._oa uth.onRequ est(_oauth )
  1447  
  1448     return s elf
  1449   }
  1450  
  1451   Request.pr ototype.ja r = functi on (jar) {
  1452     var self  = this
  1453     var cook ies
  1454  
  1455     if (self ._redirect .redirects Followed = == 0) {
  1456       self.o riginalCoo kieHeader  = self.get Header('co okie')
  1457     }
  1458  
  1459     if (!jar ) {
  1460       // dis able cooki es
  1461       cookie s = false
  1462       self._ disableCoo kies = tru e
  1463     } else {
  1464       var ta rgetCookie Jar = (jar  && jar.ge tCookieStr ing) ? jar  : globalC ookieJar
  1465       var ur ihref = se lf.uri.hre f
  1466       //fetc h cookie i n the Spec ified host
  1467       if (ta rgetCookie Jar) {
  1468         cook ies = targ etCookieJa r.getCooki eString(ur ihref)
  1469       }
  1470     }
  1471  
  1472     //if nee d cookie a nd cookie  is not emp ty
  1473     if (cook ies && coo kies.lengt h) {
  1474       if (se lf.origina lCookieHea der) {
  1475         // D on't overw rite exist ing Cookie  header
  1476         self .setHeader ('cookie',  self.orig inalCookie Header + ' ; ' + cook ies)
  1477       } else  {
  1478         self .setHeader ('cookie',  cookies)
  1479       }
  1480     }
  1481     self._ja r = jar
  1482     return s elf
  1483   }
  1484  
  1485  
  1486   // Stream  API
  1487   Request.pr ototype.pi pe = funct ion (dest,  opts) {
  1488     var self  = this
  1489  
  1490     if (self .response)  {
  1491       if (se lf._destda ta) {
  1492         self .emit('err or', new E rror('You  cannot pip e after da ta has bee n emitted  from the r esponse.') )
  1493       } else  if (self. _ended) {
  1494         self .emit('err or', new E rror('You  cannot pip e after th e response  has been  ended.'))
  1495       } else  {
  1496         stre am.Stream. prototype. pipe.call( self, dest , opts)
  1497         self .pipeDest( dest)
  1498         retu rn dest
  1499       }
  1500     } else {
  1501       self.d ests.push( dest)
  1502       stream .Stream.pr ototype.pi pe.call(se lf, dest,  opts)
  1503       return  dest
  1504     }
  1505   }
  1506   Request.pr ototype.wr ite = func tion () {
  1507     var self  = this
  1508     if (self ._aborted)  {return}
  1509  
  1510     if (!sel f._started ) {
  1511       self.s tart()
  1512     }
  1513     if (self .req) {
  1514       return  self.req. write.appl y(self.req , argument s)
  1515     }
  1516   }
  1517   Request.pr ototype.en d = functi on (chunk)  {
  1518     var self  = this
  1519     if (self ._aborted)  {return}
  1520  
  1521     if (chun k) {
  1522       self.w rite(chunk )
  1523     }
  1524     if (!sel f._started ) {
  1525       self.s tart()
  1526     }
  1527     if (self .req) {
  1528       self.r eq.end()
  1529     }
  1530   }
  1531   Request.pr ototype.pa use = func tion () {
  1532     var self  = this
  1533     if (!sel f.response Content) {
  1534       self._ paused = t rue
  1535     } else {
  1536       self.r esponseCon tent.pause .apply(sel f.response Content, a rguments)
  1537     }
  1538   }
  1539   Request.pr ototype.re sume = fun ction () {
  1540     var self  = this
  1541     if (!sel f.response Content) {
  1542       self._ paused = f alse
  1543     } else {
  1544       self.r esponseCon tent.resum e.apply(se lf.respons eContent,  arguments)
  1545     }
  1546   }
  1547   Request.pr ototype.de stroy = fu nction ()  {
  1548     var self  = this
  1549     if (!sel f._ended)  {
  1550       self.e nd()
  1551     } else i f (self.re sponse) {
  1552       self.r esponse.de stroy()
  1553     }
  1554   }
  1555  
  1556   Request.de faultProxy HeaderWhit eList =
  1557     Tunnel.d efaultProx yHeaderWhi teList.sli ce()
  1558  
  1559   Request.de faultProxy HeaderExcl usiveList  =
  1560     Tunnel.d efaultProx yHeaderExc lusiveList .slice()
  1561  
  1562   // Exports
  1563  
  1564   Request.pr ototype.to JSON = req uestToJSON
  1565   module.exp orts = Req uest