var se = Object.defineProperty, te = Object.defineProperties;
var ie = Object.getOwnPropertyDescriptors;
var C = Object.getOwnPropertySymbols;
var F = Object.prototype.hasOwnProperty, G = Object.prototype.propertyIsEnumerable;
var N = (l, e, t) => e in l ? se(l, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : l[e] = t, u = (l, e) => {
  for (var t in e || (e = {}))
    F.call(e, t) && N(l, t, e[t]);
  if (C)
    for (var t of C(e))
      G.call(e, t) && N(l, t, e[t]);
  return l;
}, S = (l, e) => te(l, ie(e));
var B = (l, e) => {
  var t = {};
  for (var s in l)
    F.call(l, s) && e.indexOf(s) < 0 && (t[s] = l[s]);
  if (l != null && C)
    for (var s of C(l))
      e.indexOf(s) < 0 && G.call(l, s) && (t[s] = l[s]);
  return t;
};
var o = (l, e, t) => N(l, typeof e != "symbol" ? e + "" : e, t);
var D = (l, e, t) => new Promise((s, n) => {
  var a = (g) => {
    try {
      r(t.next(g));
    } catch (h) {
      n(h);
    }
  }, i = (g) => {
    try {
      r(t.throw(g));
    } catch (h) {
      n(h);
    }
  }, r = (g) => g.done ? s(g.value) : Promise.resolve(g.value).then(a, i);
  r((t = t.apply(l, e)).next());
});
import { W as ne, M as _, g as oe, b as ae, r as M, I as j, c as W, S as re, P as he, V as ge, C as le, F as ce, d as de, N as ue, e as pe, h as me, i as A, j as Se, k as fe, p as De, G as _e, l as Ie, m as ve, n as we } from "./record-YrLd-o_q.js";
import { G as U, g as J, S as v, r as x, k as z, o as ye, n as V, t as H, u as T, F as q, M as f, w, V as be, H as K, y as Le, z as Te, s as $, L as Ee, b as Re, B as Y, v as Q, a2 as ke, q as Ce, x as Oe } from "./common-TyzI476o.js";
import { F as y } from "./index-CJboPLn8.js";
import { f as Pe, p as Ne, P as Me, J as Ue, h as O, B as P, d as ze } from "./observe-8IEDbvL-.js";
import { i as Je, j as xe } from "./observe-8IEDbvL-.js";
import { L as Ve } from "./buffer-9GjOvOok.js";
const E = (l, e) => {
  console.warn(`Highlight Warning: (${l}): `, { output: e });
};
class X {
  constructor(e, t) {
    o(this, "options");
    /** Determines if the client is running on a Highlight property (e.g. frontend). */
    o(this, "isRunningOnHighlight");
    /** Verbose project ID that is exposed to users. Legacy users may still be using ints. */
    o(this, "organizationID");
    o(this, "graphqlSDK");
    o(this, "events");
    o(this, "sessionData");
    o(this, "ready");
    o(this, "manualStopped");
    o(this, "state");
    o(this, "logger");
    o(this, "enableSegmentIntegration");
    o(this, "privacySetting");
    o(this, "enableCanvasRecording");
    o(this, "enablePerformanceRecording");
    o(this, "samplingStrategy");
    o(this, "inlineImages");
    o(this, "inlineVideos");
    o(this, "inlineStylesheet");
    o(this, "debugOptions");
    o(this, "listeners");
    o(this, "firstloadVersion");
    o(this, "environment");
    o(this, "sessionShortcut");
    /** The end-user's app version. This isn't Highlight's version. */
    o(this, "appVersion");
    o(this, "serviceName");
    o(this, "_worker");
    o(this, "_optionsInternal");
    o(this, "_backendUrl");
    o(this, "_recordingStartTime");
    o(this, "_isOnLocalHost");
    o(this, "_onToggleFeedbackFormVisibility");
    o(this, "_firstLoadListeners");
    o(this, "_isCrossOriginIframe");
    o(this, "_eventBytesSinceSnapshot");
    o(this, "_lastSnapshotTime");
    o(this, "_lastVisibilityChangeTime");
    o(this, "pushPayloadTimerId");
    o(this, "hasSessionUnloaded");
    o(this, "hasPushedData");
    o(this, "reloaded");
    o(this, "_hasPreviouslyInitialized");
    o(this, "_recordStop");
    o(this, "_gauges", /* @__PURE__ */ new Map());
    o(this, "_counters", /* @__PURE__ */ new Map());
    o(this, "_histograms", /* @__PURE__ */ new Map());
    o(this, "_up_down_counters", /* @__PURE__ */ new Map());
    o(this, "_integrations", []);
    var n, a, i, r, g;
    e.sessionSecureID || (e.sessionSecureID = U()), this.options = e, typeof ((n = this.options) == null ? void 0 : n.debug) == "boolean" ? this.debugOptions = this.options.debug ? { clientInteractions: !0 } : {} : this.debugOptions = (i = (a = this.options) == null ? void 0 : a.debug) != null ? i : {}, this.logger = new Ve(this.debugOptions.clientInteractions), e.storageMode && (this.logger.log(`initializing in ${e.storageMode} session mode`), ke(e.storageMode)), Re(!!(e != null && e.sessionCookie)), this._worker = new ne(), this._worker.onmessage = (h) => {
      var c, d, p;
      ((c = h.data.response) == null ? void 0 : c.type) === _.AsyncEvents ? (this._eventBytesSinceSnapshot += h.data.response.eventsSize, this.logger.log(`Web worker sent payloadID ${h.data.response.id} size ${h.data.response.eventsSize} bytes, compression ratio ${h.data.response.eventsSize / h.data.response.compressedSize}.
                Total since snapshot: ${(this._eventBytesSinceSnapshot / 1e6).toFixed(1)}MB`)) : ((d = h.data.response) == null ? void 0 : d.type) === _.CustomEvent ? this.addCustomEvent(h.data.response.tag, h.data.response.payload) : ((p = h.data.response) == null ? void 0 : p.type) === _.Stop && (E("Stopping recording due to worker failure", h.data.response), this.stopRecording(!1));
    };
    let s = J();
    if (this.reloaded = !1, !((r = this.sessionData) != null && r.sessionSecureID) && (s != null && s.sessionSecureID))
      this.sessionData = s, this.options.sessionSecureID = s.sessionSecureID, this.reloaded = !0, this.logger.log(`Tab reloaded, continuing previous session: ${this.sessionData.sessionSecureID}`);
    else {
      for (const h of Object.values(v))
        x(h);
      this.sessionData = {
        sessionSecureID: this.options.sessionSecureID,
        projectID: 0,
        payloadID: 1,
        sessionStartTime: Date.now()
      };
    }
    this._hasPreviouslyInitialized = !1, this._firstLoadListeners = t || new y(this.options);
    try {
      window.parent.document && (this._isCrossOriginIframe = !1);
    } catch (h) {
      this._isCrossOriginIframe = (g = this.options.recordCrossOriginIframe) != null ? g : !0;
    }
    this._initMembers(this.options);
  }
  static create(e) {
    return new X(e);
  }
  // Start a new session
  _reset(t) {
    return D(this, arguments, function* ({ forceNew: e }) {
      this.pushPayloadTimerId && (clearTimeout(this.pushPayloadTimerId), this.pushPayloadTimerId = void 0);
      let s, n;
      if (!e)
        try {
          s = z(v.USER_IDENTIFIER);
          const a = z(v.USER_OBJECT);
          a && (n = JSON.parse(a));
        } catch (a) {
        }
      for (const a of Object.values(v))
        x(a);
      this.sessionData.sessionSecureID = U(), this.sessionData.sessionStartTime = Date.now(), this.options.sessionSecureID = this.sessionData.sessionSecureID, this.stopRecording(), this._firstLoadListeners = new y(this.options), yield this.initialize(), s && n && this.identify(s, n);
    });
  }
  _initMembers(e) {
    var a, i, r, g, h, c, d, p, I, b, L, R;
    this.sessionShortcut = !1, this._recordingStartTime = 0, this._isOnLocalHost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "", this.ready = !1, this.state = "NotRecording", this.manualStopped = !1, this.enableSegmentIntegration = !!e.enableSegmentIntegration, this.privacySetting = (a = e.privacySetting) != null ? a : "default", this.enableCanvasRecording = (i = e.enableCanvasRecording) != null ? i : !1, this.enablePerformanceRecording = (r = e.enablePerformanceRecording) != null ? r : !0, this.inlineImages = (g = e.inlineImages) != null ? g : this._isOnLocalHost, this.inlineVideos = (h = e.inlineVideos) != null ? h : this._isOnLocalHost, this.inlineStylesheet = (c = e.inlineStylesheet) != null ? c : this._isOnLocalHost, this.samplingStrategy = u({
      canvasFactor: 0.5,
      canvasMaxSnapshotDimension: 360,
      canvasClearWebGLBuffer: !0,
      dataUrlOptions: ye()
    }, (d = e.samplingStrategy) != null ? d : {
      canvas: 2
    }), this._backendUrl = (p = e == null ? void 0 : e.backendUrl) != null ? p : "https://pub.highlight.io", this._backendUrl[0] === "/" && (this._backendUrl = new URL(this._backendUrl, document.baseURI).href);
    const t = new _e(`${this._backendUrl}`, {
      headers: {}
    });
    this.graphqlSDK = oe(t, Ce(((I = this.sessionData) == null ? void 0 : I.sessionSecureID) || ((b = this.options) == null ? void 0 : b.sessionSecureID))), this.environment = (L = e.environment) != null ? L : "production", this.appVersion = e.appVersion, this.serviceName = (R = e.serviceName) != null ? R : "", typeof e.organizationID == "string" ? this.organizationID = e.organizationID : this.organizationID = e.organizationID.toString(), this.isRunningOnHighlight = this.organizationID === "1" || this.organizationID === "1jdkoe52", this.firstloadVersion = e.firstloadVersion || "unknown", this.sessionShortcut = e.sessionShortcut || !1, this._onToggleFeedbackFormVisibility = () => {
    };
    const k = e, { firstloadVersion: s } = k, n = B(k, ["firstloadVersion"]);
    this._optionsInternal = n, this.listeners = [], this.events = [], this.hasSessionUnloaded = !1, this.hasPushedData = !1, window.Intercom && window.Intercom("onShow", () => {
      window.Intercom("update", {
        highlightSessionURL: this.getCurrentSessionURLWithTimestamp()
      }), this.addProperties({ event: "Intercom onShow" });
    }), this._eventBytesSinceSnapshot = 0, this._lastSnapshotTime = (/* @__PURE__ */ new Date()).getTime(), this._lastVisibilityChangeTime = (/* @__PURE__ */ new Date()).getTime();
  }
  identify(e, t = {}, s) {
    if (!e || e === "") {
      console.warn("Highlight's identify() call was passed an empty identifier.", { user_identifier: e, user_object: t });
      return;
    }
    this.sessionData.userIdentifier = e.toString(), this.sessionData.userObject = t, V(v.USER_IDENTIFIER, e.toString()), V(v.USER_OBJECT, JSON.stringify(t)), this._worker.postMessage({
      message: {
        type: _.Identify,
        userIdentifier: e,
        userObject: t,
        source: s
      }
    });
    for (const n of this._integrations)
      n.identify(this.sessionData.sessionSecureID, e, t, s);
  }
  log(e, t, s) {
    this._firstLoadListeners.messages.push(Pe(t, ze, e, s));
  }
  pushCustomError(e, t) {
    return this.consumeCustomError(new Error(e), void 0, t);
  }
  consumeCustomError(e, t, s) {
    let n = {};
    if (s)
      try {
        n = u(u({}, JSON.parse(s)), n);
      } catch (a) {
      }
    return this.consumeError(e, {
      message: t,
      payload: n
    });
  }
  consumeError(e, { message: t, payload: s, source: n, type: a }) {
    var h, c, d, p;
    e.cause && (s = S(u({}, s), { "exception.cause": e.cause }));
    let i = t ? t + ":" + e.message : e.message;
    a === "React.ErrorBoundary" && (i = "ErrorBoundary: " + i);
    const r = Ne(e), g = {
      event: i,
      type: a != null ? a : "custom",
      url: window.location.href,
      source: n != null ? n : "",
      lineNumber: (h = r[0]) != null && h.lineNumber ? (c = r[0]) == null ? void 0 : c.lineNumber : 0,
      columnNumber: (d = r[0]) != null && d.columnNumber ? (p = r[0]) == null ? void 0 : p.columnNumber : 0,
      stackTrace: r,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      payload: JSON.stringify(s)
    };
    this._firstLoadListeners.errors.push(g);
    for (const I of this._integrations)
      I.error(this.sessionData.sessionSecureID, g);
  }
  addProperties(e = {}, t) {
    const s = u({}, e);
    Object.entries(s).forEach(([n, a]) => {
      try {
        structuredClone(a);
      } catch (i) {
        delete s[n];
      }
    });
    for (const n of this._integrations)
      n.track(this.sessionData.sessionSecureID, u({
        sessionSecureID: this.sessionData.sessionSecureID,
        propertyType: t
      }, e));
    this._worker.postMessage({
      message: {
        type: _.Properties,
        propertiesObject: s,
        propertyType: t
      }
    });
  }
  initialize(e) {
    return D(this, null, function* () {
      var t, s, n, a, i, r, g, h, c;
      if (navigator != null && navigator.webdriver && !window.Cypress || (t = navigator == null ? void 0 : navigator.userAgent) != null && t.includes("Googlebot") || (s = navigator == null ? void 0 : navigator.userAgent) != null && s.includes("AdsBot")) {
        (n = this._firstLoadListeners) == null || n.stopListening();
        return;
      }
      try {
        if (e != null && e.forceNew) {
          yield this._reset(e);
          return;
        }
        this.logger.log("Initializing...", e, this.sessionData, this.options), this.sessionData = (a = J(this.sessionData.sessionSecureID)) != null ? a : this.sessionData, (i = this.sessionData) != null && i.sessionStartTime ? this._recordingStartTime = (r = this.sessionData) == null ? void 0 : r.sessionStartTime : (this._recordingStartTime = (/* @__PURE__ */ new Date()).getTime(), this.sessionData.sessionStartTime = this._recordingStartTime), H(""), T(this.sessionData);
        let d = z(Q.CLIENT_ID);
        d || (d = U(), V(Q.CLIENT_ID, d));
        let p;
        this.options.disableSessionRecording || this.options.disableNetworkRecording !== void 0 || typeof this.options.networkRecording == "boolean" ? p = !1 : p = ((g = this.options.networkRecording) == null ? void 0 : g.recordHeadersAndBody) || !1;
        let I = [];
        if (typeof this.options.networkRecording == "object" && ((h = this.options.networkRecording.destinationDomains) != null && h.length) && (I = this.options.networkRecording.destinationDomains), this._isCrossOriginIframe)
          yield this._setupCrossOriginIframe();
        else {
          const m = yield this.graphqlSDK.initializeSession({
            organization_verbose_id: this.organizationID,
            enable_strict_privacy: this.privacySetting === "strict",
            privacy_setting: this.privacySetting,
            enable_recording_network_contents: p,
            clientVersion: this.firstloadVersion,
            firstloadVersion: this.firstloadVersion,
            clientConfig: JSON.stringify(this._optionsInternal),
            environment: this.environment,
            id: d,
            appVersion: this.appVersion,
            serviceName: this.serviceName,
            session_secure_id: this.sessionData.sessionSecureID,
            client_id: d,
            network_recording_domains: I,
            disable_session_recording: this.options.disableSessionRecording
          });
          if (m.initializeSession.secure_id !== this.sessionData.sessionSecureID && this.logger.log(`Unexpected secure id returned by initializeSession: ${m.initializeSession.secure_id}, expected ${this.sessionData.sessionSecureID}`), this.sessionData.sessionSecureID = m.initializeSession.secure_id, this.sessionData.projectID = parseInt(((c = m == null ? void 0 : m.initializeSession) == null ? void 0 : c.project_id) || "0"), !this.sessionData.projectID || !this.sessionData.sessionSecureID) {
            console.error("Failed to initialize Highlight; an error occurred on our end.", this.sessionData);
            return;
          }
        }
        this.logger.log(`Loaded Highlight
Remote: ${this._backendUrl}
Project ID: ${this.sessionData.projectID}
SessionSecureID: ${this.sessionData.sessionSecureID}`), this.options.sessionSecureID = this.sessionData.sessionSecureID, this._worker.postMessage({
          message: {
            type: _.Initialize,
            sessionSecureID: this.sessionData.sessionSecureID,
            backend: this._backendUrl,
            debug: !!this.debugOptions.clientInteractions,
            recordingStartTime: this._recordingStartTime
          }
        });
        for (const m of this._integrations)
          m.init(this.sessionData.sessionSecureID);
        if (this.sessionData.userIdentifier && this.identify(this.sessionData.userIdentifier, this.sessionData.userObject), this._firstLoadListeners.isListening() ? this._firstLoadListeners.hasNetworkRecording || y.setupNetworkListener(this._firstLoadListeners, this.options) : this._firstLoadListeners.startListening(), this.pushPayloadTimerId && (clearTimeout(this.pushPayloadTimerId), this.pushPayloadTimerId = void 0), this._isCrossOriginIframe || (this.pushPayloadTimerId = setTimeout(() => {
          this._save();
        }, q)), this.options.disableSessionRecording) {
          this.logger.log("Highlight is NOT RECORDING a session replay per H.init setting."), this.ready = !0, this.state = "Recording", this.manualStopped = !1;
          return;
        }
        const { getDeviceDetails: b } = ae();
        b && this.recordGauge({
          name: w.DeviceMemory,
          value: b().deviceMemory,
          category: f.Device,
          group: window.location.href
        });
        const L = (m, ee) => {
          ee && this.logger.log("received isCheckout emit", { event: m }), this.events.push(m);
        };
        L.bind(this);
        const R = !!this._recordStop;
        this._recordStop && (this._recordStop(), this._recordStop = void 0);
        const [k, Z] = ve(this.privacySetting);
        this._recordStop = M({
          ignoreClass: "highlight-ignore",
          blockClass: "highlight-block",
          emit: L,
          recordCrossOriginIframes: this.options.recordCrossOriginIframe,
          privacySetting: this.privacySetting,
          maskAllInputs: k,
          maskInputOptions: Z,
          recordCanvas: this.enableCanvasRecording,
          sampling: {
            canvas: {
              fps: this.samplingStrategy.canvas,
              fpsManual: this.samplingStrategy.canvasManualSnapshot,
              resizeFactor: this.samplingStrategy.canvasFactor,
              clearWebGLBuffer: this.samplingStrategy.canvasClearWebGLBuffer,
              initialSnapshotDelay: this.samplingStrategy.canvasInitialSnapshotDelay,
              dataURLOptions: this.samplingStrategy.dataUrlOptions,
              maxSnapshotDimension: this.samplingStrategy.canvasMaxSnapshotDimension
            }
          },
          keepIframeSrcFn: (m) => !this.options.recordCrossOriginIframe,
          inlineImages: this.inlineImages,
          inlineVideos: this.inlineVideos,
          collectFonts: this.inlineImages,
          inlineStylesheet: this.inlineStylesheet,
          plugins: [Ie()],
          logger: typeof this.options.debug == "boolean" && this.options.debug || typeof this.options.debug == "object" && this.options.debug.domRecording ? {
            debug: this.logger.log,
            warn: E
          } : void 0
        }), R || this.options.recordCrossOriginIframe && this._setupCrossOriginIframeParent(), document.referrer && (window && document.referrer.includes(window.location.origin) || (this.addCustomEvent("Referrer", document.referrer), this.addProperties({ referrer: document.referrer }, { type: "session" }))), this._setupWindowListeners(), this.ready = !0, this.state = "Recording", this.manualStopped = !1;
      } catch (d) {
        this._isOnLocalHost && (console.error(d), E("initializeSession", d));
      }
    });
  }
  _visibilityHandler(e) {
    return D(this, null, function* () {
      if (this.manualStopped) {
        this.logger.log("Ignoring visibility event due to manual stop.");
        return;
      }
      (/* @__PURE__ */ new Date()).getTime() - this._lastVisibilityChangeTime < be || (this._lastVisibilityChangeTime = (/* @__PURE__ */ new Date()).getTime(), this.logger.log(`Detected window ${e ? "hidden" : "visible"}.`), e ? (this.addCustomEvent("TabHidden", !0), this.options.disableBackgroundRecording && this.stopRecording()) : (this.options.disableBackgroundRecording && (yield this.initialize()), this.addCustomEvent("TabHidden", !1)));
    });
  }
  _setupCrossOriginIframe() {
    return D(this, null, function* () {
      this.logger.log("highlight in cross-origin iframe is waiting "), yield new Promise((e) => {
        const t = (s) => {
          if (s.data.highlight === j) {
            const n = s.data;
            this.logger.log("highlight got window message ", n), this.sessionData.projectID = n.projectID, this.sessionData.sessionSecureID = n.sessionSecureID, window.parent.postMessage({
              highlight: W
            }, "*"), window.removeEventListener("message", t), e();
          }
        };
        window.addEventListener("message", t);
      });
    });
  }
  _setupCrossOriginIframeParent() {
    this.logger.log("highlight setting up cross origin iframe parent notification"), setInterval(() => {
      window.document.querySelectorAll("iframe").forEach((e) => {
        var t;
        (t = e.contentWindow) == null || t.postMessage({
          highlight: j,
          projectID: this.sessionData.projectID,
          sessionSecureID: this.sessionData.sessionSecureID
        }, "*");
      });
    }, q), window.addEventListener("message", (e) => {
      e.data.highlight === W && this.logger.log("highlight got response from initialized iframe");
    });
  }
  _setupWindowListeners() {
    var s;
    try {
      const n = this;
      this.enableSegmentIntegration && this.listeners.push(re((i) => {
        if (i.type === "track") {
          const r = {};
          r["segment-event"] = i.event, n.addProperties(r, {
            type: "track",
            source: "segment"
          });
        } else if (i.type === "identify") {
          const r = i.userId.replace(/^"(.*)"$/, "$1");
          n.identify(r, i.traits, "segment");
        }
      })), this.listeners.push(he((i) => {
        this.reloaded ? (this.addCustomEvent("Reload", i), this.reloaded = !1, n.addProperties({ reload: !0 }, { type: "session" })) : this.addCustomEvent("Navigate", i);
      })), this.listeners.push(ge((i) => {
        this.addCustomEvent("Viewport", i), this.submitViewportMetrics(i);
      })), this.listeners.push(le((i, r) => {
        let g = null, h = null;
        if (r && r.target) {
          const c = r.target;
          g = Oe(c), h = c.textContent, h && h.length > 2e3 && (h = h.substring(0, 2e3));
        }
        this.addCustomEvent("Click", {
          clickTarget: i,
          clickTextContent: h,
          clickSelector: g
        });
      })), this.listeners.push(ce((i) => {
        i && this.addCustomEvent("Focus", i);
      })), this.listeners.push(de((i) => {
        const { name: r, value: g } = i;
        this.recordGauge({
          name: r,
          value: g,
          group: window.location.href,
          category: f.WebVital
        });
      })), this.listeners.push(ue((i) => {
        const r = [];
        i.saveData !== void 0 && r.push({
          name: "saveData",
          value: i.saveData.toString()
        }), i.effectiveType !== void 0 && r.push({
          name: "effectiveType",
          value: i.effectiveType.toString()
        }), i.type !== void 0 && r.push({
          name: "type",
          value: i.type.toString()
        }), Object.entries(i).forEach(([g, h]) => h && typeof h == "number" && this.recordGauge({
          name: g,
          value: h,
          category: f.Performance,
          group: window.location.href,
          tags: r
        }));
      }, this._recordingStartTime)), this.sessionShortcut && pe(this.sessionShortcut, () => {
        window.open(this.getCurrentSessionURLWithTimestamp(), "_blank");
      }), this.enablePerformanceRecording && (this.listeners.push(Me((i) => {
        this.addCustomEvent("Performance", $(i)), Object.entries(i).filter(([r]) => r !== "relativeTimestamp").forEach(([r, g]) => g && this.recordGauge({
          name: r,
          value: g,
          category: f.Performance,
          group: window.location.href
        }));
      }, this._recordingStartTime)), this.listeners.push(Ue((i) => {
        this.addCustomEvent("Jank", $(i)), this.recordGauge({
          name: "Jank",
          value: i.jankAmount,
          category: f.WebVital,
          group: i.querySelector
        });
      }, this._recordingStartTime))), this._hasPreviouslyInitialized || ((s = window.electron) != null && s.ipcRenderer ? (window.electron.ipcRenderer.on("highlight.run", ({ visible: i }) => {
        this._visibilityHandler(!i);
      }), this.logger.log("Set up Electron highlight.run events.")) : (me((i) => this._visibilityHandler(i)), this.logger.log("Set up document visibility listener.")), this._hasPreviouslyInitialized = !0);
      const a = () => {
        this.hasSessionUnloaded = !0, this.pushPayloadTimerId && (clearTimeout(this.pushPayloadTimerId), this.pushPayloadTimerId = void 0);
      };
      window.addEventListener("beforeunload", a), this.listeners.push(() => window.removeEventListener("beforeunload", a));
    } catch (n) {
      this._isOnLocalHost && (console.error(n), E("initializeSession _setupWindowListeners", n));
    }
    const e = () => {
      this.addCustomEvent("Page Unload", ""), H(this.sessionData.sessionSecureID), T(this.sessionData);
    };
    if (window.addEventListener("beforeunload", e), this.listeners.push(() => window.removeEventListener("beforeunload", e)), navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i)) {
      const n = () => {
        this.addCustomEvent("Page Unload", ""), H(this.sessionData.sessionSecureID), T(this.sessionData);
      };
      window.addEventListener("pagehide", n), this.listeners.push(() => window.removeEventListener("beforeunload", n));
    }
  }
  submitViewportMetrics({ height: e, width: t, availHeight: s, availWidth: n }) {
    this.recordGauge({
      name: w.ViewportHeight,
      value: e,
      category: f.Device,
      group: window.location.href
    }), this.recordGauge({
      name: w.ViewportWidth,
      value: t,
      category: f.Device,
      group: window.location.href
    }), this.recordGauge({
      name: w.ScreenHeight,
      value: s,
      category: f.Device,
      group: window.location.href
    }), this.recordGauge({
      name: w.ScreenWidth,
      value: n,
      category: f.Device,
      group: window.location.href
    }), this.recordGauge({
      name: w.ViewportArea,
      value: e * t,
      category: f.Device,
      group: window.location.href
    });
  }
  recordGauge(e) {
    var n;
    const t = O.getMeter(P);
    let s = this._gauges.get(e.name);
    s || (s = t.createGauge(e.name), this._gauges.set(e.name, s)), s.record(e.value, S(u({}, (n = e.tags) == null ? void 0 : n.reduce((a, i) => S(u({}, a), { [i.name]: i.value }), {})), {
      group: e.group,
      category: e.category,
      "highlight.session_id": this.sessionData.sessionSecureID
    }));
    for (const a of this._integrations)
      a.recordGauge(this.sessionData.sessionSecureID, e);
  }
  recordCount(e) {
    var n;
    const t = O.getMeter(P);
    let s = this._counters.get(e.name);
    s || (s = t.createCounter(e.name), this._counters.set(e.name, s)), s.add(e.value, S(u({}, (n = e.tags) == null ? void 0 : n.reduce((a, i) => S(u({}, a), { [i.name]: i.value }), {})), {
      group: e.group,
      category: e.category,
      "highlight.session_id": this.sessionData.sessionSecureID
    }));
  }
  recordIncr(e) {
    this.recordCount(S(u({}, e), { value: 1 }));
  }
  recordHistogram(e) {
    var n;
    const t = O.getMeter(P);
    let s = this._histograms.get(e.name);
    s || (s = t.createHistogram(e.name), this._histograms.set(e.name, s)), s.record(e.value, S(u({}, (n = e.tags) == null ? void 0 : n.reduce((a, i) => S(u({}, a), { [i.name]: i.value }), {})), {
      group: e.group,
      category: e.category,
      "highlight.session_id": this.sessionData.sessionSecureID
    }));
  }
  recordUpDownCounter(e) {
    var n;
    const t = O.getMeter(P);
    let s = this._up_down_counters.get(e.name);
    s || (s = t.createUpDownCounter(e.name), this._up_down_counters.set(e.name, s)), s.add(e.value, S(u({}, (n = e.tags) == null ? void 0 : n.reduce((a, i) => S(u({}, a), { [i.name]: i.value }), {})), {
      group: e.group,
      category: e.category,
      "highlight.session_id": this.sessionData.sessionSecureID
    }));
  }
  /**
   * Stops Highlight from recording.
   * @param manual The end user requested to stop recording.
   */
  stopRecording(e) {
    this.manualStopped = !!e, this.manualStopped && this.addCustomEvent("Stop", "H.stop() was called which stops Highlight from recording."), this.state = "NotRecording", e && this._recordStop && (this._recordStop(), this._recordStop = void 0), this.listeners.forEach((t) => t()), this.listeners = [];
  }
  getCurrentSessionTimestamp() {
    return this._recordingStartTime;
  }
  /**
   * Returns the current timestamp for the current session.
   */
  getCurrentSessionURLWithTimestamp() {
    const e = (/* @__PURE__ */ new Date()).getTime(), { projectID: t, sessionSecureID: s } = this.sessionData, n = (e - this._recordingStartTime) / 1e3;
    return `https://${K}/${t}/sessions/${s}?ts=${n}`;
  }
  getCurrentSessionURL() {
    const e = this.sessionData.projectID, t = this.sessionData.sessionSecureID;
    return e && t ? `https://${K}/${e}/sessions/${t}` : null;
  }
  snapshot(e) {
    return D(this, null, function* () {
      yield M.snapshotCanvas(e);
    });
  }
  addSessionFeedback({ timestamp: e, verbatim: t, user_email: s, user_name: n }) {
    var a;
    this._worker.postMessage({
      message: {
        type: _.Feedback,
        verbatim: t,
        timestamp: e,
        userName: n || this.sessionData.userIdentifier,
        userEmail: s || ((a = this.sessionData.userObject) == null ? void 0 : a.name)
      }
    });
  }
  // Reset the events array and push to a backend.
  _save() {
    return D(this, null, function* () {
      var e;
      try {
        this.state === "Recording" && this.listeners && this.sessionData.sessionStartTime && Date.now() - this.sessionData.sessionStartTime > Le && (this.logger.log("Resetting session", {
          start: this.sessionData.sessionStartTime
        }), yield this._reset({}));
        let t;
        ((e = this.options) == null ? void 0 : e.sendMode) === "local" && (t = (s) => D(this, null, function* () {
          let n = new Blob([
            JSON.stringify({
              query: De(we),
              variables: s
            })
          ], {
            type: "application/json"
          });
          return yield window.fetch(`${this._backendUrl}`, {
            method: "POST",
            body: n
          }), 0;
        })), yield this._sendPayload({ sendFn: t }), this.hasPushedData = !0, this.sessionData.lastPushTime = Date.now(), T(this.sessionData);
      } catch (t) {
        this._isOnLocalHost && (console.error(t), E("_save", t));
      }
      this.state === "Recording" && (this.pushPayloadTimerId && (clearTimeout(this.pushPayloadTimerId), this.pushPayloadTimerId = void 0), this.pushPayloadTimerId = setTimeout(() => {
        this._save();
      }, Te));
    });
  }
  /**
   * This proxy should be used instead of rrweb's native addCustomEvent.
   * The proxy makes sure recording has started before emitting a custom event.
   */
  addCustomEvent(e, t) {
    if (this.state === "NotRecording") {
      let s;
      const n = () => {
        clearInterval(s), this.state === "Recording" && this.events.length > 0 ? A(e, t) : s = setTimeout(n, 500);
      };
      s = setTimeout(n, 500);
    } else this.state === "Recording" && (this.events.length > 0 || this.hasPushedData) && A(e, t);
  }
  _sendPayload(t) {
    return D(this, arguments, function* ({ sendFn: e }) {
      const s = y.getRecordedNetworkResources(this._firstLoadListeners, this._recordingStartTime), n = y.getRecordedWebSocketEvents(this._firstLoadListeners), a = [...this.events], i = [...this._firstLoadListeners.messages], r = [...this._firstLoadListeners.errors], { bytes: g, time: h } = this.enableCanvasRecording ? Y.canvas : Y.normal;
      this._eventBytesSinceSnapshot >= g && (/* @__PURE__ */ new Date()).getTime() - this._lastSnapshotTime >= h && this.takeFullSnapshot(), this.logger.log(`Sending: ${a.length} events, ${i.length} messages, ${s.length} network resources, ${r.length} errors 
To: ${this._backendUrl}
Org: ${this.organizationID}
SessionSecureID: ${this.sessionData.sessionSecureID}`);
      const c = Se();
      e ? yield e({
        session_secure_id: this.sessionData.sessionSecureID,
        payload_id: (this.sessionData.payloadID++).toString(),
        events: { events: a },
        messages: $({ messages: i }),
        resources: JSON.stringify({ resources: s }),
        web_socket_events: JSON.stringify({
          webSocketEvents: n
        }),
        errors: r,
        is_beacon: !1,
        has_session_unloaded: this.hasSessionUnloaded,
        highlight_logs: c || void 0
      }) : this._worker.postMessage({
        message: {
          type: _.AsyncEvents,
          id: this.sessionData.payloadID++,
          events: a,
          messages: i,
          errors: r,
          resourcesString: JSON.stringify({ resources: s }),
          webSocketEventsString: JSON.stringify({
            webSocketEvents: n
          }),
          hasSessionUnloaded: this.hasSessionUnloaded,
          highlightLogs: c
        }
      }), T(this.sessionData), y.clearRecordedNetworkResources(this._firstLoadListeners), this.events = this.events.slice(a.length), this._firstLoadListeners.messages = this._firstLoadListeners.messages.slice(i.length), this._firstLoadListeners.errors = this._firstLoadListeners.errors.slice(r.length), fe(c);
    });
  }
  takeFullSnapshot() {
    if (!this._recordStop) {
      this.logger.log("skipping full snapshot as rrweb is not running");
      return;
    }
    this.logger.log("taking full snapshot", {
      bytesSinceSnapshot: this._eventBytesSinceSnapshot,
      lastSnapshotTime: this._lastSnapshotTime
    }), M.takeFullSnapshot(), this._eventBytesSinceSnapshot = 0, this._lastSnapshotTime = (/* @__PURE__ */ new Date()).getTime();
  }
  registerLD(e) {
    this._integrations.length || this._integrations.push(new Ee(e));
  }
}
export {
  U as GenerateSecureID,
  X as Highlight,
  E as HighlightWarning,
  f as MetricCategory,
  J as getPreviousSessionData,
  Je as getTracer,
  xe as setupBrowserTracing
};
//# sourceMappingURL=index-CBVb9hsF.js.map
