var Fe = Object.defineProperty, $e = Object.defineProperties;
var Ve = Object.getOwnPropertyDescriptors;
var F = Object.getOwnPropertySymbols;
var ue = Object.prototype.hasOwnProperty, me = Object.prototype.propertyIsEnumerable;
var x = (i, e, t) => e in i ? Fe(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t, p = (i, e) => {
  for (var t in e || (e = {}))
    ue.call(e, t) && x(i, t, e[t]);
  if (F)
    for (var t of F(e))
      me.call(e, t) && x(i, t, e[t]);
  return i;
}, y = (i, e) => $e(i, Ve(e));
var A = (i, e) => {
  var t = {};
  for (var s in i)
    ue.call(i, s) && e.indexOf(s) < 0 && (t[s] = i[s]);
  if (i != null && F)
    for (var s of F(i))
      e.indexOf(s) < 0 && me.call(i, s) && (t[s] = i[s]);
  return t;
};
var a = (i, e, t) => x(i, typeof e != "symbol" ? e + "" : e, t);
var R = (i, e, t) => new Promise((s, n) => {
  var o = (d) => {
    try {
      c(t.next(d));
    } catch (l) {
      n(l);
    }
  }, r = (d) => {
    try {
      c(t.throw(d));
    } catch (l) {
      n(l);
    }
  }, c = (d) => d.done ? s(d.value) : Promise.resolve(d.value).then(o, r);
  c((t = t.apply(i, e)).next());
});
import { W as Ke, M as C, r as q, I as fe, a as we, S as xe, P as Ae, C as qe, F as Ge, b as je, c as Je, d as pe, g as Qe, p as Ye, e as Xe, f as Ze, h as et, s as tt, i as st } from "./record-CwjMoD8S.js";
import { R as Xt } from "./record-CwjMoD8S.js";
import { A as it, s as V, G as N, g as M, S as L, r as Se, a as G, b as nt, c as rt, d as j, e as J, f as U, F as ye, M as D, h as E, V as ot, i as at, H as Q, j as ct, k as lt, L as Ee, l as Ne, p as dt, m as be, n as ke, o as ht, q as gt, t as ut, u as mt, v as ft, P as wt, w as pt, x as St, y as yt } from "./common-CIyV2J2L.js";
import { X as bt, F as kt, C as vt, E as Rt, s as Oe, D as _t, a as Dt, m as ve, d as Te, b as Re, c as _e, r as He, e as It, p as Ct, f as Lt, g as Et, h as Nt, W as Ot, N as Tt, P as Ht, J as Pt, i as $, j as Ut, k as De, l as Ie } from "./observe-BoZQPYHR.js";
import { O as es } from "./observe-BoZQPYHR.js";
import { L as Wt } from "./buffer-DIFxvF2Q.js";
import { LDObserve as ss } from "./LDObserve.js";
import { LDRecord as ns } from "./LDRecord.js";
const zt = (i, e, t) => {
  const s = window._highlightWebSocketRequestCallback;
  window._highlightWebSocketRequestCallback = i;
  const n = window._highlightWebSocketEventCallback;
  return window._highlightWebSocketEventCallback = (o) => {
    const g = o, { message: r, size: c } = g, d = A(g, ["message", "size"]), h = t.some(
      (m) => o.name.toLowerCase().includes(m)
    ) ? d : o;
    e(h);
  }, () => {
    window._highlightWebSocketRequestCallback = s, window._highlightWebSocketEventCallback = n;
  };
}, Bt = ({
  xhrCallback: i,
  fetchCallback: e,
  webSocketRequestCallback: t,
  webSocketEventCallback: s,
  disableWebSocketRecording: n,
  bodyKeysToRedact: o,
  highlightEndpoints: r,
  tracingOrigins: c,
  urlBlocklist: d,
  bodyKeysToRecord: l
}) => {
  const h = bt(
    i,
    r,
    c,
    d,
    o,
    l
  ), g = kt(
    e,
    r,
    c,
    d,
    o,
    l
  ), m = n ? () => {
  } : zt(
    t,
    s,
    d
  );
  return () => {
    h(), g(), m();
  };
};
class I {
  constructor(e) {
    a(this, "disableConsoleRecording");
    a(this, "reportConsoleErrors");
    a(this, "enablePromisePatch");
    a(this, "consoleMethodsToRecord");
    a(this, "listeners");
    a(this, "errors");
    a(this, "messages");
    // The properties below were added in 4.0.0 (Feb 2022), and are patched in by client via setupNetworkListeners()
    a(this, "options");
    a(this, "hasNetworkRecording", !0);
    a(this, "disableNetworkRecording");
    a(this, "enableRecordingNetworkContents");
    a(this, "xhrNetworkContents");
    a(this, "fetchNetworkContents");
    a(this, "disableRecordingWebSocketContents");
    a(this, "webSocketNetworkContents");
    a(this, "webSocketEventContents");
    a(this, "tracingOrigins");
    a(this, "networkHeadersToRedact");
    a(this, "networkBodyKeysToRedact");
    a(this, "networkBodyKeysToRecord");
    a(this, "networkHeaderKeysToRecord");
    a(this, "lastNetworkRequestTimestamp");
    a(this, "urlBlocklist");
    a(this, "highlightEndpoints");
    a(this, "requestResponseSanitizer");
    var t, s;
    this.options = e, this.disableConsoleRecording = !!e.disableConsoleRecording, this.reportConsoleErrors = (t = e.reportConsoleErrors) != null ? t : !1, this.enablePromisePatch = (s = e.enablePromisePatch) != null ? s : !1, this.consoleMethodsToRecord = e.consoleMethodsToRecord || [
      ...it
    ], this.listeners = [], this.errors = [], this.messages = [], this.lastNetworkRequestTimestamp = 0;
  }
  isListening() {
    return this.listeners.length > 0;
  }
  startListening() {
    if (this.isListening()) return;
    const e = this;
    this.disableConsoleRecording || this.listeners.push(
      vt(
        (t) => {
          var s, n, o;
          if (this.reportConsoleErrors && (t.type === "Error" || t.type === "error") && t.value && t.trace) {
            const r = V(t.value);
            if (Re.includes(r) || _e.some(
              (c) => r.includes(c)
            ))
              return;
            e.errors.push({
              event: r,
              type: "console.error",
              url: window.location.href,
              source: (s = t.trace[0]) != null && s.fileName ? t.trace[0].fileName : "",
              lineNumber: (n = t.trace[0]) != null && n.lineNumber ? t.trace[0].lineNumber : 0,
              columnNumber: (o = t.trace[0]) != null && o.columnNumber ? t.trace[0].columnNumber : 0,
              stackTrace: t.trace,
              timestamp: (/* @__PURE__ */ new Date()).toISOString(),
              id: He()
            });
          }
          e.messages.push(t);
        },
        y(p({}, Te), {
          level: this.consoleMethodsToRecord
        })
      )
    ), this.listeners.push(
      Rt(
        (t) => {
          Re.includes(t.event) || _e.some(
            (s) => t.event.includes(s)
          ) || e.errors.push(t);
        },
        { enablePromisePatch: this.enablePromisePatch }
      )
    ), this.listeners.push(Oe), I.setupNetworkListener(this, this.options);
  }
  stopListening() {
    this.listeners.forEach((e) => e()), this.listeners = [];
  }
  // We define this as a static method because versions earlier than 4.0.0 (Feb 2022) don't have this code.
  // For those versions, calling this from client will monkey-patch the network listeners onto the old FirstLoadListener object.
  static setupNetworkListener(e, t) {
    var o, r, c, d, l, h, g, m, f, _, k, O;
    const s = (t == null ? void 0 : t.backendUrl) || void 0 || "https://pub.highlight.io", n = t.otlpEndpoint || "https://otel.highlight.io";
    e.highlightEndpoints = [
      s,
      `${n}/v1/traces`,
      `${n}/v1/logs`,
      `${n}/v1/metrics`
    ], e.xhrNetworkContents = [], e.fetchNetworkContents = [], e.webSocketNetworkContents = [], e.webSocketEventContents = [], e.networkHeadersToRedact = [], e.urlBlocklist = [], e.tracingOrigins = t.tracingOrigins || [], (t == null ? void 0 : t.disableNetworkRecording) !== void 0 ? (e.disableNetworkRecording = t == null ? void 0 : t.disableNetworkRecording, e.enableRecordingNetworkContents = !1, e.disableRecordingWebSocketContents = !0, e.networkHeadersToRedact = [], e.networkBodyKeysToRedact = [], e.urlBlocklist = [], e.networkBodyKeysToRecord = []) : typeof (t == null ? void 0 : t.networkRecording) == "boolean" ? (e.disableNetworkRecording = !t.networkRecording, e.enableRecordingNetworkContents = !1, e.disableRecordingWebSocketContents = !0, e.networkHeadersToRedact = [], e.networkBodyKeysToRedact = [], e.urlBlocklist = []) : (((o = t.networkRecording) == null ? void 0 : o.enabled) !== void 0 ? e.disableNetworkRecording = !t.networkRecording.enabled : e.disableNetworkRecording = !1, e.enableRecordingNetworkContents = ((r = t.networkRecording) == null ? void 0 : r.recordHeadersAndBody) || !1, e.disableRecordingWebSocketContents = ((c = t.networkRecording) == null ? void 0 : c.disableWebSocketEventRecordings) || !1, e.networkHeadersToRedact = ((l = (d = t.networkRecording) == null ? void 0 : d.networkHeadersToRedact) == null ? void 0 : l.map(
      (S) => S.toLowerCase()
    )) || [], e.networkBodyKeysToRedact = ((g = (h = t.networkRecording) == null ? void 0 : h.networkBodyKeysToRedact) == null ? void 0 : g.map(
      (S) => S.toLowerCase()
    )) || [], e.urlBlocklist = ((f = (m = t.networkRecording) == null ? void 0 : m.urlBlocklist) == null ? void 0 : f.map(
      (S) => S.toLowerCase()
    )) || [], e.urlBlocklist = [
      ...e.urlBlocklist,
      ..._t
    ], e.requestResponseSanitizer = (_ = t.networkRecording) == null ? void 0 : _.requestResponseSanitizer, e.networkHeaderKeysToRecord = (k = t.networkRecording) == null ? void 0 : k.headerKeysToRecord, e.networkHeaderKeysToRecord && (e.networkHeadersToRedact = [], e.networkHeaderKeysToRecord = e.networkHeaderKeysToRecord.map(
      (S) => S.toLocaleLowerCase()
    )), e.networkBodyKeysToRecord = (O = t.networkRecording) == null ? void 0 : O.bodyKeysToRecord, e.networkBodyKeysToRecord && (e.networkBodyKeysToRedact = [], e.networkBodyKeysToRecord = e.networkBodyKeysToRecord.map(
      (S) => S.toLocaleLowerCase()
    ))), !e.disableNetworkRecording && e.enableRecordingNetworkContents && e.listeners.push(
      Bt({
        xhrCallback: (S) => {
          e.xhrNetworkContents.push(S);
        },
        fetchCallback: (S) => {
          e.fetchNetworkContents.push(S);
        },
        webSocketRequestCallback: (S) => {
          e.webSocketNetworkContents && e.webSocketNetworkContents.push(S);
        },
        webSocketEventCallback: (S) => {
          e.webSocketEventContents.push(S);
        },
        disableWebSocketRecording: e.disableRecordingWebSocketContents,
        bodyKeysToRedact: e.networkBodyKeysToRedact,
        highlightEndpoints: e.highlightEndpoints,
        tracingOrigins: e.tracingOrigins,
        urlBlocklist: e.urlBlocklist,
        bodyKeysToRecord: e.networkBodyKeysToRecord
      })
    );
  }
  static getRecordedNetworkResources(e, t) {
    var o, r;
    let s = [], n = [];
    if (!e.disableNetworkRecording) {
      const c = ((o = window == null ? void 0 : window.performance) == null ? void 0 : o.timeOrigin) || 0;
      s = performance.getEntriesByType(
        "resource"
      );
      const d = (t - c) * 2;
      if (s = s.filter((l) => l.responseEnd < e.lastNetworkRequestTimestamp ? !1 : Dt(
        l.name,
        e.highlightEndpoints
      )).map((l) => y(p({}, l.toJSON()), {
        offsetStartTime: l.startTime - d,
        offsetResponseEnd: l.responseEnd - d,
        offsetFetchStart: l.fetchStart - d
      })), e.lastNetworkRequestTimestamp = ((r = s.at(-1)) == null ? void 0 : r.responseEnd) || e.lastNetworkRequestTimestamp, e.enableRecordingNetworkContents) {
        const l = {
          headersToRedact: e.networkHeadersToRedact,
          headersToRecord: e.networkHeaderKeysToRecord,
          requestResponseSanitizer: e.requestResponseSanitizer
        };
        s = ve(
          s,
          e.xhrNetworkContents,
          "xmlhttprequest",
          l
        ), s = ve(
          s,
          e.fetchNetworkContents,
          "fetch",
          l
        );
      }
    }
    return e.disableRecordingWebSocketContents || (n = e.webSocketNetworkContents || []), [...s, ...n];
  }
  static getRecordedWebSocketEvents(e) {
    let t = [];
    return !e.disableNetworkRecording && !e.disableRecordingWebSocketContents && (t = e.webSocketEventContents), t;
  }
  static clearRecordedNetworkResources(e) {
    e.disableNetworkRecording || (e.xhrNetworkContents = [], e.fetchNetworkContents = [], e.webSocketNetworkContents = [], e.webSocketEventContents = [], performance.clearResourceTimings());
  }
}
const W = (i, e) => {
  console.warn(`Highlight Warning: (${i}): `, { output: e });
};
class X {
  constructor(e, t) {
    a(this, "options");
    /** Determines if the client is running on a Highlight property (e.g. frontend). */
    a(this, "isRunningOnHighlight");
    /** Verbose project ID that is exposed to users. Legacy users may still be using ints. */
    a(this, "organizationID");
    a(this, "graphqlSDK");
    a(this, "events");
    a(this, "sessionData");
    a(this, "ready");
    a(this, "manualStopped");
    a(this, "state");
    a(this, "logger");
    a(this, "enableSegmentIntegration");
    a(this, "privacySetting");
    a(this, "enableCanvasRecording");
    a(this, "enablePerformanceRecording");
    a(this, "samplingStrategy");
    a(this, "inlineImages");
    a(this, "inlineVideos");
    a(this, "inlineStylesheet");
    a(this, "debugOptions");
    a(this, "listeners");
    a(this, "firstloadVersion");
    a(this, "environment");
    a(this, "sessionShortcut");
    /** The end-user's app version. This isn't Highlight's version. */
    a(this, "appVersion");
    a(this, "serviceName");
    a(this, "_worker");
    a(this, "_optionsInternal");
    a(this, "_backendUrl");
    a(this, "_recordingStartTime");
    a(this, "_isOnLocalHost");
    a(this, "_onToggleFeedbackFormVisibility");
    a(this, "_firstLoadListeners");
    a(this, "_isCrossOriginIframe");
    a(this, "_eventBytesSinceSnapshot");
    a(this, "_lastSnapshotTime");
    a(this, "_lastVisibilityChangeTime");
    a(this, "pushPayloadTimerId");
    a(this, "hasSessionUnloaded");
    a(this, "hasPushedData");
    a(this, "reloaded");
    a(this, "_hasPreviouslyInitialized");
    a(this, "_recordStop");
    a(this, "_gauges", /* @__PURE__ */ new Map());
    a(this, "_counters", /* @__PURE__ */ new Map());
    a(this, "_histograms", /* @__PURE__ */ new Map());
    a(this, "_up_down_counters", /* @__PURE__ */ new Map());
    a(this, "_integrations", []);
    var n, o, r, c, d;
    e.sessionSecureID || (e.sessionSecureID = N()), this.options = e, typeof ((n = this.options) == null ? void 0 : n.debug) == "boolean" ? this.debugOptions = this.options.debug ? { clientInteractions: !0 } : {} : this.debugOptions = (r = (o = this.options) == null ? void 0 : o.debug) != null ? r : {}, this.logger = new Wt(this.debugOptions.clientInteractions), e.storageMode && (this.logger.log(
      `initializing in ${e.storageMode} session mode`
    ), ht(e.storageMode)), Ne(!!(e != null && e.sessionCookie)), this._worker = new Ke(), this._worker.onmessage = (l) => {
      var h, g, m;
      ((h = l.data.response) == null ? void 0 : h.type) === C.AsyncEvents ? (this._eventBytesSinceSnapshot += l.data.response.eventsSize, this.logger.log(
        `Web worker sent payloadID ${l.data.response.id} size ${l.data.response.eventsSize} bytes, compression ratio ${l.data.response.eventsSize / l.data.response.compressedSize}.
                Total since snapshot: ${(this._eventBytesSinceSnapshot / 1e6).toFixed(1)}MB`
      )) : ((g = l.data.response) == null ? void 0 : g.type) === C.CustomEvent ? this.addCustomEvent(
        l.data.response.tag,
        l.data.response.payload
      ) : ((m = l.data.response) == null ? void 0 : m.type) === C.Stop && (W(
        "Stopping recording due to worker failure",
        l.data.response
      ), this.stopRecording(!1));
    };
    let s = M();
    if (this.reloaded = !1, !((c = this.sessionData) != null && c.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 l of Object.values(L))
        Se(l);
      this.sessionData = {
        sessionSecureID: this.options.sessionSecureID,
        projectID: 0,
        sessionStartTime: Date.now()
      };
    }
    this._hasPreviouslyInitialized = !1, this._firstLoadListeners = t || new I(this.options);
    try {
      window.parent.document && (this._isCrossOriginIframe = !1);
    } catch (l) {
      this._isCrossOriginIframe = (d = this.options.recordCrossOriginIframe) != null ? d : !0;
    }
    this._initMembers(this.options);
  }
  static create(e) {
    return new X(e);
  }
  // Start a new session
  _reset(s) {
    return R(this, arguments, function* ({
      forceNew: e,
      sessionKey: t
    }) {
      this.pushPayloadTimerId && (clearTimeout(this.pushPayloadTimerId), this.pushPayloadTimerId = void 0);
      let n, o;
      if (!e)
        try {
          n = G(L.USER_IDENTIFIER);
          const r = G(
            L.USER_OBJECT
          );
          r && (o = JSON.parse(r));
        } catch (r) {
        }
      for (const r of Object.values(L))
        Se(r);
      this.sessionData.sessionSecureID = t ? N(`${this.organizationID}-${t}`) : N(), this.sessionData.sessionKey = t, this.sessionData.sessionStartTime = Date.now(), this.options.sessionSecureID = this.sessionData.sessionSecureID, this.stopRecording(), this._firstLoadListeners = new I(this.options), yield this.initialize(), n && o && this.identify(n, o);
    });
  }
  _initMembers(e) {
    var o, r, c, d, l, h, g, m, f, _;
    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 = (o = e.privacySetting) != null ? o : "default", this.enableCanvasRecording = (r = e.enableCanvasRecording) != null ? r : !1, this.enablePerformanceRecording = (c = e.enablePerformanceRecording) != null ? c : !0, this.inlineImages = (d = e.inlineImages) != null ? d : this._isOnLocalHost, this.inlineVideos = (l = e.inlineVideos) != null ? l : this._isOnLocalHost, this.inlineStylesheet = (h = e.inlineStylesheet) != null ? h : this._isOnLocalHost, this.samplingStrategy = p({
      canvasFactor: 0.5,
      canvasMaxSnapshotDimension: 360,
      canvasClearWebGLBuffer: !0,
      dataUrlOptions: nt()
    }, (g = e.samplingStrategy) != null ? g : {
      canvas: 2
    }), this._backendUrl = (m = e == null ? void 0 : e.backendUrl) != null ? m : "https://pub.highlight.io", this._backendUrl[0] === "/" && (this._backendUrl = new URL(this._backendUrl, document.baseURI).href);
    const t = new ut(`${this._backendUrl}`, {
      headers: {}
    });
    this.graphqlSDK = rt(t, gt()), this.environment = (f = e.environment) != null ? f : "production", this.appVersion = e.appVersion, this.serviceName = (_ = e.serviceName) != null ? _ : "", 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 = A(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, j(
      L.USER_IDENTIFIER,
      e.toString()
    ), j(L.USER_OBJECT, JSON.stringify(t)), this._worker.postMessage({
      message: {
        type: C.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(
      It(t, Te, e, s)
    );
  }
  pushCustomError(e, t) {
    return this.consumeCustomError(new Error(e), void 0, t);
  }
  consumeCustomError(e, t, s) {
    let n = {};
    if (s)
      try {
        n = p(p({}, JSON.parse(s)), n);
      } catch (o) {
      }
    return this.consumeError(e, {
      message: t,
      payload: n
    });
  }
  consumeError(e, {
    message: t,
    payload: s,
    source: n,
    type: o
  }) {
    var l, h, g, m;
    e.cause && (s = y(p({}, s), { "exception.cause": e.cause }));
    let r = t ? t + ":" + e.message : e.message;
    o === "React.ErrorBoundary" && (r = "ErrorBoundary: " + r);
    const c = Ct(e), d = {
      event: r,
      type: o != null ? o : "custom",
      url: window.location.href,
      source: n != null ? n : "",
      lineNumber: (l = c[0]) != null && l.lineNumber ? (h = c[0]) == null ? void 0 : h.lineNumber : 0,
      columnNumber: (g = c[0]) != null && g.columnNumber ? (m = c[0]) == null ? void 0 : m.columnNumber : 0,
      stackTrace: c,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      payload: JSON.stringify(s),
      id: He()
    };
    this._firstLoadListeners.errors.push(d);
    for (const f of this._integrations)
      f.error(this.sessionData.sessionSecureID, d);
  }
  addProperties(e = {}, t) {
    const s = p({}, e);
    Object.entries(s).forEach(([n, o]) => {
      try {
        structuredClone(o);
      } catch (r) {
        delete s[n];
      }
    }), this._worker.postMessage({
      message: {
        type: C.Properties,
        propertiesObject: s,
        propertyType: t
      }
    });
    for (const n of this._integrations)
      n.track(this.sessionData.sessionSecureID, p({
        sessionSecureID: this.sessionData.sessionSecureID,
        propertyType: t
      }, e));
  }
  initialize(e) {
    return R(this, null, function* () {
      var t, s, n, o, r, c, d, l, h, g, m, f, _, k, O, S, Z, ee, te, se, ie, ne, re, oe, ae, ce, le;
      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;
        }
        if (e != null && e.sessionKey && (e == null ? void 0 : e.sessionKey) !== this.sessionData.sessionKey) {
          yield this._reset(y(p({}, e), { forceNew: !0 }));
          return;
        }
        const T = new Et();
        Lt(
          {
            backendUrl: (r = (o = this.options) == null ? void 0 : o.backendUrl) != null ? r : "https://pub.highlight.io",
            otlpEndpoint: (d = (c = this.options) == null ? void 0 : c.otlpEndpoint) != null ? d : "https://otel.highlight.io",
            projectId: (l = this.options) == null ? void 0 : l.organizationID,
            sessionSecureId: (h = this.options) == null ? void 0 : h.sessionSecureID,
            environment: (m = (g = this.options) == null ? void 0 : g.environment) != null ? m : "production",
            networkRecordingOptions: typeof ((f = this.options) == null ? void 0 : f.networkRecording) == "object" ? this.options.networkRecording : void 0,
            tracingOrigins: (_ = this.options) == null ? void 0 : _.tracingOrigins,
            serviceName: (O = (k = this.options) == null ? void 0 : k.serviceName) != null ? O : "highlight-browser",
            instrumentations: (Z = (S = this.options) == null ? void 0 : S.otel) == null ? void 0 : Z.instrumentations,
            eventNames: (te = (ee = this.options) == null ? void 0 : ee.otel) == null ? void 0 : te.eventNames,
            getIntegrations: () => [...this._integrations]
          },
          T
        ), this._gauges.clear(), this._counters.clear(), this._histograms.clear(), this._up_down_counters.clear(), this.logger.log(
          "Initializing...",
          e,
          this.sessionData,
          this.options
        ), this.sessionData = (se = M(this.sessionData.sessionSecureID)) != null ? se : this.sessionData, (ie = this.sessionData) != null && ie.sessionStartTime ? this._recordingStartTime = (ne = this.sessionData) == null ? void 0 : ne.sessionStartTime : (this._recordingStartTime = (/* @__PURE__ */ new Date()).getTime(), this.sessionData.sessionStartTime = this._recordingStartTime), J(""), U(this.sessionData);
        let H = G(ke.CLIENT_ID);
        H || (H = N(), j(ke.CLIENT_ID, H));
        let P;
        this.options.disableSessionRecording || this.options.disableNetworkRecording !== void 0 || typeof this.options.networkRecording == "boolean" ? P = !1 : P = ((re = this.options.networkRecording) == null ? void 0 : re.recordHeadersAndBody) || !1;
        let de = [];
        if (typeof this.options.networkRecording == "object" && ((oe = this.options.networkRecording.destinationDomains) != null && oe.length) && (de = this.options.networkRecording.destinationDomains), this._isCrossOriginIframe)
          yield this._setupCrossOriginIframe();
        else {
          const v = 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: H,
            appVersion: this.appVersion,
            serviceName: this.serviceName,
            session_secure_id: this.sessionData.sessionSecureID,
            session_key: this.sessionData.sessionKey,
            client_id: H,
            network_recording_domains: de,
            disable_session_recording: this.options.disableSessionRecording
          });
          if (v.initializeSession.secure_id !== this.sessionData.sessionSecureID && this.logger.log(
            `Unexpected secure id returned by initializeSession: ${v.initializeSession.secure_id}, expected ${this.sessionData.sessionSecureID}`
          ), this.sessionData.sessionSecureID = v.initializeSession.secure_id, this.sessionData.projectID = parseInt(
            ((ae = v == null ? void 0 : v.initializeSession) == null ? void 0 : ae.project_id) || "0"
          ), T.setConfig(v.initializeSession.sampling), !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: C.Initialize,
            sessionSecureID: this.sessionData.sessionSecureID,
            backend: this._backendUrl,
            debug: !!this.debugOptions.clientInteractions,
            recordingStartTime: this._recordingStartTime
          }
        });
        for (const v of this._integrations)
          v.init(this.sessionData.sessionSecureID);
        if (this.sessionData.userIdentifier && this.identify(
          this.sessionData.userIdentifier,
          this.sessionData.userObject
        ), this._firstLoadListeners.isListening() ? this._firstLoadListeners.hasNetworkRecording || I.setupNetworkListener(
          this._firstLoadListeners,
          this.options
        ) : this._firstLoadListeners.startListening(), this.pushPayloadTimerId && (clearTimeout(this.pushPayloadTimerId), this.pushPayloadTimerId = void 0), this._isCrossOriginIframe || (this.pushPayloadTimerId = setTimeout(() => {
          this._save();
        }, ye)), 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: he } = Nt();
        he && this.recordGauge({
          name: E.DeviceMemory,
          value: he().deviceMemory,
          category: D.Device,
          group: window.location.href
        });
        const ge = (v, Me) => {
          Me && this.logger.log("received isCheckout emit", { event: v }), this.events.push(v);
        };
        ge.bind(this);
        const We = !!this._recordStop;
        this._recordStop && (this._recordStop(), this._recordStop = void 0);
        const [ze, Be] = et(
          this.privacySetting
        );
        this._recordStop = q({
          ignoreClass: (ce = this.options.ignoreClass) != null ? ce : "highlight-ignore",
          ignoreSelector: this.options.ignoreSelector,
          blockClass: (le = this.options.blockClass) != null ? le : "highlight-block",
          blockSelector: this.options.blockSelector,
          emit: ge,
          recordCrossOriginIframes: this.options.recordCrossOriginIframe,
          privacySetting: this.privacySetting,
          maskAllInputs: ze,
          maskInputOptions: Be,
          maskTextClass: this.options.maskTextClass,
          maskTextSelector: this.options.maskTextSelector,
          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: (v) => !this.options.recordCrossOriginIframe,
          inlineImages: this.inlineImages,
          inlineVideos: this.inlineVideos,
          collectFonts: this.inlineImages,
          inlineStylesheet: this.inlineStylesheet,
          plugins: [Ze()],
          logger: typeof this.options.debug == "boolean" && this.options.debug || typeof this.options.debug == "object" && this.options.debug.domRecording ? {
            debug: this.logger.log,
            warn: W
          } : void 0
        }), We || 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.sessionData.sessionKey && this.addProperties(
          {
            sessionKey: this.sessionData.sessionKey
          },
          { type: "session" }
        ), this._setupWindowListeners(), this.ready = !0, this.state = "Recording", this.manualStopped = !1;
      } catch (T) {
        this._isOnLocalHost && (console.error(T), W("initializeSession", T));
      }
    });
  }
  _visibilityHandler(e) {
    return R(this, null, function* () {
      if (this.manualStopped) {
        this.logger.log("Ignoring visibility event due to manual stop.");
        return;
      }
      (/* @__PURE__ */ new Date()).getTime() - this._lastVisibilityChangeTime < ot || (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 R(this, null, function* () {
      this.logger.log("highlight in cross-origin iframe is waiting "), yield new Promise((e) => {
        const t = (s) => {
          if (s.data.highlight === fe) {
            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: we
              },
              "*"
            ), 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: fe,
            projectID: this.sessionData.projectID,
            sessionSecureID: this.sessionData.sessionSecureID
          },
          "*"
        );
      });
    }, ye), window.addEventListener("message", (e) => {
      e.data.highlight === we && this.logger.log(
        "highlight got response from initialized iframe"
      );
    });
  }
  _setupWindowListeners() {
    var s;
    try {
      const n = this;
      this.enableSegmentIntegration && this.listeners.push(
        xe((r) => {
          if (r.type === "track") {
            const c = {};
            c["segment-event"] = r.event, n.addProperties(c, {
              type: "track",
              source: "segment"
            });
          } else if (r.type === "identify") {
            const c = r.userId.replace(
              /^"(.*)"$/,
              "$1"
            );
            n.identify(
              c,
              r.traits,
              "segment"
            );
          }
        })
      ), this.listeners.push(
        Ae((r) => {
          this.reloaded ? (this.addCustomEvent("Reload", r), this.reloaded = !1, n.addProperties(
            { reload: !0 },
            { type: "session" }
          )) : this.addCustomEvent("Navigate", r);
        })
      ), this.listeners.push(
        at(
          (r) => {
            this.addCustomEvent("Viewport", r), this.submitViewportMetrics(r);
          }
        )
      ), this.listeners.push(
        qe((r, c) => {
          let d = null, l = null;
          if (c && c.target) {
            const h = c.target;
            d = mt(h), l = h.textContent, l && l.length > 2e3 && (l = l.substring(0, 2e3));
          }
          this.addCustomEvent("Click", {
            clickTarget: r,
            clickTextContent: l,
            clickSelector: d
          });
        })
      ), this.listeners.push(
        Ge((r) => {
          r && this.addCustomEvent("Focus", r);
        })
      ), this.listeners.push(
        Ot((r) => {
          const { name: c, value: d } = r;
          this.recordGauge({
            name: c,
            value: d,
            group: window.location.href,
            category: D.WebVital
          });
        })
      ), this.listeners.push(
        Tt(
          (r) => {
            const c = [];
            r.saveData !== void 0 && c.push({
              name: "saveData",
              value: r.saveData.toString()
            }), r.effectiveType !== void 0 && c.push({
              name: "effectiveType",
              value: r.effectiveType.toString()
            }), r.type !== void 0 && c.push({
              name: "type",
              value: r.type.toString()
            }), Object.entries(r).forEach(([d, l]) => {
              ft(l) && this.recordGauge({
                name: d,
                value: l,
                category: D.Performance,
                group: window.location.href,
                tags: c
              });
            });
          },
          this._recordingStartTime
        )
      ), this.sessionShortcut && je(this.sessionShortcut, () => {
        window.open(
          this.getCurrentSessionURLWithTimestamp(),
          "_blank"
        );
      }), this.enablePerformanceRecording && (this.listeners.push(
        Ht((r) => {
          this.addCustomEvent("Performance", V(r)), Object.entries(r).filter(([c]) => c !== "relativeTimestamp").forEach(
            ([c, d]) => d && this.recordGauge({
              name: c,
              value: d,
              category: D.Performance,
              group: window.location.href
            })
          );
        }, this._recordingStartTime)
      ), this.listeners.push(
        Pt((r) => {
          this.addCustomEvent("Jank", V(r)), this.recordGauge({
            name: "Jank",
            value: r.jankAmount,
            category: D.WebVital,
            group: r.querySelector
          });
        }, this._recordingStartTime)
      )), this._hasPreviouslyInitialized || ((s = window.electron) != null && s.ipcRenderer ? (window.electron.ipcRenderer.on(
        "highlight.run",
        ({ visible: r }) => {
          this._visibilityHandler(!r);
        }
      ), this.logger.log("Set up Electron highlight.run events.")) : (Je(
        (r) => this._visibilityHandler(r)
      ), this.logger.log("Set up document visibility listener.")), this._hasPreviouslyInitialized = !0);
      const o = () => {
        this.hasSessionUnloaded = !0, this.pushPayloadTimerId && (clearTimeout(this.pushPayloadTimerId), this.pushPayloadTimerId = void 0);
      };
      window.addEventListener("beforeunload", o), this.listeners.push(
        () => window.removeEventListener("beforeunload", o)
      );
    } catch (n) {
      this._isOnLocalHost && (console.error(n), W("initializeSession _setupWindowListeners", n));
    }
    const e = () => {
      this.addCustomEvent("Page Unload", ""), J(this.sessionData.sessionSecureID), U(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", ""), J(this.sessionData.sessionSecureID), U(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: E.ViewportHeight,
      value: e,
      category: D.Device,
      group: window.location.href
    }), this.recordGauge({
      name: E.ViewportWidth,
      value: t,
      category: D.Device,
      group: window.location.href
    }), this.recordGauge({
      name: E.ScreenHeight,
      value: s,
      category: D.Device,
      group: window.location.href
    }), this.recordGauge({
      name: E.ScreenWidth,
      value: n,
      category: D.Device,
      group: window.location.href
    }), this.recordGauge({
      name: E.ViewportArea,
      value: e * t,
      category: D.Device,
      group: window.location.href
    });
  }
  recordGauge(e) {
    var s, n;
    let t = this._gauges.get(e.name);
    if (!t) {
      if (t = (s = $()) == null ? void 0 : s.createGauge(e.name), !t) return;
      this._gauges.set(e.name, t);
    }
    t.record(e.value, y(p({}, (n = e.tags) == null ? void 0 : n.reduce((o, r) => y(p({}, o), { [r.name]: r.value }), {})), {
      group: e.group,
      category: e.category,
      "highlight.session_id": this.sessionData.sessionSecureID
    }));
    for (const o of this._integrations)
      o.recordGauge(this.sessionData.sessionSecureID, e);
  }
  recordCount(e) {
    var s, n;
    let t = this._counters.get(e.name);
    if (!t) {
      if (t = (s = $()) == null ? void 0 : s.createCounter(e.name), !t) return;
      this._counters.set(e.name, t);
    }
    t.add(e.value, y(p({}, (n = e.tags) == null ? void 0 : n.reduce((o, r) => y(p({}, o), { [r.name]: r.value }), {})), {
      group: e.group,
      category: e.category,
      "highlight.session_id": this.sessionData.sessionSecureID
    }));
  }
  recordIncr(e) {
    this.recordCount(y(p({}, e), { value: 1 }));
  }
  recordHistogram(e) {
    var s, n;
    let t = this._histograms.get(e.name);
    if (!t) {
      if (t = (s = $()) == null ? void 0 : s.createHistogram(e.name), !t) return;
      this._histograms.set(e.name, t);
    }
    t.record(e.value, y(p({}, (n = e.tags) == null ? void 0 : n.reduce((o, r) => y(p({}, o), { [r.name]: r.value }), {})), {
      group: e.group,
      category: e.category,
      "highlight.session_id": this.sessionData.sessionSecureID
    }));
  }
  recordUpDownCounter(e) {
    var s, n;
    let t = this._up_down_counters.get(e.name);
    if (!t) {
      if (t = (s = $()) == null ? void 0 : s.createUpDownCounter(e.name), !t) return;
      this._up_down_counters.set(e.name, t);
    }
    t.add(e.value, y(p({}, (n = e.tags) == null ? void 0 : n.reduce((o, r) => y(p({}, o), { [r.name]: r.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 = [], Oe();
  }
  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://${Q}/${t}/sessions/${s}?ts=${n}`;
  }
  getCurrentSessionURL() {
    const e = this.sessionData.projectID, t = this.sessionData.sessionSecureID;
    return e && t ? `https://${Q}/${e}/sessions/${t}` : null;
  }
  snapshot(e) {
    return R(this, null, function* () {
      yield q.snapshotCanvas(e);
    });
  }
  addSessionFeedback({
    timestamp: e,
    verbatim: t,
    user_email: s,
    user_name: n
  }) {
    var o;
    this._worker.postMessage({
      message: {
        type: C.Feedback,
        verbatim: t,
        timestamp: e,
        userName: n || this.sessionData.userIdentifier,
        userEmail: s || ((o = this.sessionData.userObject) == null ? void 0 : o.name)
      }
    });
  }
  // Reset the events array and push to a backend.
  _save() {
    return R(this, null, function* () {
      var e;
      try {
        this.state === "Recording" && this.listeners && !this.sessionData.sessionKey && this.sessionData.sessionStartTime && Date.now() - this.sessionData.sessionStartTime > ct && (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) => R(this, null, function* () {
          let n = new Blob(
            [
              JSON.stringify({
                query: dt(wt),
                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(), U(this.sessionData);
      } catch (t) {
        this._isOnLocalHost && (console.error(t), W("_save", t));
      }
      this.state === "Recording" && (this.pushPayloadTimerId && (clearTimeout(this.pushPayloadTimerId), this.pushPayloadTimerId = void 0), this.pushPayloadTimerId = setTimeout(() => {
        this._save();
      }, lt));
    });
  }
  /**
   * 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 ? pe(e, t) : s = setTimeout(n, 500);
      };
      s = setTimeout(n, 500);
    } else this.state === "Recording" && (this.events.length > 0 || this.hasPushedData) && pe(e, t);
  }
  _sendPayload(t) {
    return R(this, arguments, function* ({
      sendFn: e
    }) {
      const s = I.getRecordedNetworkResources(
        this._firstLoadListeners,
        this._recordingStartTime
      ), n = I.getRecordedWebSocketEvents(
        this._firstLoadListeners
      ), o = [...this.events], r = [...this._firstLoadListeners.messages], c = [...this._firstLoadListeners.errors], { bytes: d, time: l } = this.enableCanvasRecording ? be.canvas : be.normal;
      this._eventBytesSinceSnapshot >= d && (/* @__PURE__ */ new Date()).getTime() - this._lastSnapshotTime >= l && this.takeFullSnapshot(), this.logger.log(
        `Sending: ${o.length} events, ${r.length} messages, ${s.length} network resources, ${c.length} errors 
To: ${this._backendUrl}
Org: ${this.organizationID}
SessionSecureID: ${this.sessionData.sessionSecureID}`
      );
      const h = (/* @__PURE__ */ new Date()).getTime(), g = Qe();
      if (e) {
        const m = {
          session_secure_id: this.sessionData.sessionSecureID,
          payload_id: h.toString(),
          events: { events: o },
          messages: V({ messages: r }),
          resources: JSON.stringify({ resources: s }),
          web_socket_events: JSON.stringify({ webSocketEvents: n }),
          errors: c,
          is_beacon: !1,
          has_session_unloaded: this.hasSessionUnloaded,
          highlight_logs: g || void 0
        }, { compressedBase64: f } = yield Ye(m);
        yield e({
          session_secure_id: this.sessionData.sessionSecureID,
          payload_id: (/* @__PURE__ */ new Date()).getTime().toString(),
          data: f
        });
      } else
        this._worker.postMessage({
          message: {
            type: C.AsyncEvents,
            id: h,
            events: o,
            messages: r,
            errors: c,
            resourcesString: JSON.stringify({ resources: s }),
            webSocketEventsString: JSON.stringify({
              webSocketEvents: n
            }),
            hasSessionUnloaded: this.hasSessionUnloaded,
            highlightLogs: g
          }
        });
      U(this.sessionData), I.clearRecordedNetworkResources(
        this._firstLoadListeners
      ), this.events = this.events.slice(o.length), this._firstLoadListeners.messages = this._firstLoadListeners.messages.slice(r.length), this._firstLoadListeners.errors = this._firstLoadListeners.errors.slice(
        c.length
      ), Xe(g);
    });
  }
  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
    }), q.takeFullSnapshot(), this._eventBytesSinceSnapshot = 0, this._lastSnapshotTime = (/* @__PURE__ */ new Date()).getTime();
  }
  registerLD(e) {
    this._integrations.length || this._integrations.push(new Ee(e));
  }
}
const Mt = () => {
  var i, e;
  typeof chrome != "undefined" && ((i = chrome == null ? void 0 : chrome.runtime) != null && i.onMessage) && ((e = chrome == null ? void 0 : chrome.runtime) == null || e.onMessage.addListener(
    (t, s, n) => {
      const o = t.action;
      switch (console.log(
        `[highlight] received '${o}' event from extension.`
      ), o) {
        case "init": {
          w.init(1, {
            debug: !0
          }), w.getSessionURL().then((r) => {
            n({ url: r });
          });
          break;
        }
        case "stop": {
          w.stop(), n({ success: !0 });
          break;
        }
      }
      return !0;
    }
  ));
};
function Gt(i) {
  var e;
  i.on && ((e = i.webContents) != null && e.send) && (i.on("focus", () => {
    i.webContents.send("highlight.run", { visible: !0 });
  }), i.on("blur", () => {
    i.webContents.send("highlight.run", { visible: !1 });
  }), i.on("close", () => {
    i.webContents.send("highlight.run", { visible: !1 });
  }));
}
const jt = ({
  next: i,
  payload: e
}) => {
  if (typeof window != "undefined" && typeof document != "undefined" && "H" in window) {
    if (e.obj.type === "track") {
      const t = e.obj.event, s = e.obj.properties;
      window.H.track(t, s);
    } else if (e.obj.type === "identify") {
      const t = e.obj.userId;
      if (t != null && t.length) {
        const s = e.obj.traits;
        window.H.identify(t, s);
      }
    }
  }
  i(e);
}, Pe = () => {
  if (typeof window != "undefined") {
    if (typeof window._highlightFetchPatch != "undefined")
      return;
    window._originalFetch = window.fetch, window._fetchProxy = (i, e) => window._originalFetch(i, e), window._highlightFetchPatch = (i, e) => window._fetchProxy.call(window || global, i, e), window.fetch = window._highlightFetchPatch;
  }
}, Ce = () => null, Ue = () => {
  if (typeof window != "undefined") {
    if (typeof window._highlightWebSocketRequestCallback != "undefined")
      return;
    window._highlightWebSocketRequestCallback = Ce, window._highlightWebSocketEventCallback = Ce;
    const i = new Proxy(window.WebSocket, {
      construct(e, t) {
        const [, s] = Ut(), n = new e(...t), o = (h) => {
          window._highlightWebSocketRequestCallback({
            socketId: s,
            initiatorType: "websocket",
            type: "open",
            name: n.url,
            startTimeAbs: performance.timeOrigin + h.timeStamp
          });
        }, r = (h) => {
          window._highlightWebSocketRequestCallback({
            socketId: s,
            initiatorType: "websocket",
            type: "close",
            name: n.url,
            responseEndAbs: performance.timeOrigin + h.timeStamp
          }), n.removeEventListener("open", o), n.removeEventListener("error", d), n.removeEventListener("message", c), n.removeEventListener("close", r);
        }, c = (h) => {
          const { data: g } = h, m = typeof g == "string" ? h.data : void 0;
          let f;
          typeof g == "string" ? f = g.length : g instanceof Blob ? f = g.size : f = g.byteLength || 0, window._highlightWebSocketEventCallback({
            socketId: s,
            type: "received",
            name: n.url,
            timeStamp: performance.timeOrigin + h.timeStamp,
            size: f,
            message: m
          });
        }, d = (h) => {
          window._highlightWebSocketEventCallback({
            socketId: s,
            type: "error",
            name: n.url,
            timeStamp: performance.timeOrigin + h.timeStamp,
            size: 0
          });
        };
        n.addEventListener("open", o), n.addEventListener("error", d), n.addEventListener("message", c), n.addEventListener("close", r);
        const l = new Proxy(n.send, {
          apply: function(h, g, m) {
            const f = m[0], _ = typeof f == "string" ? f : void 0;
            let k;
            typeof f == "string" ? k = f.length : f instanceof Blob ? k = f.size : k = f.byteLength || 0, window._highlightWebSocketEventCallback({
              socketId: s,
              type: "sent",
              name: n.url,
              timeStamp: performance.timeOrigin + performance.now(),
              size: k,
              message: _
            }), h.apply(g, m);
          }
        });
        return n.send = l, n;
      }
    });
    window.WebSocket = i;
  }
};
var Ft = /* @__PURE__ */ ((i) => (i.Device = "Device", i.WebVital = "WebVital", i.Frontend = "Frontend", i.Backend = "Backend", i))(Ft || {});
const b = (i, e) => {
  console.warn(`highlight.run warning: (${i}): `, e);
}, $t = 200;
let z = [], K, u, B, Le = [], Y = !1;
const w = {
  options: void 0,
  init: (i, e) => {
    var t, s, n, o, r, c, d, l;
    try {
      if (w.options = e, typeof window == "undefined" || typeof document == "undefined")
        return;
      if (!i) {
        console.info(
          "Highlight is not initializing because projectID was passed undefined."
        );
        return;
      }
      e != null && e.sessionCookie ? St() : Ne(!1);
      const h = M();
      let g = N();
      if (e != null && e.sessionKey ? g = N(
        `${i}-${e.sessionKey}`
      ) : h != null && h.sessionSecureID && (g = h.sessionSecureID), Y)
        return { sessionSecureID: g };
      Y = !0, Pe(), Ue();
      const m = y(p({}, e), {
        organizationID: i,
        firstloadVersion: yt,
        environment: (e == null ? void 0 : e.environment) || "production",
        appVersion: e == null ? void 0 : e.version,
        sessionSecureID: g
      });
      return u = u != null ? u : new X(m, B), e != null && e.manualStart || u.initialize(), B = new I(m), e != null && e.manualStart || B.startListening(), !((s = (t = e == null ? void 0 : e.integrations) == null ? void 0 : t.mixpanel) != null && s.disabled) && ((o = (n = e == null ? void 0 : e.integrations) == null ? void 0 : n.mixpanel) != null && o.projectToken) && tt(e.integrations.mixpanel), !((c = (r = e == null ? void 0 : e.integrations) == null ? void 0 : r.amplitude) != null && c.disabled) && ((l = (d = e == null ? void 0 : e.integrations) == null ? void 0 : d.amplitude) != null && l.apiKey) && st(e.integrations.amplitude), { sessionSecureID: g };
    } catch (h) {
      b("init", h);
    }
  },
  snapshot: (i) => R(void 0, null, function* () {
    try {
      if (u && u.ready)
        return yield u.snapshot(i);
    } catch (e) {
      b("snapshot", e);
    }
  }),
  addSessionFeedback: ({
    verbatim: i,
    userName: e,
    userEmail: t,
    timestampOverride: s
  }) => {
    try {
      w.onHighlightReady(
        () => u.addSessionFeedback({
          verbatim: i,
          timestamp: s || (/* @__PURE__ */ new Date()).toISOString(),
          user_email: t,
          user_name: e
        })
      );
    } catch (n) {
      b("error", n);
    }
  },
  consumeError: (i, e, t) => {
    try {
      w.onHighlightReady(
        () => u.consumeCustomError(
          i,
          e,
          JSON.stringify(t)
        )
      );
    } catch (s) {
      b("error", s);
    }
  },
  consume: (i, e) => {
    try {
      w.onHighlightReady(() => u.consumeError(i, e));
    } catch (t) {
      b("error", t);
    }
  },
  error: (i, e) => {
    try {
      w.onHighlightReady(
        () => u.pushCustomError(i, JSON.stringify(e))
      );
    } catch (t) {
      b("error", t);
    }
  },
  track: (i, e = {}) => {
    var t, s, n, o, r, c, d, l, h, g, m;
    try {
      w.onHighlightReady(() => {
        u.addProperties(y(p({}, e), { event: i })), u.log("H.track", "INFO", y(p({}, e != null ? e : {}), {
          event: i
        }));
      });
      const f = u == null ? void 0 : u.getCurrentSessionURL();
      (n = (s = (t = w.options) == null ? void 0 : t.integrations) == null ? void 0 : s.mixpanel) != null && n.disabled || (o = window.mixpanel) != null && o.track && window.mixpanel.track(i, y(p({}, e), {
        highlightSessionURL: f
      })), (d = (c = (r = w.options) == null ? void 0 : r.integrations) == null ? void 0 : c.amplitude) != null && d.disabled || (l = window.amplitude) != null && l.getInstance && window.amplitude.getInstance().logEvent(i, y(p({}, e), {
        highlightSessionURL: f
      })), (m = (g = (h = w.options) == null ? void 0 : h.integrations) == null ? void 0 : g.intercom) != null && m.disabled || window.Intercom && window.Intercom("trackEvent", i, e);
    } catch (f) {
      b("track", f);
    }
  },
  log: (i, e, t) => {
    try {
      w.onHighlightReady(
        () => u.log(i, e, t != null ? t : {})
      );
    } catch (s) {
      b("log", s);
    }
  },
  start: (i) => {
    (u == null ? void 0 : u.state) === "Recording" && !(i != null && i.forceNew) ? i != null && i.silent || console.warn(
      "Highlight is already recording. Please `H.stop()` the current session before starting a new one."
    ) : (B.startListening(), w.onHighlightReady(
      () => R(void 0, null, function* () {
        yield u.initialize(i);
      }),
      { waitForReady: !1 }
    ));
  },
  stop: (i) => {
    (u == null ? void 0 : u.state) !== "Recording" ? i != null && i.silent || console.warn(
      "Highlight is already stopped. Please call `H.start()`."
    ) : w.onHighlightReady(() => u.stopRecording(!0));
  },
  identify: (i, e = {}, t) => {
    var s, n, o, r, c, d, l, h;
    try {
      w.onHighlightReady(
        () => u.identify(i, e, t)
      );
    } catch (g) {
      b("identify", g);
    }
    if ((o = (n = (s = w.options) == null ? void 0 : s.integrations) == null ? void 0 : n.mixpanel) != null && o.disabled || (r = window.mixpanel) != null && r.identify && (window.mixpanel.identify(
      typeof (e == null ? void 0 : e.email) == "string" ? e == null ? void 0 : e.email : i
    ), e && (window.mixpanel.track("identify", e), window.mixpanel.people.set(e))), !((l = (d = (c = w.options) == null ? void 0 : c.integrations) == null ? void 0 : d.amplitude) != null && l.disabled) && (h = window.amplitude) != null && h.getInstance && (window.amplitude.getInstance().setUserId(i), Object.keys(e).length > 0)) {
      const g = Object.keys(
        e
      ).reduce((m, f) => (m.set(f, e[f]), m), new window.amplitude.Identify());
      window.amplitude.getInstance().identify(g);
    }
  },
  metrics: (i) => {
    try {
      for (const e of i)
        w.recordMetric(e);
    } catch (e) {
      b("metrics", e);
    }
  },
  recordMetric: (i) => {
    try {
      w.onHighlightReady(() => {
        var e;
        u.recordGauge(y(p({}, i), {
          tags: (e = i.tags) != null ? e : [],
          group: window.location.href,
          category: "Frontend"
          /* Frontend */
        }));
      });
    } catch (e) {
      b("recordMetric", e);
    }
  },
  recordCount: (i) => {
    try {
      w.onHighlightReady(() => {
        u.recordCount(i);
      });
    } catch (e) {
      b("recordCount", e);
    }
  },
  recordIncr: (i) => {
    try {
      w.onHighlightReady(() => {
        u.recordIncr(i);
      });
    } catch (e) {
      b("recordIncr", e);
    }
  },
  recordHistogram: (i) => {
    try {
      w.onHighlightReady(() => {
        u.recordHistogram(i);
      });
    } catch (e) {
      b("recordHistogram", e);
    }
  },
  recordUpDownCounter: (i) => {
    try {
      w.onHighlightReady(() => {
        u.recordUpDownCounter(i);
      });
    } catch (e) {
      b("recordUpDownCounter", e);
    }
  },
  startSpan: (i, e, t, s) => {
    const n = De();
    if (!n) {
      const r = Ie();
      return s === void 0 && t === void 0 ? e(r) : s === void 0 ? t(r) : s(r);
    }
    const o = (r, c) => {
      const d = c(r);
      return d instanceof Promise ? d.finally(() => r.end()) : (r.end(), d);
    };
    return s === void 0 && t === void 0 ? n.startActiveSpan(
      i,
      (r) => o(r, e)
    ) : s === void 0 ? n.startActiveSpan(
      i,
      e,
      (r) => o(r, t)
    ) : n.startActiveSpan(
      i,
      e,
      t,
      (r) => o(r, s)
    );
  },
  startManualSpan: (i, e, t, s) => {
    const n = De();
    if (!n) {
      const o = Ie();
      return s === void 0 && t === void 0 ? e(o) : s === void 0 ? t(o) : s(o);
    }
    return s === void 0 && t === void 0 ? n.startActiveSpan(i, e) : s === void 0 ? n.startActiveSpan(
      i,
      e,
      t
    ) : n.startActiveSpan(
      i,
      e,
      t,
      s
    );
  },
  getSessionURL: () => new Promise((i, e) => {
    w.onHighlightReady(() => {
      const t = u.sessionData.sessionSecureID, s = M(t);
      s ? i(
        `https://${Q}/${s.projectID}/sessions/${t}`
      ) : e(new Error(`Unable to get session URL: ${t}`));
    });
  }),
  getSessionDetails: () => new Promise((i, e) => {
    w.onHighlightReady(() => R(void 0, null, function* () {
      try {
        const t = yield w.getSessionURL();
        if (!t)
          throw new Error("Could not get session URL");
        const s = u.sessionData.sessionSecureID, n = M(s), o = n == null ? void 0 : n.sessionStartTime;
        if (!o)
          throw new Error("Could not get session start timestamp");
        const r = (/* @__PURE__ */ new Date()).getTime(), c = new URL(t), d = new URL(t);
        d.searchParams.set(
          "ts",
          ((r - o) / 1e3).toString()
        ), i({
          url: c.toString(),
          urlWithTimestamp: d.toString(),
          sessionSecureID: s
        });
      } catch (t) {
        e(t);
      }
    }));
  }),
  getRecordingState: () => {
    var i;
    return (i = u == null ? void 0 : u.state) != null ? i : "NotRecording";
  },
  onHighlightReady: (i, e) => {
    if (u && u.ready) {
      i();
      return;
    }
    if (z.push({ options: e, func: i }), K !== void 0)
      return;
    const t = () => {
      z = z.filter((n) => {
        var o;
        return !u || ((o = n.options) == null ? void 0 : o.waitForReady) !== !1 && !u.ready ? !0 : (n.func(), !1);
      }), K = void 0, z.length > 0 && (K = setTimeout(
        t,
        $t
      ));
    };
    t();
  },
  registerLD(i) {
    Le.length || (w.onHighlightReady(() => {
      u.registerLD(i);
    }), pt(this, i, w.options), Le.push(new Ee(i)));
  }
};
typeof window != "undefined" && (window.H = w);
Mt();
Pe();
Ue();
const Jt = {
  reset: () => {
    Y = !1, u = void 0, z = [], K = void 0, B = void 0;
  },
  setHighlightObj: (i) => {
    u = i;
  }
};
export {
  N as GenerateSecureID,
  w as H,
  jt as HighlightSegmentMiddleware,
  ss as LDObserve,
  ns as LDRecord,
  Ft as MetricCategory,
  es as Observe,
  Xt as Record,
  Jt as __testing,
  Gt as configureElectronHighlight
};
//# sourceMappingURL=index.js.map
