/*
XHR Request
adapted code from <https://github.com/xui/xui/blob/master/src/js/xhr.js>
@credits Brian LeRoux, Brock Whitten, Rob Ellis
558840
function xhr (url, options, callback) {
  if (typeof options === 'function') {
    callback = options
    options = null
  }
  const o = options || {}
  const req = new XMLHttpRequest()
  const method = o.method || 'get'
  const params = o.data || null

  req.queryString = params
  req.open(method, url, true)
  req.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

  if (method.toLowerCase() === 'post') {
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  }

  for (let key in o.headers) {
    if (o.headers.hasOwnProperty(key)) {
      req.setRequestHeader(key, o.headers[key])
    }
  }

  function stateChange () {
    if (req.readyState === 4) {
      if ((/^[20]/).test(req.status)) {
        callback(null, req.responseText)
      } else if ((/^[45]/).test(req.status)) {
        callback(new Error(req.status))
      }
    }
  }

  req.onreadystatechange = stateChange

  try {
    req.send(params)
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('Error: Resolving URL ' + url)
    callback(e)
  }
}
678211
function makeHttpRequest(next) {
  var start;
  var payload = '#\u00A0#';

  var httpReq = http.request({
    host: 'localhost',
    port: 1337,
    method: 'POST',
    path: '/upper'
  }, function(res) {
    res.setEncoding('utf8'); // VCR will ignore this
    var body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      var time = Date.now() - start;

      console.log('UNICODE');
      console.log('  status:', res.statusCode);
      console.log('  body  :', body);
      console.log('  time  :', time);

      common.verify(function() {
        body.should.eql(payload);
        common.shouldBeDynamicallyTimed(time);
      });

      console.log();

      next();
    });
  });

  start = Date.now();
  httpReq.end(payload);
}
336309
function load(url, successCallback, errorCallback) {
  const xhr = new XMLHttpRequest();

  // async, however scripts will be executed in the order they are in the
  // DOM to mirror normal script loading.
  xhr.open("GET", url, true);
  if ("overrideMimeType" in xhr) {
    xhr.overrideMimeType("text/plain");
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 0 || xhr.status === 200) {
        successCallback(xhr.responseText);
      } else {
        errorCallback();
        throw new Error("Could not load " + url);
      }
    }
  };
  return xhr.send(null);
}
790591
function (xhr) {
        this.xhr = xhr;
        this.status = xhr.status;
        this.$nativeResponseHeaders = xhr.getAllResponseHeaders();
        this.responses = {};

        var xml = xhr.responseXML;

        // Construct response list
        if (xml && xml.documentElement) {
            this.responses.xml = xml;
        }
        this.responses.text = xhr.responseText;

        try {
            this.statusText = xhr.statusText;
        } catch (e) {
            this.statusText = "";
        }
    }
7772
function XMLHttpRequest() {
  EventTarget.call(this, events);

  this.readyState;

  if (support.xhr.timeout) {
    this.timeout = 0;
  }

  if (support.xhr.cors) {
    this.withCredentials = false;
  }

  this.upload;
  this.responseType = '';
  this.responseText = '';
  this.responseXML = null;
  this.readyState = states.UNSENT;

  if (support.xhr.response) {
    this.response = '';
  }

  if (support.xhr.responseURL) {
    this.responseURL = '';
  }

  this.status = 0;
  this.statusText = '';
}
376116
function( url, cb ) {
		var xhr = new window.XMLHttpRequest();
		if ( "withCredentials" in xhr ) {
			xhr.open( "GET", url, true );
		} else if ( typeof window.XDomainRequest !== "undefined" ) { //IE
			xhr = new window.XDomainRequest();
			xhr.open( "GET", url );
		}
		if( cb ){
			xhr.onload = cb;
		}
		xhr.send();
		return xhr;
	}
930632
function xhrClient (request) {
    return new PromiseObj(function (resolve) {

        var xhr = new XMLHttpRequest(), handler = function (event) {

                var response = request.respondWith(
                'response' in xhr ? xhr.response : xhr.responseText, {
                    status: xhr.status === 1223 ? 204 : xhr.status, // IE9 status bug
                    statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText)
                });

                each(trim(xhr.getAllResponseHeaders()).split('\n'), function (row) {
                    response.headers.append(row.slice(0, row.indexOf(':')), row.slice(row.indexOf(':') + 1));
                });

                resolve(response);
            };

        request.abort = function () { return xhr.abort(); };

        xhr.open(request.method, request.getUrl(), true);

        if (request.timeout) {
            xhr.timeout = request.timeout;
        }

        if (request.responseType && 'responseType' in xhr) {
            xhr.responseType = request.responseType;
        }

        if (request.withCredentials || request.credentials) {
            xhr.withCredentials = true;
        }

        if (!request.crossOrigin) {
            request.headers.set('X-Requested-With', 'XMLHttpRequest');
        }

        // deprecated use downloadProgress
        if (isFunction(request.progress) && request.method === 'GET') {
            xhr.addEventListener('progress', request.progress);
        }

        if (isFunction(request.downloadProgress)) {
            xhr.addEventListener('progress', request.downloadProgress);
        }

        // deprecated use uploadProgress
        if (isFunction(request.progress) && /^(POST|PUT)$/i.test(request.method)) {
            xhr.upload.addEventListener('progress', request.progress);
        }

        if (isFunction(request.uploadProgress) && xhr.upload) {
            xhr.upload.addEventListener('progress', request.uploadProgress);
        }

        request.headers.forEach(function (value, name) {
            xhr.setRequestHeader(name, value);
        });

        xhr.onload = handler;
        xhr.onabort = handler;
        xhr.onerror = handler;
        xhr.ontimeout = handler;
        xhr.send(request.getBody());
    });
}
12926
function processResponse( xhr ){
    var responseText = xhr.responseText,
        status       = xhr.status,
        statusText,
        data;

    if ( !xhr ) {
        throw new Error( $.getString( "Errors.Security" ) );
    } else if ( xhr.status !== 200 && xhr.status !== 0 ) {
        status     = xhr.status;
        statusText = ( status == 404 ) ?
            "Not Found" :
            xhr.statusText;
        throw new Error( $.getString( "Errors.Status", status, statusText ) );
    }

    if( responseText.match(/\s*<.*/) ){
        try{
        data = ( xhr.responseXML && xhr.responseXML.documentElement ) ?
            xhr.responseXML :
            $.parseXml( responseText );
        } catch (e){
            data = xhr.responseText;
        }
    }else if( responseText.match(/\s*[\{\[].*/) ){
        try{
          data = $.parseJSON(responseText);
        } catch(e){
          data =  responseText;
        }
    }else{
        data = responseText;
    }
    return data;
}
1173769
function xhr(mockHandler, requestSettings, origSettings, origHandler) {
		// Extend with our default mockjax settings
		mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);

		if (typeof mockHandler.headers === 'undefined') {
			mockHandler.headers = {};
		}
		if (typeof requestSettings.headers === 'undefined') {
			requestSettings.headers = {};
		}
		if ( mockHandler.contentType ) {
			mockHandler.headers['content-type'] = mockHandler.contentType;
		}

		return {
			status: mockHandler.status,
			statusText: mockHandler.statusText,
			readyState: 1,
			open: function() { },
			send: function() {
				origHandler.fired = true;
				_xhrSend.call(this, mockHandler, requestSettings, origSettings);
			},
			abort: function() {
				clearTimeout(this.responseTimer);
			},
			setRequestHeader: function(header, value) {
				requestSettings.headers[header] = value;
			},
			getResponseHeader: function(header) {
				// 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
				if ( mockHandler.headers && mockHandler.headers[header] ) {
					// Return arbitrary headers
					return mockHandler.headers[header];
				} else if ( header.toLowerCase() == 'last-modified' ) {
					return mockHandler.lastModified || (new Date()).toString();
				} else if ( header.toLowerCase() == 'etag' ) {
					return mockHandler.etag || '';
				} else if ( header.toLowerCase() == 'content-type' ) {
					return mockHandler.contentType || 'text/plain';
				}
			},
			getAllResponseHeaders: function() {
				var headers = '';
				// since jQuery 1.9 responseText type has to match contentType
				if (mockHandler.contentType) {
					mockHandler.headers['Content-Type'] = mockHandler.contentType;
				}
				$.each(mockHandler.headers, function(k, v) {
					headers += k + ': ' + v + "\n";
				});
				return headers;
			}
		};
	}
