var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { hasOwnProperty, isArray, isFormData, isFunction, isNull, isNullish, isString } from './type-utils';
import { logger } from './logger';
import { nativeForEach, nativeIndexOf, window } from './globals';
var breaker = {};
export function eachArray(obj, iterator, thisArg) {
    if (isArray(obj)) {
        if (nativeForEach && obj.forEach === nativeForEach) {
            obj.forEach(iterator, thisArg);
        }
        else if ('length' in obj && obj.length === +obj.length) {
            for (var i = 0, l = obj.length; i < l; i++) {
                if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
                    return;
                }
            }
        }
    }
}
/**
 * @param {*=} obj
 * @param {function(...*)=} iterator
 * @param {Object=} thisArg
 */
export function each(obj, iterator, thisArg) {
    var e_1, _a;
    if (isNullish(obj)) {
        return;
    }
    if (isArray(obj)) {
        return eachArray(obj, iterator, thisArg);
    }
    if (isFormData(obj)) {
        try {
            for (var _b = __values(obj.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
                var pair = _c.value;
                if (iterator.call(thisArg, pair[1], pair[0]) === breaker) {
                    return;
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return;
    }
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
            if (iterator.call(thisArg, obj[key], key) === breaker) {
                return;
            }
        }
    }
}
export var extend = function (obj) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
    }
    eachArray(args, function (source) {
        for (var prop in source) {
            if (source[prop] !== void 0) {
                obj[prop] = source[prop];
            }
        }
    });
    return obj;
};
export var extendArray = function (obj) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
    }
    eachArray(args, function (source) {
        eachArray(source, function (item) {
            obj.push(item);
        });
    });
    return obj;
};
export var include = function (obj, target) {
    var found = false;
    if (isNull(obj)) {
        return found;
    }
    if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
        return obj.indexOf(target) != -1;
    }
    each(obj, function (value) {
        if (found || (found = value === target)) {
            return breaker;
        }
        return;
    });
    return found;
};
/**
 * Object.entries() polyfill
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
 */
export function entries(obj) {
    var ownProps = Object.keys(obj);
    var i = ownProps.length;
    var resArray = new Array(i); // preallocate the Array
    while (i--) {
        resArray[i] = [ownProps[i], obj[ownProps[i]]];
    }
    return resArray;
}
export var isValidRegex = function (str) {
    try {
        new RegExp(str);
    }
    catch (_a) {
        return false;
    }
    return true;
};
export var trySafe = function (fn) {
    try {
        return fn();
    }
    catch (_a) {
        return undefined;
    }
};
export var safewrap = function (f) {
    return function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        try {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            return f.apply(this, args);
        }
        catch (e) {
            logger.critical('Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.');
            logger.critical(e);
        }
    };
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
export var safewrapClass = function (klass, functions) {
    for (var i = 0; i < functions.length; i++) {
        klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]]);
    }
};
export var stripEmptyProperties = function (p) {
    var ret = {};
    each(p, function (v, k) {
        if (isString(v) && v.length > 0) {
            ret[k] = v;
        }
    });
    return ret;
};
/**
 * Deep copies an object.
 * It handles cycles by replacing all references to them with `undefined`
 * Also supports customizing native values
 *
 * @param value
 * @param customizer
 * @returns {{}|undefined|*}
 */
