Skip to content

Latest commit

 

History

History
280 lines (242 loc) · 6.99 KB

File metadata and controls

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