267729
function(xhr){
			if (xhr && (xhr.readyState == 4)) {
				if (xmlloader.httpSuccess(xhr)) {
					processResponse(xhr);
				}
				else { //if it failed, it mighht be that the source has no CORS enabled. In such case, fallback to proxy before erroring
					if(usingCORS && xmlloader.proxyURL) { //if it failed when using CORS and we've got a proxy, try to get the data via the proxy
					  xhr=undefined;
					  usingCORS = false;
					  var new_xhr = xmlloader.xhr();
					  new_xhr.open('GET', xmlloader.proxyURL+'?url='+url, true);
					  new_xhr.onreadystatechange = function() {change(new_xhr);}
					  new_xhr.send(null);
					} else {
					  errorcallback && errorcallback({id: "xmlhttprequest_error", msg: xhr.status});
					}
				}
				//to prevent IE memory leaks
				xhr = undefined;
			} 
		}
1107742
function(async) {
  /**
   * Result: the function to get `Result` instance. The request result object.
   * - xhrObj: the xhr obj which can get the xhr result.
   *
   * How to use it? if `r` is the instance of `Result`.
   * var r_json = r.json();
   * var status = r.status_code;
   * var headers = r.headers;
  **/
  var Result = function(xhrObj) {
    var headers = {}, header;
    // code from https://github.com/developit/unfetch/blob/master/src/index.js
    xhrObj.getAllResponseHeaders().replace(/^(.*?):\s*([\s\S]*?)$/gm, function(m, key, value) {
      header = headers[key];
      headers[key] = header ? header + ',' + value : value;
    });
    return {
      status: xhrObj.status,
      statusText: xhrObj.statusText,
      url: xhrObj.responseURL,
      text: xhrObj.responseText,
      responseType: xhrObj.responseType,
      headers: headers,
      ok: function() { return (xhrObj.status/200|0) == 1; },    // 200-399
      json: function() { return JSON.parse(xhrObj.responseText); },
      xml: function() { return xhrObj.responseXML; },
      blob: function() { return new Blob([xhrObj.response]); }
    };
  },

  _method = '',
  _url = '',
  _headers = {},
  _body = '',
  _async = async !== false,
  _events = {},

  _xhr = new XMLHttpRequest(),

  _typeof = function(v) {
    if (v === null) return 'null';
    if (v !== Object(v)) return typeof v;
    return ({}).toString.call(v).slice(8, -1).toLowerCase();
  },
  /**
   * on: the function `on` to binding event.
   * - event: the event name. can be `ready`, `error`, `success`, `fail`.
   * - callback: when event trigger, do the callback.
   *
   * How to use it?
   * var XHRLib = require('xhr.js');
   * var xhr = XHRLib(); // all use default.
   * xhr.on('ready', function(r) {});
   * xhr.on('error', function(r) {});
   * xhr.on('success', function(r) {});
   * xhr.on('fail', function(r) {});
  **/
  on = function(event, callback) {
    if ('ready-success-fail'.split('-').indexOf(event) >= 0 && _typeof(callback) == 'function')
      _events[event] = callback;
  },
  __callback_func = function(t) {
    return _events[t] ? _events[t]: function() {};
  },
  // onreadystatechange callback function
  __on_request_callback = function() {
    if (_xhr.readyState === 4) {
      var result = Result(_xhr);
      // ready
      __callback_func('ready')(result, _this);
      // success
      if (_xhr.status === 200) __callback_func('success')(result, _this);
      // fail
      else __callback_func('fail')(result, _this);
    }
  },

  /**
   * setRequestHeader: set the request header.
   * - key: the header key.
   * - value: the header value.
   *
   * How to use it?
   * var xhr = new require('xhr.js')();
   *
   * xhr.setRequestHeader('Content-Type', 'application/json');
  **/
  setRequestHeader = function(key, value) {
    _headers[key] = value;
  },

  /**
   * setAsync: set the request async / sync.
   * - async: the default is async.
   *
   * How to use it?
   * var xhr = new require('xhr.js')();
   *
   * xhr.setAsync(false);
  **/
  setAsync = function(async) {
    _async = async;
  },


  // change array to url get format: a=b&c=d
  _params_2_url = function(params) {
    var encode = encodeURIComponent,
      p = [],
      key;
    for (key in params) p.push(encode(key) + '=' + encode(params[key]));

    return p.join('&');
  },

  /**
   * request: submit a request.
   * - method: the request method.
   * - url: the request url.
   * - body: the request body, can be dict / formdata.
   * - onsuccess: when request success.
   * - onfail: when request fail.
   *
   * How to use it?
   * var xhr = new require('xhr.js')();
   *
   * xhr.request('GET', '/update_name', {'name': 'hustcc'}, onsuccess, onerror);
  **/
  request = function(method, url, body, onsuccess, onfail) {
    _method = method;
    _url = url;
    _body = body;
    on('success', onsuccess);
    on('fail', onfail);
    return _request();
  },

  /**
   * get: submit a request with method = 'GET'.
   * - url: the request url.
   * - params: the request params.
   * - onsuccess: when request success.
   * - onfail: when request fail.
   *
   * How to use it?
   * var xhr = new require('xhr.js')();
   *
   * xhr.get('/update_name', {'name': 'hustcc'}, onsuccess, onerror);
  **/
  get = function(url, params, onsuccess, onfail) {
    // url中包含 get 参数和 params 合并
    if (_typeof(params) == 'object') params = _params_2_url(params);
    else params = '';

    if (params) url = url + '?' + params;
    return request('GET', url, '', onsuccess, onfail);
  },

  /**
   * post: submit a request with method = 'POST'.
   * - url: the request url.
   * - params: the request params.
   * - onsuccess: when request success.
   * - onfail: when request fail.
   *
   * How to use it?
   * var xhr = new require('xhr.js')();
   *
   * xhr.post('/update_name', {'name': 'hustcc'}, onsuccess, onerror);
   * xhr.post('/update_img', new FormData(), onsuccess, onerror);
  **/
  post = function(url, params, onsuccess, onfail) {
    var t = _typeof(params), cn = 'Content-Type', cv = 'application/';

    if (t == 'object') {
      params = _params_2_url(params);
      setRequestHeader(cn, cv + 'x-www-form-urlencoded');
    }
    else if (t == 'formdata') {} // for formdata type.
    else setRequestHeader(cn, cv + 'json');
    // if is string / formdata
    return request('POST', url, params, onsuccess, onfail);
  },


  // private method, use XMLHttpRequest to send a request.
  _request = function() {
    _xhr.open(_method, _url, _async);
    // 设置 header 内容
    for (var key in _headers) _xhr.setRequestHeader(key, _headers[key]);
    _xhr.onreadystatechange = __on_request_callback;
    _xhr.send(_body);
    return _this;
  },

  // the return object.
  _this =  {
    /**
     * url: get the request url.
     *
     * How to use it?
     * var xhr = new require('xhr.js')();
     *
     * xhr.url();
    **/
    url: function() {return _url;},
    /**
     * body: get the request body.
     *
     * How to use it?
     * var xhr = new require('xhr.js')();
     *
     * xhr.body();
    **/
    body: function() {return _body;},
    on: on,
    setRequestHeader: setRequestHeader,
    setAsync: setAsync,
    request: request,
    get: get,
    post: post,
    /**
     * abort: to abort request.
     *
     * How to use it?
     * var xhr = new require('xhr.js')();
     *
     * xhr.abort();
    **/
    abort: _xhr.abort,
    /**
     * reset: to reset the xhr instance, all will again.
     *
     * How to use it?
     * var xhr = new require('xhr.js')();
     *
     * xhr.reset();
    **/
    reset: function() {
      _async = true;
      _url = _body = _method = '';
      _headers = _events = {};
    }
  };
  return _this;
}
1225430
function getXhrOrXdr(id, suppliedXhr) {
        var xhrOrXdr = requestData[id] && requestData[id].xhr;

        if (!xhrOrXdr) {
            if (suppliedXhr) {
                xhrOrXdr = suppliedXhr;
            }
            else {
                if (options.cors.expected) {
                    xhrOrXdr = getCorsAjaxTransport();
                }
                else {
                    xhrOrXdr = qq.createXhrInstance();
                }
            }

            requestData[id].xhr = xhrOrXdr;
        }

        return xhrOrXdr;
    }