function deepCircularCopy(value, customizer) {
    var COPY_IN_PROGRESS_SET = new Set();
    function internalDeepCircularCopy(value, key) {
        if (value !== Object(value))
            return customizer ? customizer(value, key) : value; // primitive value
        if (COPY_IN_PROGRESS_SET.has(value))
            return undefined;
        COPY_IN_PROGRESS_SET.add(value);
        var result;
        if (isArray(value)) {
            result = [];
            eachArray(value, function (it) {
                result.push(internalDeepCircularCopy(it));
            });
        }
        else {
            result = {};
            each(value, function (val, key) {
                if (!COPY_IN_PROGRESS_SET.has(val)) {
                    ;
                    result[key] = internalDeepCircularCopy(val, key);
                }
            });
        }
        return result;
    }
    return internalDeepCircularCopy(value);
}
export function _copyAndTruncateStrings(object, maxStringLength) {
    return deepCircularCopy(object, function (value) {
        if (isString(value) && !isNull(maxStringLength)) {
            return value.slice(0, maxStringLength);
        }
        return value;
    });
}
export var registerEvent = (function () {
    // written by Dean Edwards, 2005
    // with input from Tino Zijdel - crisp@xs4all.nl
    // with input from Carl Sverre - mail@carlsverre.com
    // with input from PostHog
    // http://dean.edwards.name/weblog/2005/10/add-event/
    // https://gist.github.com/1930440
    /**
     * @param {Object} element
     * @param {string} type
     * @param {function(...*)} handler
     * @param {boolean=} oldSchool
     * @param {boolean=} useCapture
     */
    var register_event = function (element, type, handler, oldSchool, useCapture) {
        if (!element) {
            logger.error('No valid element provided to register_event');
            return;
        }
        if (element.addEventListener && !oldSchool) {
            element.addEventListener(type, handler, !!useCapture);
        }
        else {
            var ontype = 'on' + type;
            var old_handler = element[ontype] // can be undefined
            ;
            element[ontype] = makeHandler(element, handler, old_handler);
        }
    };
    function makeHandler(element, new_handler, old_handlers) {
        return function (event) {
            event = event || fixEvent(window === null || window === void 0 ? void 0 : window.event);
            // this basically happens in firefox whenever another script
            // overwrites the onload callback and doesn't pass the event
            // object to previously defined callbacks.  All the browsers
            // that don't define window.event implement addEventListener
            // so the dom_loaded handler will still be fired as usual.
            if (!event) {
                return undefined;
            }
            var ret = true;
            var old_result;
            if (isFunction(old_handlers)) {
                old_result = old_handlers(event);
            }
            var new_result = new_handler.call(element, event);
            if (false === old_result || false === new_result) {
                ret = false;
            }
            return ret;
        };
    }
    function fixEvent(event) {
        if (event) {
            event.preventDefault = fixEvent.preventDefault;
            event.stopPropagation = fixEvent.stopPropagation;
        }
        return event;
    }
    fixEvent.preventDefault = function () {
        ;
        this.returnValue = false;
    };
    fixEvent.stopPropagation = function () {
        ;
        this.cancelBubble = true;
    };
    return register_event;
})();
// NOTE: Update PostHogConfig docs if you change this list
// We will not try to catch all bullets here, but we should make an effort to catch the most common ones
// You should be highly against adding more to this list, because ultimately customers can configure
// their `cross_subdomain_cookie` setting to anything they want.
var EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app'];
export function isCrossDomainCookie(documentLocation) {
    var e_2, _a;
    var hostname = documentLocation === null || documentLocation === void 0 ? void 0 : documentLocation.hostname;
    if (!isString(hostname)) {
        return false;
    }
    // split and slice isn't a great way to match arbitrary domains,
    // but it's good enough for ensuring we only match herokuapp.com when it is the TLD
    // for the hostname
    var lastTwoParts = hostname.split('.').slice(-2).join('.');
    try {
        for (var EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1 = __values(EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE), EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1_1 = EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1.next(); !EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1_1.done; EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1_1 = EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1.next()) {
            var excluded = EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1_1.value;
            if (lastTwoParts === excluded) {
                return false;
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1_1 && !EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1_1.done && (_a = EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1.return)) _a.call(EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return true;
}
export function find(value, predicate) {
    for (var i = 0; i < value.length; i++) {
        if (predicate(value[i])) {
            return value[i];
        }
    }
    return undefined;
}
//# sourceMappingURL=index.js.map