Skip to content

Latest commit

 

History

History
277 lines (239 loc) · 6.83 KB

File metadata and controls

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