290012
function (request, xhr, callback) {

            var model = request.model;

            if (this._parsePayloadOnUpdate(request, xhr)) {
                this._parseModelPayload(xhr, model, request.options);
            }

            if (callback) {
                callback(null, model, request.options);
            }
        }
430742
function() {

		// XHR cannot access local files, always use ActiveX for that case
		if ( this.isLocal ) {
			return createActiveXHR();
		}

		// Support: IE 9-11
		// IE seems to error on cross-domain PATCH requests when ActiveX XHR
		// is used. In IE 9+ always use the native XHR.
		// Note: this condition won't catch Edge as it doesn't define
		// document.documentMode but it also doesn't support ActiveX so it won't
		// reach this code.
		if ( document.documentMode > 8 ) {
			return createStandardXHR();
		}

		// Support: IE<9
		// oldIE XHR does not support non-RFC2616 methods (#13240)
		// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
		// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
		// Although this check for six methods instead of eight
		// since IE also does not support "trace" and "connect"
		return /^(get|post|head|put|delete|options)$/i.test( this.type ) &&
			createStandardXHR() || createActiveXHR();
	}
408311
function makePostCorsRequest (url, data) {
        var xhr = createCORSRequest('POST', url, data);

        if (typeof _beforeXHRCallback === 'function') {
            _beforeXHRCallback(xhr);
        }

        if ('withCredentials' in xhr) {

            xhr.onreadystatechange = function() {
                if (xhr.readyState !== 4) {
                    return;
                }

                if (xhr.status === 202) {
                    sendSavedErrors();
                } else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400 && xhr.status !== 429) {
                    offlineSave(url, data);
                }
            };

            xhr.onload = function() {
                _private.log('posted to Raygun');

                callAfterSend(this);
            };

        } else if (window.XDomainRequest) {
            xhr.ontimeout = function() {
                if (_enableOfflineSave) {
                    _private.log('Raygun: saved locally');
                    offlineSave(url, data);
                }
            };

            xhr.onload = function() {
                _private.log('posted to Raygun');

                sendSavedErrors();
                callAfterSend(this);
            };
        }

        xhr.onerror = function() {
            _private.log('failed to post to Raygun');

            callAfterSend(this);
        };

        if (!xhr) {
            _private.log('CORS not supported');
            return;
        }

        xhr.send(data);
    }
76168
function toDataUrl(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}
608642
function createResponse(xhr, request){
  
  // XHR header processing borrowed from jQuery
  var responseHeaders = {}, match;
  while ((match = headersRegex.exec(xhr.getAllResponseHeaders()))) {
		responseHeaders[match[1].toLowerCase()] = match[2];
	}
	
  return {
    statusCode: xhr.status,
    statusText: xhr.statusText,
    headers: responseHeaders,
    originalUrl: request.url,
    effectiveUrl: request.url,
    redirected: false,
    requestMethod: request.method,
    requestHeaders: request.headers,
    body: xhr.responseText,
    retries: 0,
    throttled: false
  };
}