import { assignableWindow } from '../utils/globals';
import { logger } from '../utils/logger';
import Config from '../config';
import { isUndefined } from '../utils/type-utils';
var LOGGER_PREFIX = '[TRACING-HEADERS]';
var TracingHeaders = /** @class */ (function () {
    function TracingHeaders(instance) {
        var _this = this;
        this.instance = instance;
        this._restoreXHRPatch = undefined;
        this._restoreFetchPatch = undefined;
        this._startCapturing = function () {
            var _a, _b, _c, _d;
            // NB: we can assert sessionManager is present only because we've checked previously
            if (isUndefined(_this._restoreXHRPatch)) {
                (_b = (_a = assignableWindow.__PosthogExtensions__) === null || _a === void 0 ? void 0 : _a.tracingHeadersPatchFns) === null || _b === void 0 ? void 0 : _b._patchXHR(_this.instance.sessionManager);
            }
            if (isUndefined(_this._restoreFetchPatch)) {
                (_d = (_c = assignableWindow.__PosthogExtensions__) === null || _c === void 0 ? void 0 : _c.tracingHeadersPatchFns) === null || _d === void 0 ? void 0 : _d._patchFetch(_this.instance.sessionManager);
            }
        };
    }
    TracingHeaders.prototype._loadScript = function (cb) {
        var _a;
        if ((_a = assignableWindow.__PosthogExtensions__) === null || _a === void 0 ? void 0 : _a.tracingHeadersPatchFns) {
            // already loaded
            cb();
        }
        this.instance.requestRouter.loadScript("/static/tracing-headers.js?v=".concat(Config.LIB_VERSION), function (err) {
            if (err) {
                return logger.error(LOGGER_PREFIX + ' failed to load script', err);
            }
            cb();
        });
    };
    TracingHeaders.prototype.startIfEnabledOrStop = function () {
        var _a, _b;
        if (this.instance.config.__add_tracing_headers) {
            this._loadScript(this._startCapturing);
        }
        else {
            (_a = this._restoreXHRPatch) === null || _a === void 0 ? void 0 : _a.call(this);
            (_b = this._restoreFetchPatch) === null || _b === void 0 ? void 0 : _b.call(this);
            // we don't want to call these twice so we reset them
            this._restoreXHRPatch = undefined;
            this._restoreFetchPatch = undefined;
        }
    };
    return TracingHeaders;
}());
export { TracingHeaders };
//# sourceMappingURL=tracing-headers.js.map