Skip to content

Latest commit

 

History

History
306 lines (266 loc) · 7.59 KB

File metadata and controls

306 lines (266 loc) · 7.59 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) {
Apr 26, 2017
Apr 26, 2017
84
var header = this._headers[name.toLowerCase()]
85
if (header)
86
return header.value
87
return null
Jun 24, 2015
Jun 24, 2015
88
}
89
90
ClientRequest.prototype.removeHeader = function (name) {
91
var self = this
Jul 7, 2015
Jul 7, 2015
92
delete self._headers[name.toLowerCase()]
Jun 24, 2015
Jun 24, 2015
93
}
94
95
ClientRequest.prototype._onFinish = function () {
96
var self = this
97
Jul 13, 2015
Jul 13, 2015
98
if (self._destroyed)
99
return
Jun 24, 2015
Jun 24, 2015
100
var opts = self._opts
101
Jul 7, 2015
Jul 7, 2015
102
var headersObj = self._headers
Jan 16, 2017
Jan 16, 2017
103
var body = null
Apr 4, 2017
Apr 4, 2017
104
if (opts.method !== 'GET' && opts.method !== 'HEAD') {
Jul 7, 2015
Jul 7, 2015
105
if (capability.blobConstructor) {
Sep 15, 2015
Sep 15, 2015
106
body = new global.Blob(self._body.map(function (buffer) {
Jan 13, 2016
Jan 13, 2016
107
return toArrayBuffer(buffer)
Jul 8, 2015
Jul 8, 2015
108
}), {
109
type: (headersObj['content-type'] || {}).value || ''
110
})
Jul 1, 2015
Jul 1, 2015
111
} else {
112
// get utf8 string
113
body = Buffer.concat(self._body).toString()
114
}
Jun 24, 2015
Jun 24, 2015
115
}
116
Apr 4, 2017
Apr 4, 2017
117
// create flattened list of headers
118
var headersList = []
119
Object.keys(headersObj).forEach(function (keyName) {
120
var name = headersObj[keyName].name
121
var value = headersObj[keyName].value
122
if (Array.isArray(value)) {
123
value.forEach(function (v) {
124
headersList.push([name, v])
125
})
126
} else {
127
headersList.push([name, value])
128
}
129
})
Jun 24, 2015
Jun 24, 2015
130
Apr 4, 2017
Apr 4, 2017
131
if (self._mode === 'fetch') {
Sep 15, 2015
Sep 15, 2015
132
global.fetch(self._opts.url, {
Jun 24, 2015
Jun 24, 2015
133
method: self._opts.method,
Apr 4, 2017
Apr 4, 2017
134
headers: headersList,
Jan 18, 2017
Jan 18, 2017
135
body: body || undefined,
Jun 24, 2015
Jun 24, 2015
136
mode: 'cors',
Jul 20, 2015
Jul 20, 2015
137
credentials: opts.withCredentials ? 'include' : 'same-origin'
Jun 24, 2015
Jun 24, 2015
138
}).then(function (response) {
139
self._fetchResponse = response
140
self._connect()
Oct 2, 2015
Oct 2, 2015
141
}, function (reason) {
Jul 8, 2015
Jul 8, 2015
142
self.emit('error', reason)
Jun 24, 2015
Jun 24, 2015
143
})
144
} else {
Sep 15, 2015
Sep 15, 2015
145
var xhr = self._xhr = new global.XMLHttpRequest()
Jul 8, 2015
Jul 8, 2015
146
try {
Sep 12, 2015
Sep 12, 2015
147
xhr.open(self._opts.method, self._opts.url, true)
Jul 8, 2015
Jul 8, 2015
148
} catch (err) {
149
process.nextTick(function () {
150
self.emit('error', err)
151
})
152
return
153
}
Jun 24, 2015
Jun 24, 2015
154
155
// Can't set responseType on really old browsers
156
if ('responseType' in xhr)
Jul 3, 2015
Jul 3, 2015
157
xhr.responseType = self._mode.split(':')[0]
Jun 24, 2015
Jun 24, 2015
158
159
if ('withCredentials' in xhr)
Jul 7, 2015
Jul 7, 2015
160
xhr.withCredentials = !!opts.withCredentials
Jun 24, 2015
Jun 24, 2015
161
162
if (self._mode === 'text' && 'overrideMimeType' in xhr)
163
xhr.overrideMimeType('text/plain; charset=x-user-defined')
164
Oct 18, 2016
Oct 18, 2016
165
if ('timeout' in opts) {
166
xhr.timeout = opts.timeout
167
xhr.ontimeout = function () {
168
self.emit('timeout')
169
}
170
}
171
Apr 4, 2017
Apr 4, 2017
172
headersList.forEach(function (header) {
173
xhr.setRequestHeader(header[0], header[1])
Jun 24, 2015
Jun 24, 2015
174
})
175
Jul 3, 2015
Jul 3, 2015
176
self._response = null
Jun 24, 2015
Jun 24, 2015
177
xhr.onreadystatechange = function () {
178
switch (xhr.readyState) {
179
case rStates.LOADING:
180
case rStates.DONE:
Jul 8, 2015
Jul 8, 2015
181
self._onXHRProgress()
Jun 24, 2015
Jun 24, 2015
182
break
183
}
184
}
Jul 2, 2015
Jul 2, 2015
185
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
186
// in onprogress, not in onreadystatechange with xhr.readyState = 3
187
if (self._mode === 'moz-chunked-arraybuffer') {
188
xhr.onprogress = function () {
Jul 8, 2015
Jul 8, 2015
189
self._onXHRProgress()
Jul 2, 2015
Jul 2, 2015
190
}
191
}
Jun 24, 2015
Jun 24, 2015
192
Jul 8, 2015
Jul 8, 2015
193
xhr.onerror = function () {
Jul 13, 2015
Jul 13, 2015
194
if (self._destroyed)
195
return
Jul 8, 2015
Jul 8, 2015
196
self.emit('error', new Error('XHR error'))
197
}
198
199
try {
200
xhr.send(body)
201
} catch (err) {
202
process.nextTick(function () {
203
self.emit('error', err)
204
})
205
return
206
}
Jun 24, 2015
Jun 24, 2015
207
}
208
}
209
Jul 3, 2015
Jul 3, 2015
210
/**
Oct 13, 2015
Oct 13, 2015
211
* Checks if xhr.status is readable and non-zero, indicating no error.
212
* Even though the spec says it should be available in readyState 3,
213
* accessing it throws an exception in IE8
Jul 3, 2015
Jul 3, 2015
214
*/
215
function statusValid (xhr) {
216
try {
Oct 13, 2015
Oct 13, 2015
217
var status = xhr.status
218
return (status !== null && status !== 0)
Jul 3, 2015
Jul 3, 2015
219
} catch (e) {
220
return false
221
}
222
}
223
Jul 8, 2015
Jul 8, 2015
224
ClientRequest.prototype._onXHRProgress = function () {
225
var self = this
226
Jul 13, 2015
Jul 13, 2015
227
if (!statusValid(self._xhr) || self._destroyed)
Jul 8, 2015
Jul 8, 2015
228
return
229
230
if (!self._response)
231
self._connect()
232
233
self._response._onXHRProgress()
234
}
235
Jun 24, 2015
Jun 24, 2015
236
ClientRequest.prototype._connect = function () {
237
var self = this
238
Jul 13, 2015
Jul 13, 2015
239
if (self._destroyed)
240
return
241
Jun 24, 2015
Jun 24, 2015
242
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
Jan 4, 2017
Jan 4, 2017
243
self._response.on('error', function(err) {
244
self.emit('error', err)
245
})
246
Jun 24, 2015
Jun 24, 2015
247
self.emit('response', self._response)
248
}
249
250
ClientRequest.prototype._write = function (chunk, encoding, cb) {
251
var self = this
252
253
self._body.push(chunk)
254
cb()
255
}
256
Jul 13, 2015
Jul 13, 2015
257
ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
Jun 24, 2015
Jun 24, 2015
258
var self = this
Jul 13, 2015
Jul 13, 2015
259
self._destroyed = true
Jul 13, 2015
Jul 13, 2015
260
if (self._response)
261
self._response._destroyed = true
Jun 24, 2015
Jun 24, 2015
262
if (self._xhr)
263
self._xhr.abort()
Jul 13, 2015
Jul 13, 2015
264
// Currently, there isn't a way to truly abort a fetch.
265
// If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
Jun 24, 2015
Jun 24, 2015
266
}
267
268
ClientRequest.prototype.end = function (data, encoding, cb) {
269
var self = this
270
if (typeof data === 'function') {
271
cb = data
272
data = undefined
273
}
274
Aug 8, 2015
Aug 8, 2015
275
stream.Writable.prototype.end.call(self, data, encoding, cb)
Jun 24, 2015
Jun 24, 2015
276
}
277
278
ClientRequest.prototype.flushHeaders = function () {}
279
ClientRequest.prototype.setTimeout = function () {}
280
ClientRequest.prototype.setNoDelay = function () {}
281
ClientRequest.prototype.setSocketKeepAlive = function () {}
Jul 13, 2015
Jul 13, 2015
282
283
// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
284
var unsafeHeaders = [
285
'accept-charset',
286
'accept-encoding',
287
'access-control-request-headers',
288
'access-control-request-method',
289
'connection',
290
'content-length',
291
'cookie',
292
'cookie2',
293
'date',
294
'dnt',
295
'expect',
296
'host',
297
'keep-alive',
298
'origin',
299
'referer',
300
'te',
301
'trailer',
302
'transfer-encoding',
303
'upgrade',
304
'user-agent',
305
'via'
Jul 13, 2015
Jul 13, 2015
306
]