Debian Codegraph @

reqwest.js

raw symbols SCIP
1 /*!
2 * Reqwest! A general purpose XHR connection manager
3 * license MIT (c) Dustin Diaz 2015
4 * https://github.com/ded/reqwest
5 */
6
7 !function (name, context, definition) {
8 if (typeof module != 'undefined' && module.exports) module.exports = definition()
9 else if (typeof define == 'function' && define.amd) define(definition)
10 else context[name] = definition()
11 }('reqwest', this, function () {
12
13 var context = this
14
15 if ('window' in context) {
16 var doc = document
17 , byTag = 'getElementsByTagName'
18 , head = doc[byTag]('head')[0]
19 } else {
20 var XHR2
21 try {
22 XHR2 = require('xhr2')
23 } catch (ex) {
24 throw new Error('Peer dependency `xhr2` required! Please npm install xhr2')
25 }
26 }
27
28
29 var httpsRe = /^http/
30 , protocolRe = /(^\w+):\/\//
31 , twoHundo = /^(20\d|1223)$/ //http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
32 , readyState = 'readyState'
33 , contentType = 'Content-Type'
34 , requestedWith = 'X-Requested-With'
35 , uniqid = 0
36 , callbackPrefix = 'reqwest_' + (+new Date())
37 , lastValue // data stored by the most recent JSONP callback
38 , xmlHttpRequest = 'XMLHttpRequest'
39 , xDomainRequest = 'XDomainRequest'
40 , noop = function () {}
41
42 , isArray = typeof Array.isArray == 'function'
43 ? Array.isArray
44 : function (a) {
45 return a instanceof Array
46 }
47
48 , defaultHeaders = {
49 'contentType': 'application/x-www-form-urlencoded'
50 , 'requestedWith': xmlHttpRequest
51 , 'accept': {
52 '*': 'text/javascript, text/html, application/xml, text/xml, */*'
53 , 'xml': 'application/xml, text/xml'
54 , 'html': 'text/html'
55 , 'text': 'text/plain'
56 , 'json': 'application/json, text/javascript'
57 , 'js': 'application/javascript, text/javascript'
58 }
59 }
60
61 , xhr = function(o) {
62 // is it x-domain
63 if (o['crossOrigin'] === true) {
64 var xhr = context[xmlHttpRequest] ? new XMLHttpRequest() : null
65 if (xhr && 'withCredentials' in xhr) {
66 return xhr
67 } else if (context[xDomainRequest]) {
68 return new XDomainRequest()
69 } else {
70 throw new Error('Browser does not support cross-origin requests')
71 }
72 } else if (context[xmlHttpRequest]) {
73 return new XMLHttpRequest()
74 } else if (XHR2) {
75 return new XHR2()
76 } else {
77 return new ActiveXObject('Microsoft.XMLHTTP')
78 }
79 }
80 , globalSetupOptions = {
81 dataFilter: function (data) {
82 return data
83 }
84 }
85
86 function succeed(r) {
87 var protocol = protocolRe.exec(r.url)
88 protocol = (protocol && protocol[1]) || context.location.protocol
89 return httpsRe.test(protocol) ? twoHundo.test(r.request.status) : !!r.request.response
90 }
91
92 function handleReadyState(r, success, error) {
93 return function () {
94 // use _aborted to mitigate against IE err c00c023f
95 // (can't read props on aborted request objects)
96 if (r._aborted) return error(r.request)
97 if (r._timedOut) return error(r.request, 'Request is aborted: timeout')
98 if (r.request && r.request[readyState] == 4) {
99 r.request.onreadystatechange = noop
100 if (succeed(r)) success(r.request)
101 else
102 error(r.request)
103 }
104 }
105 }
106
107 function setHeaders(http, o) {
108 var headers = o['headers'] || {}
109 , h
110
111 headers['Accept'] = headers['Accept']
112 || defaultHeaders['accept'][o['type']]
113 || defaultHeaders['accept']['*']
114
115 var isAFormData = typeof FormData !== 'undefined' && (o['data'] instanceof FormData);
116 // breaks cross-origin requests with legacy browsers
117 if (!o['crossOrigin'] && !headers[requestedWith]) headers[requestedWith] = defaultHeaders['requestedWith']
118 if (!headers[contentType] && !isAFormData) headers[contentType] = o['contentType'] || defaultHeaders['contentType']
119 for (h in headers)
120 headers.hasOwnProperty(h) && 'setRequestHeader' in http && http.setRequestHeader(h, headers[h])
121 }
122
123 function setCredentials(http, o) {
124 if (typeof o['withCredentials'] !== 'undefined' && typeof http.withCredentials !== 'undefined') {
125 http.withCredentials = !!o['withCredentials']
126 }
127 }
128
129 function generalCallback(data) {
130 lastValue = data
131 }
132
133 function urlappend (url, s) {
134 return url + (/\?/.test(url) ? '&' : '?') + s
135 }
136
137 function handleJsonp(o, fn, err, url) {
138 var reqId = uniqid++
139 , cbkey = o['jsonpCallback'] || 'callback' // the 'callback' key
140 , cbval = o['jsonpCallbackName'] || reqwest.getcallbackPrefix(reqId)
141 , cbreg = new RegExp('((^|\\?|&)' + cbkey + ')=([^&]+)')
142 , match = url.match(cbreg)
143 , script = doc.createElement('script')
144 , loaded = 0
145 , isIE10 = navigator.userAgent.indexOf('MSIE 10.0') !== -1
146
147 if (match) {
148 if (match[3] === '?') {
149 url = url.replace(cbreg, '$1=' + cbval) // wildcard callback func name
150 } else {
151 cbval = match[3] // provided callback func name
152 }
153 } else {
154 url = urlappend(url, cbkey + '=' + cbval) // no callback details, add 'em
155 }
156
157 context[cbval] = generalCallback
158
159 script.type = 'text/javascript'
160 script.src = url
161 script.async = true
162 if (typeof script.onreadystatechange !== 'undefined' && !isIE10) {
163 // need this for IE due to out-of-order onreadystatechange(), binding script
164 // execution to an event listener gives us control over when the script
165 // is executed. See http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
166 script.htmlFor = script.id = '_reqwest_' + reqId
167 }
168
169 script.onload = script.onreadystatechange = function () {
170 if ((script[readyState] && script[readyState] !== 'complete' && script[readyState] !== 'loaded') || loaded) {
171 return false
172 }
173 script.onload = script.onreadystatechange = null
174 script.onclick && script.onclick()
175 // Call the user callback with the last value stored and clean up values and scripts.
176 fn(lastValue)
177 lastValue = undefined
178 head.removeChild(script)
179 loaded = 1
180 }
181
182 // Add the script to the DOM head
183 head.appendChild(script)
184
185 // Enable JSONP timeout
186 return {
187 abort: function () {
188 script.onload = script.onreadystatechange = null
189 err({}, 'Request is aborted: timeout', {})
190 lastValue = undefined
191 head.removeChild(script)
192 loaded = 1
193 }
194 }
195 }
196
197 function getRequest(fn, err) {
198 var o = this.o
199 , method = (o['method'] || 'GET').toUpperCase()
200 , url = typeof o === 'string' ? o : o['url']
201 // convert non-string objects to query-string form unless o['processData'] is false
202 , data = (o['processData'] !== false && o['data'] && typeof o['data'] !== 'string')
203 ? reqwest.toQueryString(o['data'])
204 : (o['data'] || null)
205 , http
206 , sendWait = false
207
208 // if we're working on a GET request and we have data then we should append
209 // query string to end of URL and not post data
210 if ((o['type'] == 'jsonp' || method == 'GET') && data) {
211 url = urlappend(url, data)
212 data = null
213 }
214
215 if (o['type'] == 'jsonp') return handleJsonp(o, fn, err, url)
216
217 // get the xhr from the factory if passed
218 // if the factory returns null, fall-back to ours
219 http = (o.xhr && o.xhr(o)) || xhr(o)
220
221 http.open(method, url, o['async'] === false ? false : true)
222 setHeaders(http, o)
223 setCredentials(http, o)
224 if (context[xDomainRequest] && http instanceof context[xDomainRequest]) {
225 http.onload = fn
226 http.onerror = err
227 // NOTE: see
228 // http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/30ef3add-767c-4436-b8a9-f1ca19b4812e
229 http.onprogress = function() {}
230 sendWait = true
231 } else {
232 http.onreadystatechange = handleReadyState(this, fn, err)
233 }
234 o['before'] && o['before'](http)
235 if (sendWait) {
236 setTimeout(function () {
237 http.send(data)
238 }, 200)
239 } else {
240 http.send(data)
241 }
242 return http
243 }
244
245 function Reqwest(o, fn) {
246 this.o = o
247 this.fn = fn
248
249 init.apply(this, arguments)
250 }
251
252 function setType(header) {
253 // json, javascript, text/plain, text/html, xml
254 if (header === null) return undefined; //In case of no content-type.
255 if (header.match('json')) return 'json'
256 if (header.match('javascript')) return 'js'
257 if (header.match('text')) return 'html'
258 if (header.match('xml')) return 'xml'
259 }
260
261 function init(o, fn) {
262
263 this.url = typeof o == 'string' ? o : o['url']
264 this.timeout = null
265
266 // whether request has been fulfilled for purpose
267 // of tracking the Promises
268 this._fulfilled = false
269 // success handlers
270 this._successHandler = function(){}
271 this._fulfillmentHandlers = []
272 // error handlers
273 this._errorHandlers = []
274 // complete (both success and fail) handlers
275 this._completeHandlers = []
276 this._erred = false
277 this._responseArgs = {}
278
279 var self = this
280
281 fn = fn || function () {}
282
283 if (o['timeout']) {
284 this.timeout = setTimeout(function () {
285 timedOut()
286 }, o['timeout'])
287 }
288
289 if (o['success']) {
290 this._successHandler = function () {
291 o['success'].apply(o, arguments)
292 }
293 }
294
295 if (o['error']) {
296 this._errorHandlers.push(function () {
297 o['error'].apply(o, arguments)
298 })
299 }
300
301 if (o['complete']) {
302 this._completeHandlers.push(function () {
303 o['complete'].apply(o, arguments)
304 })
305 }
306
307 function complete (resp) {
308 o['timeout'] && clearTimeout(self.timeout)
309 self.timeout = null
310 while (self._completeHandlers.length > 0) {
311 self._completeHandlers.shift()(resp)
312 }
313 }
314
315 function success (resp) {
316 var type = o['type'] || resp && setType(resp.getResponseHeader('Content-Type')) // resp can be undefined in IE
317 resp = (type !== 'jsonp') ? self.request : resp
318 // use global data filter on response text
319 var filteredResponse = globalSetupOptions.dataFilter(resp.responseText, type)
320 , r = filteredResponse
321 try {
322 resp.responseText = r
323 } catch (e) {
324 // can't assign this in IE<=8, just ignore
325 }
326 if (r) {
327 switch (type) {
328 case 'json':
329 try {
330 resp = context.JSON ? context.JSON.parse(r) : eval('(' + r + ')')
331 } catch (err) {
332 return error(resp, 'Could not parse JSON in response', err)
333 }
334 break
335 case 'js':
336 resp = eval(r)
337 break
338 case 'html':
339 resp = r
340 break
341 case 'xml':
342 resp = resp.responseXML
343 && resp.responseXML.parseError // IE trololo
344 && resp.responseXML.parseError.errorCode
345 && resp.responseXML.parseError.reason
346 ? null
347 : resp.responseXML
348 break
349 }
350 }
351
352 self._responseArgs.resp = resp
353 self._fulfilled = true
354 fn(resp)
355 self._successHandler(resp)
356 while (self._fulfillmentHandlers.length > 0) {
357 resp = self._fulfillmentHandlers.shift()(resp)
358 }
359
360 complete(resp)
361 }
362
363 function timedOut() {
364 self._timedOut = true
365 self.request.abort()
366 }
367
368 function error(resp, msg, t) {
369 resp = self.request
370 self._responseArgs.resp = resp
371 self._responseArgs.msg = msg
372 self._responseArgs.t = t
373 self._erred = true
374 while (self._errorHandlers.length > 0) {
375 self._errorHandlers.shift()(resp, msg, t)
376 }
377 complete(resp)
378 }
379
380 this.request = getRequest.call(this, success, error)
381 }
382
383 Reqwest.prototype = {
384 abort: function () {
385 this._aborted = true
386 this.request.abort()
387 }
388
389 , retry: function () {
390 init.call(this, this.o, this.fn)
391 }
392
393 /**
394 * Small deviation from the Promises A CommonJs specification
395 * http://wiki.commonjs.org/wiki/Promises/A
396 */
397
398 /**
399 * `then` will execute upon successful requests
400 */
401 , then: function (success, fail) {
402 success = success || function () {}
403 fail = fail || function () {}
404 if (this._fulfilled) {
405 this._responseArgs.resp = success(this._responseArgs.resp)
406 } else if (this._erred) {
407 fail(this._responseArgs.resp, this._responseArgs.msg, this._responseArgs.t)
408 } else {
409 this._fulfillmentHandlers.push(success)
410 this._errorHandlers.push(fail)
411 }
412 return this
413 }
414
415 /**
416 * `always` will execute whether the request succeeds or fails
417 */
418 , always: function (fn) {
419 if (this._fulfilled || this._erred) {
420 fn(this._responseArgs.resp)
421 } else {
422 this._completeHandlers.push(fn)
423 }
424 return this
425 }
426
427 /**
428 * `fail` will execute when the request fails
429 */
430 , fail: function (fn) {
431 if (this._erred) {
432 fn(this._responseArgs.resp, this._responseArgs.msg, this._responseArgs.t)
433 } else {
434 this._errorHandlers.push(fn)
435 }
436 return this
437 }
438 , 'catch': function (fn) {
439 return this.fail(fn)
440 }
441 }
442
443 function reqwest(o, fn) {
444 return new Reqwest(o, fn)
445 }
446
447 // normalize newline variants according to spec -> CRLF
448 function normalize(s) {
449 return s ? s.replace(/\r?\n/g, '\r\n') : ''
450 }
451
452 function serial(el, cb) {
453 var n = el.name
454 , t = el.tagName.toLowerCase()
455 , optCb = function (o) {
456 // IE gives value="" even where there is no value attribute
457 // 'specified' ref: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-862529273
458 if (o && !o['disabled'])
459 cb(n, normalize(o['attributes']['value'] && o['attributes']['value']['specified'] ? o['value'] : o['text']))
460 }
461 , ch, ra, val, i
462
463 // don't serialize elements that are disabled or without a name
464 if (el.disabled || !n) return
465
466 switch (t) {
467 case 'input':
468 if (!/reset|button|image|file/i.test(el.type)) {
469 ch = /checkbox/i.test(el.type)
470 ra = /radio/i.test(el.type)
471 val = el.value
472 // WebKit gives us "" instead of "on" if a checkbox has no value, so correct it here
473 ;(!(ch || ra) || el.checked) && cb(n, normalize(ch && val === '' ? 'on' : val))
474 }
475 break
476 case 'textarea':
477 cb(n, normalize(el.value))
478 break
479 case 'select':
480 if (el.type.toLowerCase() === 'select-one') {
481 optCb(el.selectedIndex >= 0 ? el.options[el.selectedIndex] : null)
482 } else {
483 for (i = 0; el.length && i < el.length; i++) {
484 el.options[i].selected && optCb(el.options[i])
485 }
486 }
487 break
488 }
489 }
490
491 // collect up all form elements found from the passed argument elements all
492 // the way down to child elements; pass a '<form>' or form fields.
493 // called with 'this'=callback to use for serial() on each element
494 function eachFormElement() {
495 var cb = this
496 , e, i
497 , serializeSubtags = function (e, tags) {
498 var i, j, fa
499 for (i = 0; i < tags.length; i++) {
500 fa = e[byTag](tags[i])
501 for (j = 0; j < fa.length; j++) serial(fa[j], cb)
502 }
503 }
504
505 for (i = 0; i < arguments.length; i++) {
506 e = arguments[i]
507 if (/input|select|textarea/i.test(e.tagName)) serial(e, cb)
508 serializeSubtags(e, [ 'input', 'select', 'textarea' ])
509 }
510 }
511
512 // standard query string style serialization
513 function serializeQueryString() {
514 return reqwest.toQueryString(reqwest.serializeArray.apply(null, arguments))
515 }
516
517 // { 'name': 'value', ... } style serialization
518 function serializeHash() {
519 var hash = {}
520 eachFormElement.apply(function (name, value) {
521 if (name in hash) {
522 hash[name] && !isArray(hash[name]) && (hash[name] = [hash[name]])
523 hash[name].push(value)
524 } else hash[name] = value
525 }, arguments)
526 return hash
527 }
528
529 // [ { name: 'name', value: 'value' }, ... ] style serialization
530 reqwest.serializeArray = function () {
531 var arr = []
532 eachFormElement.apply(function (name, value) {
533 arr.push({name: name, value: value})
534 }, arguments)
535 return arr
536 }
537
538 reqwest.serialize = function () {
539 if (arguments.length === 0) return ''
540 var opt, fn
541 , args = Array.prototype.slice.call(arguments, 0)
542
543 opt = args.pop()
544 opt && opt.nodeType && args.push(opt) && (opt = null)
545 opt && (opt = opt.type)
546
547 if (opt == 'map') fn = serializeHash
548 else if (opt == 'array') fn = reqwest.serializeArray
549 else fn = serializeQueryString
550
551 return fn.apply(null, args)
552 }
553
554 reqwest.toQueryString = function (o, trad) {
555 var prefix, i
556 , traditional = trad || false
557 , s = []
558 , enc = encodeURIComponent
559 , add = function (key, value) {
560 // If value is a function, invoke it and return its value
561 value = ('function' === typeof value) ? value() : (value == null ? '' : value)
562 s[s.length] = enc(key) + '=' + enc(value)
563 }
564 // If an array was passed in, assume that it is an array of form elements.
565 if (isArray(o)) {
566 for (i = 0; o && i < o.length; i++) add(o[i]['name'], o[i]['value'])
567 } else {
568 // If traditional, encode the "old" way (the way 1.3.2 or older
569 // did it), otherwise encode params recursively.
570 for (prefix in o) {
571 if (o.hasOwnProperty(prefix)) buildParams(prefix, o[prefix], traditional, add)
572 }
573 }
574
575 // spaces should be + according to spec
576 return s.join('&').replace(/%20/g, '+')
577 }
578
579 function buildParams(prefix, obj, traditional, add) {
580 var name, i, v
581 , rbracket = /\[\]$/
582
583 if (isArray(obj)) {
584 // Serialize array item.
585 for (i = 0; obj && i < obj.length; i++) {
586 v = obj[i]
587 if (traditional || rbracket.test(prefix)) {
588 // Treat each array item as a scalar.
589 add(prefix, v)
590 } else {
591 buildParams(prefix + '[' + (typeof v === 'object' ? i : '') + ']', v, traditional, add)
592 }
593 }
594 } else if (obj && obj.toString() === '[object Object]') {
595 // Serialize object item.
596 for (name in obj) {
597 buildParams(prefix + '[' + name + ']', obj[name], traditional, add)
598 }
599
600 } else {
601 // Serialize scalar item.
602 add(prefix, obj)
603 }
604 }
605
606 reqwest.getcallbackPrefix = function () {
607 return callbackPrefix
608 }
609
610 // jQuery and Zepto compatibility, differences can be remapped here so you can call
611 // .ajax.compat(options, callback)
612 reqwest.compat = function (o, fn) {
613 if (o) {
614 o['type'] && (o['method'] = o['type']) && delete o['type']
615 o['dataType'] && (o['type'] = o['dataType'])
616 o['jsonpCallback'] && (o['jsonpCallbackName'] = o['jsonpCallback']) && delete o['jsonpCallback']
617 o['jsonp'] && (o['jsonpCallback'] = o['jsonp'])
618 }
619 return new Reqwest(o, fn)
620 }
621
622 reqwest.ajaxSetup = function (options) {
623 options = options || {}
624 for (var k in options) {
625 globalSetupOptions[k] = options[k]
626 }
627 }
628
629 return reqwest
630 });