Debian Codegraph @

src/reqwest.js

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