import { __read, __spreadArray } from "tslib";
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/prefer-optional-chain */
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
import { getRegexp } from '@slardar/sdk-template';
import { getDefaultBrowser } from '../../utils';
import { hookGlobalAsync } from './capture-global';
import { dedupe } from './dedupe';
import { normalizeUnknownError, normalizeError, normalizeException } from './util';
export var JS_ERROR_EV_TYPE = 'js_error';
export var JsErrorMonitor = function (window) {
    if (window === void 0) { window = getDefaultBrowser(); }
    if (!window) {
        return;
    }
    return function (props, cb) {
        var ignoreErrors = props.ignoreErrors, onerror = props.onerror, onunhandledrejection = props.onunhandledrejection, dedupeFlag = props.dedupe, captureGlobalAsync = props.captureGlobalAsync;
        var ignoreRegExp = getRegexp(ignoreErrors);
        var restoreFns = [];
        var dedupeFn = dedupe();
        var report = function (_a) {
            var error = _a.error, extra = _a.extra, react = _a.react, source = _a.source;
            var err = dedupeFlag ? dedupeFn(error) : error;
            if (cb && err) {
                if (ignoreRegExp && ignoreRegExp.test(err.message)) {
                    return;
                }
                cb({
                    ev_type: JS_ERROR_EV_TYPE,
                    payload: {
                        error: err,
                        breadcrumbs: [],
                        extra: extra,
                        react: react,
                        source: source,
                    },
                });
            }
        };
        if (onerror) {
            var handleError_1 = function (ev) { return report({ error: normalizeError(ev), source: { type: 'onerror' } }); };
            window.addEventListener('error', handleError_1);
            restoreFns.push(function () { return window.removeEventListener('error', handleError_1); });
        }
        if (onunhandledrejection) {
            var handleRejection_1 = function (ev) {
                return report({ error: normalizeException(ev), source: { type: 'onunhandledrejection' } });
            };
            window.addEventListener('unhandledrejection', handleRejection_1);
            restoreFns.push(function () { return window.removeEventListener('unhandledrejection', handleRejection_1); });
        }
        if (captureGlobalAsync) {
            restoreFns.push.apply(restoreFns, __spreadArray([], __read(hookGlobalAsync(report)), false));
        }
        var tearDown = function () {
            restoreFns.forEach(function (fn) { return fn(); });
        };
        return [
            function (err, extra, react) { return report({ error: normalizeUnknownError(err), extra: extra, react: react, source: { type: 'manual' } }); },
            tearDown,
        ];
    };
};
//# sourceMappingURL=index.js.map