"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionRecordingWrapper = void 0;
var constants_1 = require("../../constants");
var core_1 = require("@posthog/core");
var logger_1 = require("../../utils/logger");
var globals_1 = require("../../utils/globals");
var triggerMatching_1 = require("./triggerMatching");
var LOGGER_PREFIX = '[SessionRecording]';
var logger = (0, logger_1.createLogger)(LOGGER_PREFIX);
/**
 * This only exists to let us test changes to sessionrecording.ts before rolling them out to everyone
 * it should not be depended on in other ways, since i'm going to delete it long before the end of September 2025
 */
var SessionRecordingWrapper = /** @class */ (function () {
    function SessionRecordingWrapper(_instance) {
        this._instance = _instance;
        this._forceAllowLocalhostNetworkCapture = false;
        if (!this._instance.sessionManager) {
            logger.error('started without valid sessionManager');
            throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.');
        }
        if (this._instance.config.cookieless_mode === 'always') {
            throw new Error(LOGGER_PREFIX + ' cannot be used with cookieless_mode="always"');
        }
    }
    Object.defineProperty(SessionRecordingWrapper.prototype, "started", {
        get: function () {
            var _a;
            return !!((_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.isStarted);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SessionRecordingWrapper.prototype, "status", {
        /**
         * defaults to buffering mode until a flags response is received
         * once a flags response is received status can be disabled, active or sampled
         */
        get: function () {
            var _a;
            if (!this._isRecordingEnabled) {
                return triggerMatching_1.DISABLED;
            }
            return ((_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.status) || triggerMatching_1.LAZY_LOADING;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SessionRecordingWrapper.prototype, "_isRecordingEnabled", {
        get: function () {
            var enabled_server_side = !!this._instance.get_property(constants_1.SESSION_RECORDING_ENABLED_SERVER_SIDE);
            var enabled_client_side = !this._instance.config.disable_session_recording;
            var isDisabled = this._instance.config.disable_session_recording || this._instance.consent.isOptedOut();
            return globals_1.window && enabled_server_side && enabled_client_side && !isDisabled;
        },
        enumerable: false,
        configurable: true
    });
    SessionRecordingWrapper.prototype.startIfEnabledOrStop = function (startReason) {
        var _a;
        if (this._isRecordingEnabled && ((_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.isStarted)) {
            return;
        }
        // According to the rrweb docs, rrweb is not supported on IE11 and below:
        // "rrweb does not support IE11 and below because it uses the MutationObserver API, which was supported by these browsers."
        // https://github.com/rrweb-io/rrweb/blob/master/guide.md#compatibility-note
        //
        // However, MutationObserver does exist on IE11, it just doesn't work well and does not detect all changes.
        // Instead, when we load "recorder.js", the first JS error is about "Object.assign" and "Array.from" being undefined.
        // Thus instead of MutationObserver, we look for this function and block recording if it's undefined.
        var canRunReplay = !(0, core_1.isUndefined)(Object.assign) && !(0, core_1.isUndefined)(Array.from);
        if (this._isRecordingEnabled && canRunReplay) {
            this._lazyLoadAndStart(startReason);
            logger.info('starting');
        }
        else {
            this.stopRecording();
        }
    };
    /**
     * session recording waits until it receives remote config before loading the script
     * this is to ensure we can control the script name remotely
     * and because we wait until we have local and remote config to determine if we should start at all
     * if start is called and there is no remote config then we wait until there is
     */
    SessionRecordingWrapper.prototype._lazyLoadAndStart = function (startReason) {
        var _this = this;
        var _a, _b, _c, _d, _e;
        // by checking `_isRecordingEnabled` here we know that
        // we have stored remote config and client config to read
        // replay waits for both local and remote config before starting
        if (!this._isRecordingEnabled) {
            return;
        }
        // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is
        // imported), don't load the script. Otherwise, remotely import recorder.js from cdn since it hasn't been loaded.
        if (!((_b = (_a = globals_1.assignableWindow === null || globals_1.assignableWindow === void 0 ? void 0 : globals_1.assignableWindow.__PosthogExtensions__) === null || _a === void 0 ? void 0 : _a.rrweb) === null || _b === void 0 ? void 0 : _b.record) ||
            !((_c = globals_1.assignableWindow.__PosthogExtensions__) === null || _c === void 0 ? void 0 : _c.initSessionRecording)) {
            (_e = (_d = globals_1.assignableWindow.__PosthogExtensions__) === null || _d === void 0 ? void 0 : _d.loadExternalDependency) === null || _e === void 0 ? void 0 : _e.call(_d, this._instance, this._scriptName, function (err) {
                if (err) {
                    return logger.error('could not load recorder', err);
                }
                _this._onScriptLoaded(startReason);
            });
        }
        else {
            this._onScriptLoaded(startReason);
        }
    };
    SessionRecordingWrapper.prototype.stopRecording = function () {
        var _a;
        (_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.stop();
    };
    SessionRecordingWrapper.prototype.onRemoteConfig = function (response) {
        var _a;
        var _b;
        this._pendingRemoteConfig = response;
        var persistence = this._instance.persistence;
        if (persistence) {
            persistence.register((_a = {},
                _a[constants_1.SESSION_RECORDING_ENABLED_SERVER_SIDE] = !!response.sessionRecording,
                _a[constants_1.SESSION_RECORDING_SCRIPT_CONFIG] = (_b = response.sessionRecording) === null || _b === void 0 ? void 0 : _b.scriptConfig,
                _a));
        }
        if (!this._lazyLoadedSessionRecording) {
            this._lazyLoadAndStart();
        }
        else {
            this._lazyLoadedSessionRecording.onRemoteConfig(response);
            this._pendingRemoteConfig = undefined;
        }
        this.startIfEnabledOrStop();
    };
    SessionRecordingWrapper.prototype.log = function (message, level) {
        var _a;
        if (level === void 0) { level = 'log'; }
        if ((_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.log) {
            this._lazyLoadedSessionRecording.log(message, level);
        }
        else {
            logger.warn('log called before recorder was ready');
        }
    };
    Object.defineProperty(SessionRecordingWrapper.prototype, "_scriptName", {
        get: function () {
            var _a, _b, _c;
            return (((_c = (_b = (_a = this._instance) === null || _a === void 0 ? void 0 : _a.persistence) === null || _b === void 0 ? void 0 : _b.get_property(constants_1.SESSION_RECORDING_SCRIPT_CONFIG)) === null || _c === void 0 ? void 0 : _c.script) || 'lazy-recorder');
        },
        enumerable: false,
        configurable: true
    });
    SessionRecordingWrapper.prototype._onScriptLoaded = function (startReason) {
        var _a, _b;
        if (!((_a = globals_1.assignableWindow.__PosthogExtensions__) === null || _a === void 0 ? void 0 : _a.initSessionRecording)) {
            throw Error('Called on script loaded before session recording is available');
        }
        if (!this._lazyLoadedSessionRecording) {
            this._lazyLoadedSessionRecording = (_b = globals_1.assignableWindow.__PosthogExtensions__) === null || _b === void 0 ? void 0 : _b.initSessionRecording(this._instance);
            this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture =
                this._forceAllowLocalhostNetworkCapture;
            // If we have a pending remote config, apply it now
            if (this._pendingRemoteConfig) {
                this._lazyLoadedSessionRecording.onRemoteConfig(this._pendingRemoteConfig);
                // Clear the pending config after applying it
                this._pendingRemoteConfig = undefined;
            }
        }
        this._lazyLoadedSessionRecording.start(startReason);
    };
    SessionRecordingWrapper.prototype.onRRwebEmit = function (rawEvent) {
        var _a, _b;
        (_b = (_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.onRRwebEmit) === null || _b === void 0 ? void 0 : _b.call(_a, rawEvent);
    };
    /**
     * this ignores the linked flag config and (if other conditions are met) causes capture to start
     *
     * It is not usual to call this directly,
     * instead call `posthog.startSessionRecording({linked_flag: true})`
     * */
    SessionRecordingWrapper.prototype.overrideLinkedFlag = function () {
        var _a;
        // TODO what if this gets called before lazy loading is done
        (_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.overrideLinkedFlag();
    };
    /**
     * this ignores the sampling config and (if other conditions are met) causes capture to start
     *
     * It is not usual to call this directly,
     * instead call `posthog.startSessionRecording({sampling: true})`
     * */
    SessionRecordingWrapper.prototype.overrideSampling = function () {
        var _a;
        // TODO what if this gets called before lazy loading is done
        (_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.overrideSampling();
    };
    /**
     * this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start
     *
     * It is not usual to call this directly,
     * instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`
     * */
    SessionRecordingWrapper.prototype.overrideTrigger = function (triggerType) {
        var _a;
        // TODO what if this gets called before lazy loading is done
        (_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.overrideTrigger(triggerType);
    };
    Object.defineProperty(SessionRecordingWrapper.prototype, "sdkDebugProperties", {
        /*
         * whenever we capture an event, we add these properties to the event
         * these are used to debug issues with the session recording
         * when looking at the event feed for a session
         */
        get: function () {
            var _a;
            return (((_a = this._lazyLoadedSessionRecording) === null || _a === void 0 ? void 0 : _a.sdkDebugProperties) || {
                $recording_status: this.status,
            });
        },
        enumerable: false,
        configurable: true
    });
    return SessionRecordingWrapper;
}());
exports.SessionRecordingWrapper = SessionRecordingWrapper;
//# sourceMappingURL=sessionrecording-wrapper.js.map