Skip to content

Latest commit

 

History

History
294 lines (254 loc) · 7.43 KB

File metadata and controls

294 lines (254 loc) · 7.43 KB
 
Jun 24, 2015
Jun 24, 2015
1
var capability = require('./capability')
Jul 13, 2015
Jul 13, 2015
2
var inherits = require('inherits')
Jun 24, 2015
Jun 24, 2015
3
var response = require('./response')
Apr 27, 2016
Apr 27, 2016
4
var stream = require('readable-stream')
Jan 13, 2016
Jan 13, 2016
5
var toArrayBuffer = require('to-arraybuffer')
Jun 24, 2015
Jun 24, 2015
6
7
var IncomingMessage = response.IncomingMessage
8
var rStates = response.readyStates
9
Sep 1, 2016
Sep 1, 2016
10
function decideMode (preferBinary, useFetch) {
11
if (capability.fetch && useFetch) {
Jul 2, 2015
Jul 2, 2015
12
return 'fetch'
13
} else if (capability.mozchunkedarraybuffer) {
14
return 'moz-chunked-arraybuffer'
15
} else if (capability.msstream) {
16
return 'ms-stream'
17
} else if (capability.arraybuffer && preferBinary) {
18
return 'arraybuffer'
Jul 3, 2015
Jul 3, 2015
19
} else if (capability.vbArray && preferBinary) {
20
return 'text:vbarray'
Jul 2, 2015
Jul 2, 2015
21
} else {
22
return 'text'
23
}
24
}
25
Jun 24, 2015
Jun 24, 2015
26
var ClientRequest = module.exports = function (opts) {
27
var self = this
28
stream.Writable.call(self)
29
30
self._opts = opts
31
self._body = []
Jul 7, 2015
Jul 7, 2015
32
self._headers = {}
Jul 7, 2015
Jul 7, 2015
33
if (opts.auth)
34
self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
Sep 15, 2015
Sep 15, 2015
35
Object.keys(opts.headers).forEach(function (name) {
Jun 24, 2015
Jun 24, 2015
36
self.setHeader(name, opts.headers[name])
37
})
38
Jul 2, 2015
Jul 2, 2015
39
var preferBinary
Sep 1, 2016
Sep 1, 2016
40
var useFetch = true
Oct 18, 2016
Oct 18, 2016
41
if (opts.mode === 'disable-fetch' || 'timeout' in opts) {
42
// If the use of XHR should be preferred and includes preserving the 'content-type' header.
43
// Force XHR to be used since the Fetch API does not yet support timeouts.
Sep 1, 2016
Sep 1, 2016
44
useFetch = false
45
preferBinary = true
46
} else if (opts.mode === 'prefer-streaming') {
Aug 20, 2015
Aug 20, 2015
47
// If streaming is a high priority but binary compatibility and
48
// the accuracy of the 'content-type' header aren't
Jul 2, 2015
Jul 2, 2015
49
preferBinary = false
Aug 20, 2015
Aug 20, 2015
50
} else if (opts.mode === 'allow-wrong-content-type') {
51
// If streaming is more important than preserving the 'content-type' header
Jul 2, 2015
Jul 2, 2015
52
preferBinary = !capability.overrideMimeType
Aug 20, 2015
Aug 20, 2015
53
} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
54
// Use binary if text streaming may corrupt data or the content-type header, or for speed
55
preferBinary = true
Jul 2, 2015
Jul 2, 2015
56
} else {
57
throw new Error('Invalid value for opts.mode')
58
}
Sep 1, 2016
Sep 1, 2016
59
self._mode = decideMode(preferBinary, useFetch)
Jun 24, 2015
Jun 24, 2015
60
Jul 2, 2015
Jul 2, 2015
61
self.on('finish', function () {
62
self._onFinish()
63
})
Jun 24, 2015
Jun 24, 2015
64
}
65
Jul 3, 2015
Jul 3, 2015
66
inherits(ClientRequest, stream.Writable)
Jun 24, 2015
Jun 24, 2015
67
68
ClientRequest.prototype.setHeader = function (name, value) {
69
var self = this
Jul 13, 2015
Jul 13, 2015
70
var lowerName = name.toLowerCase()
71
// This check is not necessary, but it prevents warnings from browsers about setting unsafe
72
// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
73
// http-browserify did it, so I will too.
Sep 15, 2015
Sep 15, 2015
74
if (unsafeHeaders.indexOf(lowerName) !== -1)
Jul 13, 2015
Jul 13, 2015
75
return
76
77
self._headers[lowerName] = {
Jul 7, 2015
Jul 7, 2015
78
name: name,
79
value: value
80
}
Jun 24, 2015
Jun 24, 2015
81
}
82
83
ClientRequest.prototype.getHeader = function (name) {
84
var self = this
Jul 7, 2015
Jul 7, 2015
85
return self._headers[name.toLowerCase()].value
Jun 24, 2015
Jun 24, 2015
86
}
87
88
ClientRequest.prototype.removeHeader = function (name) {
89
var self = this
Jul 7, 2015
Jul 7, 2015
90
delete self._headers[name.toLowerCase()]
Jun 24, 2015
Jun 24, 2015
91
}
92
93
ClientRequest.prototype._onFinish = function () {
94
var self = this
95
Jul 13, 2015
Jul 13, 2015
96
if (self._destroyed)
97
return
Jun 24, 2015
Jun 24, 2015
98
var opts = self._opts
99
Jul 7, 2015
Jul 7, 2015
100
var headersObj = self._headers
Jan 16, 2017
Jan 16, 2017
101
var body = null
Nov 4, 2016
Nov 4, 2016
102
if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH' || opts.method === 'MERGE') {
Jul 7, 2015
Jul 7, 2015
103
if (capability.blobConstructor) {
Sep 15, 2015
Sep 15, 2015
104
body = new global.Blob(self._body.map(function (buffer) {
Jan 13, 2016
Jan 13, 2016
105
return toArrayBuffer(buffer)
Jul 8, 2015
Jul 8, 2015
106
}), {
107
type: (headersObj['content-type'] || {}).value || ''
108
})
Jul 1, 2015
Jul 1, 2015
109
} else {
110
// get utf8 string
111
body = Buffer.concat(self._body).toString()
112
}
Jun 24, 2015
Jun 24, 2015
113
}
114
115
if (self._mode === 'fetch') {
Sep 15, 2015
Sep 15, 2015
116
var headers = Object.keys(headersObj).map(function (name) {
Jul 7, 2015
Jul 7, 2015
117
return [headersObj[name].name, headersObj[name].value]
Jun 24, 2015
Jun 24, 2015
118
})
119
Sep 15, 2015
Sep 15, 2015
120
global.fetch(self._opts.url, {
Jun 24, 2015
Jun 24, 2015
121
method: self._opts.method,
Jan 18, 2017
Jan 18, 2017
122
headers: headers,
Jan 18, 2017
Jan 18, 2017
123
body: body || undefined,
Jun 24, 2015
Jun 24, 2015
124
mode: 'cors',
Jul 20, 2015
Jul 20, 2015
125
credentials: opts.withCredentials ? 'include' : 'same-origin'
Jun 24, 2015
Jun 24, 2015
126
}).then(function (response) {
127
self._fetchResponse = response
128
self._connect()
Oct 2, 2015
Oct 2, 2015
129
}, function (reason) {
Jul 8, 2015
Jul 8, 2015
130
self.emit('error', reason)
Jun 24, 2015
Jun 24, 2015
131
})
132
} else {
Sep 15, 2015
Sep 15, 2015
133
var xhr = self._xhr = new global.XMLHttpRequest()
Jul 8, 2015
Jul 8, 2015
134
try {
Sep 12, 2015
Sep 12, 2015
135
xhr.open(self._opts.method, self._opts.url, true)
Jul 8, 2015
Jul 8, 2015
136
} catch (err) {
137
process.nextTick(function () {
138
self.emit('error', err)
139
})
140
return
141
}
Jun 24, 2015
Jun 24, 2015
142
143
// Can't set responseType on really old browsers
144
if ('responseType' in xhr)
Jul 3, 2015
Jul 3, 2015
145
xhr.responseType = self._mode.split(':')[0]
Jun 24, 2015
Jun 24, 2015
146
147
if ('withCredentials' in xhr)
Jul 7, 2015
Jul 7, 2015
148
xhr.withCredentials = !!opts.withCredentials
Jun 24, 2015
Jun 24, 2015
149
150
if (self._mode === 'text' && 'overrideMimeType' in xhr)
151
xhr.overrideMimeType('text/plain; charset=x-user-defined')
152
Oct 18, 2016
Oct 18, 2016
153
if ('timeout' in opts) {
154
xhr.timeout = opts.timeout
155
xhr.ontimeout = function () {
156
self.emit('timeout')
157
}
158
}
159
Sep 15, 2015
Sep 15, 2015
160
Object.keys(headersObj).forEach(function (name) {
Jul 7, 2015
Jul 7, 2015
161
xhr.setRequestHeader(headersObj[name].name, headersObj[name].value)
Jun 24, 2015
Jun 24, 2015
162
})
163
Jul 3, 2015
Jul 3, 2015
164
self._response = null
Jun 24, 2015
Jun 24, 2015
165
xhr.onreadystatechange = function () {
166
switch (xhr.readyState) {
167
case rStates.LOADING:
168
case rStates.DONE:
Jul 8, 2015
Jul 8, 2015
169
self._onXHRProgress()
Jun 24, 2015
Jun 24, 2015
170
break
171
}
172
}
Jul 2, 2015
Jul 2, 2015
173
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
174
// in onprogress, not in onreadystatechange with xhr.readyState = 3
175
if (self._mode === 'moz-chunked-arraybuffer') {
176
xhr.onprogress = function () {
Jul 8, 2015
Jul 8, 2015
177
self._onXHRProgress()
Jul 2, 2015
Jul 2, 2015
178
}
179
}
Jun 24, 2015
Jun 24, 2015
180
Jul 8, 2015
Jul 8, 2015
181
xhr.onerror = function () {
Jul 13, 2015
Jul 13, 2015
182
if (self._destroyed)
183
return
Jul 8, 2015
Jul 8, 2015
184
self.emit('error', new Error('XHR error'))
185
}
186
187
try {
188
xhr.send(body)
189
} catch (err) {
190
process.nextTick(function () {
191
self.emit('error', err)
192
})
193
return
194
}
Jun 24, 2015
Jun 24, 2015
195
}
196
}
197
Jul 3, 2015
Jul 3, 2015
198
/**
Oct 13, 2015
Oct 13, 2015
199
* Checks if xhr.status is readable and non-zero, indicating no error.
200
* Even though the spec says it should be available in readyState 3,
201
* accessing it throws an exception in IE8
Jul 3, 2015
Jul 3, 2015
202
*/
203
function statusValid (xhr) {
204
try {
Oct 13, 2015
Oct 13, 2015
205
var status = xhr.status
206
return (status !== null && status !== 0)
Jul 3, 2015
Jul 3, 2015
207
} catch (e) {
208
return false
209
}
210
}
211
Jul 8, 2015
Jul 8, 2015
212
ClientRequest.prototype._onXHRProgress = function () {
213
var self = this
214
Jul 13, 2015
Jul 13, 2015
215
if (!statusValid(self._xhr) || self._destroyed)
Jul 8, 2015
Jul 8, 2015
216
return
217
218
if (!self._response)
219
self._connect()
220
221
self._response._onXHRProgress()
222
}
223
Jun 24, 2015
Jun 24, 2015
224
ClientRequest.prototype._connect = function () {
225
var self = this
226
Jul 13, 2015
Jul 13, 2015
227
if (self._destroyed)
228
return
229
Jun 24, 2015
Jun 24, 2015
230
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
Jan 4, 2017
Jan 4, 2017
231
self._response.on('error', function(err) {
232
self.emit('error', err)
233
})
234
Jun 24, 2015
Jun 24, 2015
235
self.emit('response', self._response)
236
}
237
238
ClientRequest.prototype._write = function (chunk, encoding, cb) {
239
var self = this
240
241
self._body.push(chunk)
242
cb()
243
}
244
Jul 13, 2015
Jul 13, 2015
245
ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
Jun 24, 2015
Jun 24, 2015
246
var self = this
Jul 13, 2015
Jul 13, 2015
247
self._destroyed = true
Jul 13, 2015
Jul 13, 2015
248
if (self._response)
249
self._response._destroyed = true
Jun 24, 2015
Jun 24, 2015
250
if (self._xhr)
251
self._xhr.abort()
Jul 13, 2015
Jul 13, 2015
252
// Currently, there isn't a way to truly abort a fetch.
253
// If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
Jun 24, 2015
Jun 24, 2015
254
}
255
256
ClientRequest.prototype.end = function (data, encoding, cb) {
257
var self = this
258
if (typeof data === 'function') {
259
cb = data
260
data = undefined
261
}
262
Aug 8, 2015
Aug 8, 2015
263
stream.Writable.prototype.end.call(self, data, encoding, cb)
Jun 24, 2015
Jun 24, 2015
264
}
265
266
ClientRequest.prototype.flushHeaders = function () {}
267
ClientRequest.prototype.setTimeout = function () {}
268
ClientRequest.prototype.setNoDelay = function () {}
269
ClientRequest.prototype.setSocketKeepAlive = function () {}
Jul 13, 2015
Jul 13, 2015
270
271
// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
272
var unsafeHeaders = [
273
'accept-charset',
274
'accept-encoding',
275
'access-control-request-headers',
276
'access-control-request-method',
277
'connection',
278
'content-length',
279
'cookie',
280
'cookie2',
281
'date',
282
'dnt',
283
'expect',
284
'host',
285
'keep-alive',
286
'origin',
287
'referer',
288
'te',
289
'trailer',
290
'transfer-encoding',
291
'upgrade',
292
'user-agent',
293
'via'
Jul 13, 2015
Jul 13, 2015
294
]