Normalizes the response object so that we can extract response headers from
it in a uniform way regardless of whether we're using request.js or
browser-request.js.

@param {Object} response

@return {Object}
358518
function normalizeResponse(response)
{
  // if the response doesn't already have a getResponseHeader() method, add one
  if (response && !response.getResponseHeader)
  {
    response.getResponseHeader = function(header)
    {
      return response.headers && response.headers[
              Util.isString(header) ? header.toLowerCase() : header];
    };
  }

  return response;
}
11486
function serverResponseToRESPONSE (response) {
	try {
		const obj = JSON.parse(response);
		if (obj.result === RESPONSE_UNKNOWN) {
			return RESPONSE_UNKNOWN;
		} else {
			return obj.result.result;
		}
	} catch (e) {
		return RESPONSE_INVALID;
	}
}
1188665
function normalizeServer(server) {
  // normalize hostname
  if (!reProtocol.test(server)) {
    server = 'http://' + server;
  }
  server = url.parse(server);

  return {
    protocol: server.protocol,
    hostname: server.hostname,
    auth: server.auth,
    pathname: server.pathname,
    port: parseInt(server.port, 10) || (server.protocol === 'https:' ? 443 : 80)
  };
}
323897
function getResponseHeader(sHeaderName) {
		var sResponseHeader;

		sHeaderName = sHeaderName.toLowerCase();

		for (sResponseHeader in this.headers) {
			if (sResponseHeader.toLowerCase() === sHeaderName) {
				return this.headers[sResponseHeader];
			}
		}
	}
