import{ulid as i}from"ulid";import{trace as d}from"@opentelemetry/api";import{CompositePropagator as m,W3CBaggagePropagator as c,W3CTraceContextPropagator as f}from"@opentelemetry/core";import{Resource as l}from"@opentelemetry/resources";import{BatchSpanProcessor as u,WebTracerProvider as E}from"@opentelemetry/sdk-trace-web";import{registerInstrumentations as y}from"@opentelemetry/instrumentation";import{DocumentLoadInstrumentation as T}from"@opentelemetry/instrumentation-document-load";import{OTLPTraceExporter as R}from"@opentelemetry/exporter-trace-otlp-http";import{FetchInstrumentation as _}from"@opentelemetry/instrumentation-fetch";import{XMLHttpRequestInstrumentation as h}from"@opentelemetry/instrumentation-xml-http-request";import{ATTR_SERVICE_NAME as w,ATTR_SERVICE_VERSION as g}from"@opentelemetry/semantic-conventions";import{withPathPrefix as C}from"@redocly/theme/core/utils";import{ServerRoutes as I}from"../../../../constants/index.js";import{PACKAGE_NAME as O}from"../../../../config/product-gates";import{ErrorInstrumentation as n}from"./error-instrumentation";class P{sessionId;initialReferrer;init(){if(this.disabled())return;this.sessionId=`ses_${i()}`,this.initialReferrer=document.referrer||void 0;const e=new E({resource:new l({[w]:"realm-ui",[g]:`${O}@${process.env.REDOCLY_PORTAL_VERSION}`,"redocly.session.id":this.sessionId})});e.addSpanProcessor(new u(new R({url:C(I.OTEL_TRACES),headers:{}}))),e.register({propagator:new m({propagators:[new c,new f]})}),y({instrumentations:[new T,new _,new h,new n(void 0,r=>{this.send(r)})]})}send(e){try{if(this.disabled())return;const r=new Date,s=i(),t=d.getTracer("ClientTelemetry").startSpan(`event.${e.type}`,{attributes:{"redocly.event_id":s,"redocly.event_type":e.type,"redocly.page.uri":location.href,"redocly.page.initial_referrer":this.initialReferrer},startTime:r});"payload"in e&&typeof e.payload=="object"&&e.payload!==null&&Object.entries(e.payload).forEach(([a,o])=>{const p=a.replace(/([A-Z])/g,"_$1").toLowerCase();o!==void 0&&t.setAttribute(`redocly.event_data.${p}`,o)}),t.end(r)}catch(r){process.env.NODE_ENV!=="production"&&console.error("Event reporting failed:",r)}}sendError(e,r){this.send(n.toErrorEvent(e,r))}disabled(){return process.env.NODE_ENV!=="production"||process.env.REDOCLY_TELEMETRY==="off"}}const q=new P;export{P as OtelClientTelemetry,q as otelTelemetry};
