<commit_before>/**
 * @module request
 *
 * @description Jsonp requests on client normal http requests on server.
 */
/*!
 * @TODO: what about normal ajax requests on client ?
 */

var _ = require('lodash');
var UAParser = require('ua-parser-js');

module.exports = typeof window == 'undefined' ? serverRequest : clientRequest;

/**
 * Враппер для jQuery.ajax и request с более менее общим апи.
 *
 * Из параметров ниже, `xhr` и `errorDesc` зависит от среды исполнения.
 *
 * @param {string} conf.url - Урл запроса.
 * @param {string} conf.type - Тип запроса (на сервере поддерживается только json).
 * @param {Object} conf.data - Параметры запроса.
 * @param {Function} [conf.success] - callback(body, xhr)
 * @param {Function} [conf.error] - callback(xhr, reason)
 * @param {Function} [conf.complete] - callback(error, result, xhr)
 * @param {int} conf.timeout - In milliseconds.
 * @returns {*}
 */
function serverRequest(conf) {
    var request = require('request'),
        winston = require('./logger');

    if (conf.method && conf.method.toLowerCase() == 'post') {
        conf.form = conf.data;
    } else {
        conf.qs = conf.data;
    }

    _.defaults(conf, {
        success: _.noop,
        error: _.noop,
        complete: _.noop,
        pool: false
    });

    // @doclink: https://github.com/mikeal/request#requestoptions-callback
    return request(conf, function(error, xhr, body) {
        if (error) {
            conf.error.call(conf.context, xhr, error);

            winston.error("Couldn't do request", {
                url: conf.url,
                params: conf,
                statusCode: xhr && xhr.statusCode,
                error: error + ''
            });
        } else {
            try {
                body = conf.type.match(/^json/) ? JSON.parse(body) : body;
                conf.success.call(conf.context, body, xhr);
            } catch (ex) {
                if (ex instanceof SyntaxError) {
                    var err = new SyntaxError(
                        "[request] couldn't parse response as JSON (from " + conf.url + "): " + body
                    );

                    conf.error.call(conf.context, xhr, err);
                } else {
                    throw ex;
                }
            }
        }

        conf.complete.call(conf.context, error, body, xhr);
    });
}


var isLegacyIECached = null;

function isLegacyIE() {
    if (isLegacyIECached == null) {
        var res = UAParser(navigator.userAgent);
        isLegacyIECached = res.browser.name == 'IE' && Number(res.browser.major) < 10;
    }
    return isLegacyIECached;
}

var originRe = /(?:https?:\/\/|\/)?([^/:]+)/;

function isSameOrigin(url) {
    var matched = url.match(originRe);
    if (matched) {
        return document.location.hostname == matched[1];
    }
}

function clientRequest(conf) {
    var reqwest = require('reqwest');
    // @doclink: https://github.com/ded/reqwest

    _.defaults(conf, {
        success: _.noop,
        error: _.noop,
        complete: _.noop,
        overrideType: _.noop
    });

    if (!isSameOrigin(conf.url)) {<commit_msg>fix lib/request again<commit_after>/**
 * @module request
 *
 * @description Jsonp requests on client normal http requests on server.
 */
/*!
 * @TODO: what about normal ajax requests on client ?
 */

var _ = require('lodash');
var UAParser = require('ua-parser-js');

module.exports = typeof window == 'undefined' ? serverRequest : clientRequest;

/**
 * Враппер для jQuery.ajax и request с более менее общим апи.
 *
 * Из параметров ниже, `xhr` и `errorDesc` зависит от среды исполнения.
 *
 * @param {string} conf.url - Урл запроса.
 * @param {string} conf.type - Тип запроса (на сервере поддерживается только json).
 * @param {Object} conf.data - Параметры запроса.
 * @param {Function} [conf.success] - callback(body, xhr)
 * @param {Function} [conf.error] - callback(xhr, reason)
 * @param {Function} [conf.complete] - callback(error, result, xhr)
 * @param {int} conf.timeout - In milliseconds.
 * @returns {*}
 */
function serverRequest(conf) {
    var request = require('request'),
        winston = require('./logger');

    if (conf.method && conf.method.toLowerCase() == 'post') {
        conf.form = conf.data;
    } else {
        conf.qs = conf.data;
    }

    _.defaults(conf, {
        success: _.noop,
        error: _.noop,
        complete: _.noop,
        pool: false
    });

    // @doclink: https://github.com/mikeal/request#requestoptions-callback
    return request(conf, function(error, xhr, body) {
        if (error) {
            conf.error.call(conf.context, xhr, error);

            winston.error("Couldn't do request", {
                url: conf.url,
                params: conf,
                statusCode: xhr && xhr.statusCode,
                error: error + ''
            });
        } else {
            try {
                body = conf.type.match(/^json/) ? JSON.parse(body) : body;
                conf.success.call(conf.context, body, xhr);
            } catch (ex) {
                if (ex instanceof SyntaxError) {
                    var err = new SyntaxError(
                        "[request] couldn't parse response as JSON (from " + conf.url + "): " + body
                    );

                    conf.error.call(conf.context, xhr, err);
                } else {
                    throw ex;
                }
            }
        }

        conf.complete.call(conf.context, error, body, xhr);
    });
}


var isLegacyIECached = null;

function isLegacyIE() {
    if (isLegacyIECached == null) {
        var res = UAParser(navigator.userAgent);
        isLegacyIECached = res.browser.name == 'IE' && Number(res.browser.major) < 10;
    }
    return isLegacyIECached;
}

var originRe = /https?:\/\/([^/:]+)/;

function isCrossOrigin(url) {
    var matched = url.match(originRe);
    if (matched) {
        return document.location.hostname != matched[1];
    }
}

function clientRequest(conf) {
    var reqwest = require('reqwest');
    // @doclink: https://github.com/ded/reqwest

    _.defaults(conf, {
        success: _.noop,
        error: _.noop,
        complete: _.noop,
        overrideType: _.noop
    });

    if (isCrossOrigin(conf.url)) {
{'fraction_non_alphanumeric': 0.14177784922038258, 'fraction_numerical': 0.0009644751647645073, 'mean_word_length': 2.0529931305201177, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7436246', 'n_tokens_mistral': 1971, 'n_tokens_neox': 1937, 'n_words': 462}