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