1077391
function parseHeaders(xhr) {
  const pairs = xhr.getAllResponseHeaders().trim().split('\n');
  const headers = {};
  pairs.forEach((header) => {
    const split = header.trim().split(':');
    const key = split.shift().trim().toLowerCase();
    const value = split.join(':').trim();
    headers[key] = value;
  });
  return headers;
}
1112186
function getOperationResponseHeaders(operation) {
    var headers = [];

    if (operation) {
        _.each(operation.responses, function(response, responseCode) {
            // Convert responseCode to a numeric value for sorting ("default" comes last)
            responseCode = parseInt(responseCode) || 999;

            _.each(response.headers, function(header, name) {
                // We only care about headers that have a default value defined
                if (header.default !== undefined) {
                    headers.push({
                        order: responseCode,
                        name: name.toLowerCase(),
                        value: header.default
                    });
                }
            });
        });
    }

    return _.sortBy(headers, 'order');
}
455807
function transform(req, res, next) {
    const state = res.state;
    const body = state.body;
    const type = typeof body;
    const isBuffer = body instanceof Buffer;
    let contentType;

    // error conversion
    if (body instanceof Error) {
        res.log('transform', 'Converting Error to response');
        res.status(500).body(httpStatus[500]).set('content-type', 'text/plain');

    // buffer conversion
    } else if (isBuffer) {
        res.log('transform', 'Converting Buffer to base64 string');
        res.body(body.toString('base64'));
        contentType = 'application/octet-stream';

    // object conversion
    } else if (type === 'object') {
        res.log('transform', 'Converting object to JSON string');
        res.body(JSON.stringify(body));
        contentType = 'application/json';

    // not string conversion
    } else if (type !== 'string') {
        res.log('transform', 'Converting ' + type + ' to string');
        res.body(String(body));
        contentType = 'text/plain';

    } else {
        contentType = 'text/html';
    }

    // set content type if not yet set
    if (!state.headers.hasOwnProperty('content-type') && contentType) {
        res.log('transform', 'Set content type');
        res.set('Content-Type', contentType);
    }

    next();
}
905220
function normalize(obj) {
    const isMultipart = isFormData(obj);
    const content = { filename: '', value: '', mime: '' };
    const result = ((isMultipart) ? new FormData() : {});
    let file = null;

    Object.keys(obj).forEach((item) => {
        if (isMultipart) {
            if (obj[item].value) content.value = obj[item].value;
            else content.value = obj[item];

            content.filename = obj[item].filename || null;
            content.mime = obj[item].mime || null;

            if (content.value instanceof stream.Stream) {
                result.append(item, content.value, {
                    contentType: content.mime,
                    filename: content.filename,
                });

                return;
            }

            if (Buffer.isBuffer(content.value)) {
                file = FileType(content.value);
                result.append(item, content.value, {
                    contentType: content.mime || file.mime || 'application/octet-stream',
                    filename: content.filename || `data-${Date.now()}.${file.ext || ''}`,
                });

                return;
            }

            if (typeof content.value === 'object') {
                result.append(item, JSON.stringify(content.value), {
                    contentType: 'application/json',
                });

                return;
            }

            result.append(item, content.value);
        } else {
            if (typeof obj[item] === 'object') {
                result[item] = JSON.stringify(obj[item]);
                return;
            }

            result[item] = obj[item];
        }
    });

    return result;
}
580042
function parseResponse({ browser, history, document, response }) {
  const window      = document.defaultView;
  window._request   = response.request;
  window._response  = response;
  history.updateLocation(window, response._url);

  const done = window._eventQueue.waitForCompletion();
  response
    ._consume()
    .then(function(body) {

      const contentType = response.headers.get('Content-Type') || '';
      const html        = getHTMLFromResponseBody(body, contentType);
      response.body     = html;
      document.write(html || '<html></html>');
      document.close();

      browser.emit('loaded', document);
      if (response.status >= 400)
        throw new Error(`Server returned status code ${response.status} from ${response.url}`);
      if (!document.documentElement)
        throw new Error(`Could not parse document at ${response.url}`);

    })
    .then(function() {

      // Handle meta refresh.  Automatically reloads new location and counts
      // as a redirect.
      //
      // If you need to check the page before refresh takes place, use this:
      //   browser.wait({
      //     function: function() {
      //       return browser.query('meta[http-equiv="refresh"]');
      //     }
      //   });
      const refresh = getMetaRefresh(document);

      if (refresh) {
        const { refreshTimeout } = refresh;
        const { refreshURL }     = refresh;

        window._eventQueue.setTimeout(function() {
          // Allow completion function to run
          window._eventQueue.enqueue(function() {
            window._eventQueue.enqueue(function() {
              // Count a meta-refresh in the redirects count.
              history.replace(refreshURL);
              // This results in a new window getting loaded
              const newWindow = history.current.window;
              newWindow.addEventListener('load', function() {
                ++newWindow._request._redirectCount;
              });
            });
          });
        }, refreshTimeout * 1000);
      }

    })
    .catch(function(error) {
      browser.emit('error', error);
    })
    .then(done);
}
999623
function normalize(route) {
  const normalized = { ...route };

  if (is.not.array(normalized.path) && is.not.string(normalized.path)) {
    throw new Error("The route's path must be a String or [String]");
  }

  if (is.array(normalized.method)) {
    /* If method is an array */
    for (let method of normalized.method) {
      method = clean(method);
    }
  }

  /* If method is a string */
  if (is.string(normalized.method)) {
    normalized.method = clean(normalized.method);
  }

  return normalized;
}
1318915
function normalize(result) {
  return {
    relevance: result.relevance || 0,
    language: result.language || null,
    value: result.value || []
  }
}
1184938
function (error, response) {
            // Destroy the client - frees up resources so that the application
            // stops running
            client.destroy()
            // Display the contents of an error, if one occurred
            if (error) {
              console.log('Request error: ' + error.message)
              // The 'code' property, if set, typically has a string
              // representation of the error code.
              if (error.code) {
                console.log('Request error code: ' + error.code)
              // If no string representation is available for the error code
              // but the error is a DXL 'RequestError', a numeric error
              // code should be available in the
              // 'dxlErrorResponse.errorCode' property.
              } else if (error.dxlErrorResponse) {
                console.log('Request error code: ' +
                  error.dxlErrorResponse.errorCode)
              }
            // No error occurred, so extract information from the response. The
            // toString() call converts the payload from a binary Buffer into a
            // string, decoded using UTF-8 character encoding.
            } else {
              console.log('Client received response payload: ' +
                response.payload.toString())
            }
          }
43411
function fixRedirectedResponse(response) {
  if (isNotRedirectedResponse(response)) {
    return Promise.resolve(response);
  }

  const body = 'body' in response ?
    Promise.resolve(response.body) : response.blob();

  return body.then(data => {
    return new Response(data, {
      headers: response.headers,
      status: response.status
    });
  });
}
1193671
function formatResponse (res) {
    // iterate over rows in response
    _.each(res, row => {
        // iterate over key/value pairs in row object
        _.each(row, (val, key) => {
            // convert nulls to undefined
            if (val === null) {
                row[key] = undefined
            }
        })
    })
}
711592
@SuppressWarnings("unchecked")
	public static <T> JSONNormalizer getJSONStandardizer(Response<T> response) {
		JSONNormalizer standardizer = new JSONNormalizer();
		Class<JSONNormalizer> standardizerClazz = ClassUtil.getClassAnnotationValue(response.getClass(), Normalized.class, "value", Class.class);
		if (standardizerClazz != null) {
			try {
				standardizer = standardizerClazz.newInstance();
			} catch (InstantiationException e) {
			} catch (IllegalAccessException e) {
			}
		}
		return standardizer;
	}
1264985
function normalizeHeaderKey() {
  var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

  return key.replace(/\r?\n|\r/g, ' ') // no newlines in keys
  .trim().toLowerCase().replace(/^MIME\b|^[a-z]|-[a-z]/ig, function (c) {
    return c.toUpperCase();
  }); // use uppercase words, except MIME
}
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
  };
}