@embrace-io/web-sdk
Version:
3 lines (2 loc) • 30.2 kB
JavaScript
;var e=require("./EmbraceInstrumentationBase-CS1Yr6S5.js"),t=require("@opentelemetry/api"),s=require("@opentelemetry/api-logs"),n=require("@opentelemetry/instrumentation"),r=require("@opentelemetry/resources"),i=require("@opentelemetry/sdk-logs"),a=require("@opentelemetry/sdk-trace-web"),o=require("@opentelemetry/otlp-transformer"),c=require("@opentelemetry/otlp-exporter-base"),u=require("uuid"),l=require("@opentelemetry/core"),d=require("@opentelemetry/semantic-conventions"),g=require("@opentelemetry/semantic-conventions/incubating"),h=require("tslib"),_=require("@opentelemetry/opentelemetry-browser-detector"),p=require("web-vitals/attribution"),m=require("@opentelemetry/instrumentation-document-load"),S=require("@opentelemetry/instrumentation-fetch"),T=require("@opentelemetry/instrumentation-xml-http-request"),E=require("@opentelemetry/web-common");class b{constructor(e=t.INVALID_SPAN_CONTEXT){this._spanContext=e}fail(e){}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t,s){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}const v=new class{startSpan(e,t){return new b}setSpan(e,s){return t.ROOT_CONTEXT}getSpan(e){}};class w{getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:v}setDelegate(e){this._delegate=e}startSpan(e,t,s){return this.getDelegate().startSpan(e,t,s)}setSpan(e,t){return this.getDelegate().setSpan(e,t)}getSpan(e){return this.getDelegate().getSpan(e)}}class y{constructor({proxyTraceManager:e}){this.getTraceManager=()=>this._proxyTraceManager,this._proxyTraceManager=e}static getInstance(){return this._instance||(this._instance=new y({proxyTraceManager:new w})),this._instance}setGlobalTraceManager(e){this._proxyTraceManager.setDelegate(e)}startSpan(e,t,s){return this.getTraceManager().startSpan(e,t,s)}setSpan(e,t){return this.getTraceManager().setSpan(e,t)}getSpan(e){return this.getTraceManager().getSpan(e)}}const I=y.getInstance(),f="enduser.pseudo.id";const M=new class{getEmbraceUserId(){return""}getUserId(){return null}setUserId(){}clearUserId(){}};class D{getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:M}setDelegate(e){this._delegate=e}getEmbraceUserId(){return this.getDelegate().getEmbraceUserId()}getUserId(){return this.getDelegate().getUserId()}setUserId(e){this.getDelegate().setUserId(e)}clearUserId(){this.getDelegate().clearUserId()}}class L{constructor({proxyUserManager:e}){this._proxyUserManager=e}static getInstance(){return this._instance||(this._instance=new L({proxyUserManager:new D})),this._instance}getUserManager(){return this._proxyUserManager}setGlobalUserManager(e){this._proxyUserManager.setDelegate(e)}getEmbraceUserId(){return this.getUserManager().getEmbraceUserId()}getUserId(){return this.getUserManager().getUserId()}setUserId(e){this.getUserManager().setUserId(e)}clearUserId(){this.getUserManager().clearUserId()}}const R=L.getInstance();class P{constructor(e){this._delegate=e}export(e,t){this._delegate.export(e,t)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class U extends P{constructor(e){super(j(e,o.JsonLogsSerializer))}}const O=e=>B(e)+"/v2/logs";class A extends U{constructor({appID:e,userID:t}){super(Object.assign(Object.assign({},F),{headers:C(e,t),url:O(e)}))}}class N extends P{constructor(e){super(j(Object.assign(Object.assign({},e),{compression:"gzip"}),o.JsonTraceSerializer))}}const x=e=>B(e)+"/v2/spans";class k extends N{constructor({appID:e,userID:t}){super(Object.assign(Object.assign({},F),{headers:C(e,t),url:x(e)}))}}const C=(e,t)=>({"X-EM-AID":e,"X-EM-DID":t}),B=e=>`https://a-${e}.data.emb-api.com`,F={compression:"gzip",keepalive:!0,concurrencyLimit:5,timeoutMillis:3e4};class Y{constructor(e){this._config=e}static async _compressRequest(e){const t=new CompressionStream("gzip"),s=t.writable.getWriter();s.write(e),s.close();const n=[],r=t.readable.getReader();let i=!1;for(;!i;){const e=await r.read();e.value&&n.push(e.value),i=e.done}const a=new Uint8Array(n.reduce(((e,t)=>e+t.length),0));let o=0;for(const e of n)a.set(e,o),o+=e.length;return a}send(e,t){return this._asyncSend(e,t)}shutdown(){}async _asyncSend(e,t){let s=e;const n=Object.assign({"Content-Type":"application/json"},this._config.headers);"gzip"===this._config.compression&&(s=await Y._compressRequest(e),n["Content-Encoding"]="gzip",n["Content-Length"]=s.length.toString());try{return(await fetch(this._config.url,{method:"POST",keepalive:!0,headers:n,body:s,signal:AbortSignal.timeout(t)})).ok?{status:"success"}:{status:"failure",error:new Error("Fetch request failed")}}catch(e){return{status:"failure",error:new Error("Fetch request errored")}}}}const H=e=>new Y(e),K=()=>u.v4().replace(/-/g,"").toUpperCase();class q{constructor(t,s=new e.OTelPerformanceManager){this._transport=t,this._perf=s}async send(e,t){var s;const n=this._perf.getNowMillis()+t;let r=await this._transport.send(e,t),i=5,a=1e3;for(;"retryable"===r.status&&i>0;){i--;const t=Math.max(Math.min(a,5e3)+(40*Math.random()-20),0);a*=1.5;const o=null!==(s=r.retryInMillis)&&void 0!==s?s:t,c=n-this._perf.getNowMillis();if(o>c)return r;r=await this._retry(e,c,o)}return r}shutdown(){this._transport.shutdown()}_retry(e,t,s){return new Promise(((n,r)=>{setTimeout((()=>{this._transport.send(e,t).then(n,r)}),s)}))}}const j=(e,t)=>{return c.createOtlpNetworkExportDelegate(e,t,(s={transport:H(e)},new q(s.transport)));var s};class V{constructor({perf:t,spanSessionManager:n}){this._perf=null!=t?t:new e.OTelPerformanceManager,this._logger=s.logs.getLogger("embrace-web-sdk-logs"),this._spanSessionManager=n}static _logSeverityToSeverityNumber(e){switch(e){case"info":return s.SeverityNumber.INFO;case"warning":return s.SeverityNumber.WARN;default:return s.SeverityNumber.ERROR}}logException(t,{handled:n=!0,attributes:r={},timestamp:i=this._perf.getNowMillis()}={}){n||this._spanSessionManager.incrSessionCountForKey(e.KEY_EMB_UNHANDLED_EXCEPTIONS_COUNT),this._logger.emit({timestamp:i,severityNumber:s.SeverityNumber.ERROR,severityText:"ERROR",body:t.message||"",attributes:Object.assign(Object.assign({},r),{[e.KEY_EMB_TYPE]:e.EMB_TYPES.SystemException,[e.KEY_EMB_EXCEPTION_HANDLING]:n?"HANDLED":"UNHANDLED",[d.ATTR_EXCEPTION_TYPE]:t.constructor.name,"exception.name":t.name,[d.ATTR_EXCEPTION_MESSAGE]:t.message,[d.ATTR_EXCEPTION_STACKTRACE]:t.stack})})}message(t,s,{attributes:n={},includeStacktrace:r=!0}={}){"error"===s&&this._spanSessionManager.incrSessionCountForKey(e.KEY_EMB_ERROR_LOG_COUNT),this._logMessage({message:t,severity:s,timestamp:this._perf.getNowMillis(),attributes:n,stackTrace:r&&"info"!=s?(new Error).stack:void 0})}_logMessage({message:t,severity:s,timestamp:n,attributes:r={},stackTrace:i}){this._logger.emit({timestamp:n,severityNumber:V._logSeverityToSeverityNumber(s),severityText:s.toUpperCase(),body:t,attributes:Object.assign(Object.assign(Object.assign({},r),{[e.KEY_EMB_TYPE]:e.EMB_TYPES.SystemLog}),i?{[e.KEY_EMB_JS_EXCEPTION_STACKTRACE]:i}:{})})}}class G{constructor({diag:s,perf:n,visibilityDoc:r=window.document}={}){this._activeSessionId=null,this._activeSessionStartTime=null,this._sessionSpan=null,this._activeSessionCounts=null,this._sessionStartedListeners=[],this._sessionEndedListeners=[],this._diag=null!=s?s:t.diag.createComponentLogger({namespace:"EmbraceSpanSessionManager"}),this._perf=null!=n?n:new e.OTelPerformanceManager,this._visibilityDoc=r}addBreadcrumb(e){this._sessionSpan?this._sessionSpan.addEvent("emb-breadcrumb",{message:e},this._perf.getNowMillis()):this._diag.debug("trying to add breadcrumb to a session, but there is no session in progress. This is a no-op.")}addProperty(t,s){this._sessionSpan?this._sessionSpan.setAttribute(e.KEY_PREFIX_EMB_PROPERTIES+t,s):this._diag.debug("trying to add properties to a session, but there is no session in progress. This is a no-op.")}endSessionSpan(){this.endSessionSpanInternal("manual")}endSessionSpanInternal(t){if(this._sessionSpan){this._sessionSpan.setAttributes(Object.assign({[e.KEY_EMB_SESSION_REASON_ENDED]:t},this._activeSessionCounts)),this._sessionSpan.end(),this._sessionSpan=null,this._activeSessionStartTime=null,this._activeSessionId=null,this._activeSessionCounts=null;for(const e of this._sessionEndedListeners)try{e()}catch(e){this._diag.warn("Error while executing session ended listener",e)}}else this._diag.debug("trying to end a session, but there is no session in progress. This is a no-op.")}getSessionId(){return this._activeSessionId}getSessionSpan(){return this._sessionSpan}getSessionStartTime(){return this._activeSessionStartTime}startSessionSpan(){this._sessionSpan&&this.endSessionSpanInternal("manual");const s=t.trace.getTracer("embrace-web-sdk-sessions");this._activeSessionId=K(),this._activeSessionStartTime=this._perf.getNowHRTime(),this._activeSessionCounts={},this._sessionSpan=s.startSpan("emb-session",{attributes:{[e.KEY_EMB_TYPE]:e.EMB_TYPES.Session,[e.KEY_EMB_STATE]:"hidden"===this._visibilityDoc.visibilityState?e.EMB_STATES.Background:e.EMB_STATES.Foreground,[g.ATTR_SESSION_ID]:this._activeSessionId}});for(const e of this._sessionStartedListeners)try{e()}catch(e){this._diag.warn("Error while executing session started listener",e)}}incrSessionCountForKey(e){this._sessionSpan&&this._activeSessionCounts?this._activeSessionCounts[e]=(this._activeSessionCounts[e]||0)+1:this._diag.debug("trying to increment a count for the active session, but there is no session in progress. This is a no-op.")}addSessionStartedListener(e){const t=this._sessionStartedListeners.push(e);return()=>{this._sessionStartedListeners.splice(t-1,1)}}addSessionEndedListener(e){const t=this._sessionEndedListeners.push(e);return()=>{this._sessionEndedListeners.splice(t-1,1)}}}class X{constructor(e){this._span=e}addEvent(e,t,s){return this._span.addEvent(e,t,s),this}addLink(e){return this._span.addLink(e),this}addLinks(e){return this._span.addLinks(e),this}end(e){this._span.end(e)}isRecording(){return this._span.isRecording()}recordException(e,t){this._span.recordException(e,t)}setAttribute(e,t){return this._span.setAttribute(e,t),this}setAttributes(e){return this._span.setAttributes(e),this}setStatus(e){return this._span.setStatus(e),this}spanContext(){return this._span.spanContext()}updateName(e){return this._span.updateName(e),this}fail(t={code:"failure"}){t.code&&this._span.setAttribute(e.KEY_EMB_ERROR_CODE,t.code.toUpperCase()),this._span.end(t.endTime)}}class ${constructor(){this.setSpan=t.trace.setSpan}startSpan(s,n={},r){const i=t.trace.getTracer("embrace-web-sdk-traces");n.attributes=n.attributes?n.attributes:{},n.attributes[e.KEY_EMB_TYPE]=e.EMB_TYPES.Perf;const a=n.parentSpan?t.trace.setSpan(t.context.active(),n.parentSpan):r;return new X(i.startSpan(s,n,a))}getSpan(e){const s=t.trace.getSpan(e);if(s)return new X(s)}}const z="embrace_user",Q="embrace_user_id",W="embrace_external_user_id";class J{constructor({diag:e,storage:s=localStorage}={}){this._embraceUserId=null,this._diag=null!=e?e:t.diag.createComponentLogger({namespace:"EmbraceUserManager"}),this._storage=s,this._migrateOldLocalStorageKey(),this._initialSetup()}getEmbraceUserId(){return this._embraceUserId||this._generateNewEmbraceUserId()}setEmbraceUserId(e){this._embraceUserId=e;try{this._storage.setItem(Q,e)}catch(e){this._diag.warn("Failed to persist user object for storage, keeping it in-memory only",e)}}clearEmbraceUserId(){this._embraceUserId=null;try{this._storage.removeItem(Q)}catch(e){this._diag.warn("Failed to remove embrace user in storage",e)}}_migrateOldLocalStorageKey(){try{const e=this._storage.getItem(z);if(e){const t=JSON.parse(e);(e=>"string"==typeof e[f]&&32===e[f].length)(t)?(this._diag.debug("Migrating old user data from storage"),this._storage.setItem(Q,t[f]),this._storage.removeItem(z)):(this._diag.warn("Invalid user data found in storage, clearing old user data"),this._storage.removeItem(z))}}catch(e){this._diag.warn("Failed to get old user data from storage",e)}}_initialSetup(){try{const t=this._storage.getItem(Q);t?"string"==typeof(e=t)&&32===e.length?this._embraceUserId=t:(this._diag.warn("Invalid embrace user id, generating a new one"),this.clearEmbraceUserId()):this._diag.debug("No existing user found in storage, creating a new one")}catch(e){this._diag.warn("Failed to get embrace user id from storage, defaulting to a new one",e)}var e;this._embraceUserId||(this._embraceUserId=this._generateNewEmbraceUserId())}_generateNewEmbraceUserId(){const e=K();return this.setEmbraceUserId(e),e}getUserId(){return this._storage.getItem(W)}setUserId(e){this._storage.setItem(W,e)}clearUserId(){this._storage.removeItem(W)}}class Z{constructor({diag:e,processorName:s}){this._processorName=s,this._diag=null!=e?e:t.diag.createComponentLogger({namespace:s})}get diag(){return this._diag}get processorName(){return this._processorName}}class ee extends Z{constructor(e){var{exporter:t}=e,s=h.__rest(e,["exporter"]);super(Object.assign(Object.assign({},s),{processorName:"EmbraceSessionBatchedSpanProcessor"})),this._pendingSpans=[],this._shutdown=()=>this._exporter.shutdown(),this._exporter=t,this._shutdownOnce=new l.BindOnceFuture(this._shutdown,this)}forceFlush(){return this.diag.debug("forceFlush called for EmbraceSessionBatchedSpanProcessor. This is a no op"),Promise.resolve(void 0)}onEnd(t){this._shutdownOnce.isCalled?this.diag.debug("span ended after processor shutdown. Ignoring span."):(t=>t.attributes[e.KEY_EMB_TYPE]===e.EMB_TYPES.Session)(t)?(this.diag.debug("session span ended. Exporting all pending spans."),l.internal._export(this._exporter,[t,...this._pendingSpans]).then((e=>{var t;e.code===l.ExportResultCode.FAILED&&this.diag.error(`spans failed to export: ${(null===(t=e.error)||void 0===t?void 0:t.message)||"unknown error"}`)})).catch((e=>{let t="unknown error";e&&e instanceof Error?t=e.message:"string"==typeof e&&(t=e),this.diag.error(`spans failed to export: ${t}`)})),this._pendingSpans=[]):(this.diag.debug("non-session span ended. Adding to pending spans queue."),this._pendingSpans.push(t))}onStart(){}shutdown(){return this._shutdownOnce.call()}}class te{constructor({spanSessionManager:e}){this._spanSessionManager=e}forceFlush(){return Promise.resolve(void 0)}onEmit(e){e.setAttributes({[g.ATTR_LOG_RECORD_UID]:K(),[g.ATTR_SESSION_ID]:this._spanSessionManager.getSessionId()})}shutdown(){return Promise.resolve(void 0)}}const se=/.+:\/\/.+/;class ne{forceFlush(){return Promise.resolve(void 0)}onEnd(t){var s,n,r,i,a,o,c,u,l,h;(e=>{var t;if((e.attributes[d.ATTR_HTTP_REQUEST_METHOD]||e.attributes[d.SEMATTRS_HTTP_METHOD])&&(e.attributes[d.ATTR_HTTP_RESPONSE_STATUS_CODE]||e.attributes[d.SEMATTRS_HTTP_STATUS_CODE])){const s=null!==(t=e.attributes[d.ATTR_URL_FULL])&&void 0!==t?t:e.attributes[d.SEMATTRS_HTTP_URL];return!(!s||"string"!=typeof s||!se.exec(s))}return!1})(t)&&(t.attributes[e.KEY_EMB_TYPE]=e.EMB_TYPES.Network,null!==(s=(o=t.attributes)[d.ATTR_URL_FULL])&&void 0!==s||(o[d.ATTR_URL_FULL]=t.attributes[d.SEMATTRS_HTTP_URL]),null!==(n=(c=t.attributes)[d.ATTR_HTTP_RESPONSE_STATUS_CODE])&&void 0!==n||(c[d.ATTR_HTTP_RESPONSE_STATUS_CODE]=t.attributes[d.SEMATTRS_HTTP_STATUS_CODE]),null!==(r=(u=t.attributes)[d.ATTR_HTTP_REQUEST_METHOD])&&void 0!==r||(u[d.ATTR_HTTP_REQUEST_METHOD]=t.attributes[d.SEMATTRS_HTTP_METHOD]),null!==(i=(l=t.attributes)[g.ATTR_HTTP_RESPONSE_BODY_SIZE])&&void 0!==i||(l[g.ATTR_HTTP_RESPONSE_BODY_SIZE]=t.attributes[d.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH]),null!==(a=(h=t.attributes)[g.ATTR_HTTP_REQUEST_BODY_SIZE])&&void 0!==a||(h[g.ATTR_HTTP_REQUEST_BODY_SIZE]=t.attributes[d.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH]))}onStart(){}shutdown(){return Promise.resolve(void 0)}}class re{constructor({urlDocument:e=window.document}={}){this._urlDocument=e}forceFlush(){return Promise.resolve(void 0)}onEmit(t){t.attributes[e.KEY_EMB_TYPE]||t.setAttribute(e.KEY_EMB_TYPE,e.EMB_TYPES.SystemLog),t.setAttribute(d.ATTR_URL_FULL,this._urlDocument.URL)}shutdown(){return Promise.resolve(void 0)}}class ie{constructor({userManager:e}){this._userManager=e}forceFlush(){return Promise.resolve(void 0)}onEmit(e){this._userManager.getUserId()&&e.setAttributes({[g.ATTR_USER_ID]:this._userManager.getUserId()})}shutdown(){return Promise.resolve(void 0)}}class ae{constructor({userManager:e}){this._userManager=e}forceFlush(){return Promise.resolve(void 0)}onEnd(e){const t=this._userManager.getUserId();t&&(e.attributes[g.ATTR_USER_ID]=t)}onStart(){}shutdown(){return Promise.resolve(void 0)}}const oe="1.3.0",ce="embrace-web-sdk",ue="embrace_app_instance_id",le=(e,t)=>{let s=null;try{s=e.getItem(ue)}catch(e){t.warn("Failed to retrieve app instance ID from session storage",e)}if(!s){t.debug("No existing app instance ID found in session storage, creating a new one"),s=K();try{e.setItem(ue,s)}catch(e){t.warn("Failed to persist app instance ID to session storage",e)}}return s};class de extends e.EmbraceInstrumentationBase{constructor({diag:e,backgroundSessions:t=!1,visibilityDoc:s=window.document}={}){super({instrumentationName:"SpanSessionOnLoadInstrumentation",instrumentationVersion:"1.0.0",config:{},diag:e}),this._onVisibilityChange=()=>{this._diag.debug(`Visibility change detected: ${s.visibilityState}`),this.sessionManager.endSessionSpanInternal("state_changed"),"hidden"===s.visibilityState&&t?(this._diag.debug("Starting a session since document visibility switched to hidden and `backgroundSessions` is enabled"),this.sessionManager.startSessionSpan()):"visible"===s.visibilityState&&(this._diag.debug("Starting a session since document visibility switched to visible"),this.sessionManager.startSessionSpan())},this._config.enabled&&this.enable()}disable(){window.removeEventListener("visibilitychange",this._onVisibilityChange)}enable(){window.addEventListener("visibilitychange",this._onVisibilityChange)}}const ge=["keydown","mousedown","mousemove","scroll"];class he extends e.EmbraceInstrumentationBase{constructor({diag:e}={}){super({instrumentationName:"SpanSessionBrowserActivityInstrumentation",instrumentationVersion:"1.0.0",diag:e,config:{}}),this.disable=()=>{(({target:e,events:t,callback:s})=>{t.forEach((t=>{e.removeEventListener(t,s)}))})({target:window,events:ge,callback:this._onActivityThrottled}),this._activityTimeout&&clearTimeout(this._activityTimeout),this._activityTimeout=null},this.enable=()=>{(({target:e,events:t,callback:s})=>{t.forEach((t=>{e.addEventListener(t,s)}))})({target:window,events:ge,callback:this._onActivityThrottled})},this._onInactivity=()=>{this._diag.debug("Inactivity detected"),this._activityTimeout&&clearTimeout(this._activityTimeout),this._activityTimeout=null,this.sessionManager.endSessionSpanInternal("inactivity")},this._onActivity=()=>{this._diag.debug("Activity detected"),this._activityTimeout&&clearTimeout(this._activityTimeout),this.sessionManager.getSessionId()||this.sessionManager.startSessionSpan(),this._activityTimeout=setTimeout(this._onInactivity,18e5)},this._activityTimeout=null,this._onActivityThrottled=((e,t=1e3)=>{let s=!1;return(...n)=>{s||(e(...n),setTimeout((()=>{s=!1}),t),s=!0)}})(this._onActivity,3e4),this._config.enabled&&this.enable()}}class _e extends e.EmbraceInstrumentationBase{constructor({diag:e}={}){super({instrumentationName:"SpanSessionOnLoadInstrumentation",instrumentationVersion:"1.0.0",diag:e,config:{}}),this._config.enabled&&this.enable()}disable(){this.sessionManager.endSessionSpanInternal("unknown")}enable(){this.sessionManager.startSessionSpan()}}const pe=144e5;class me extends e.EmbraceInstrumentationBase{constructor({diag:e,perf:t}={}){super({instrumentationName:"SpanSessionTimeoutInstrumentation",instrumentationVersion:"1.0.0",diag:e,perf:t,config:{}}),this.disable=()=>{this._sessionTimeout&&clearTimeout(this._sessionTimeout),this._sessionTimeout=null},this.enable=()=>{this._checkTimeout()},this._onTimeout=()=>{this._diag.debug("Timeout detected"),this._sessionTimeout&&clearTimeout(this._sessionTimeout),this.sessionManager.endSessionSpanInternal("timer"),this.sessionManager.startSessionSpan(),this._sessionTimeout=setTimeout(this._checkTimeout,pe)},this._checkTimeout=()=>{const e=this.sessionManager.getSessionStartTime();if(e){const t=this.perf.getNowHRTime(),s=l.hrTimeToMilliseconds(t),n=l.hrTimeToMilliseconds(e),r=pe-(s-n);return r<=0?void this._onTimeout():(this._sessionTimeout&&clearTimeout(this._sessionTimeout),void(this._sessionTimeout=setTimeout(this._checkTimeout,r)))}this._sessionTimeout&&clearTimeout(this._sessionTimeout),this._sessionTimeout=setTimeout(this._checkTimeout,pe)},this._sessionTimeout=null,this._config.enabled&&this.enable()}}class Se extends e.EmbraceInstrumentationBase{constructor({diag:e,perf:t}={}){super({instrumentationName:"GlobalExceptionInstrumentation",instrumentationVersion:"1.0.0",diag:e,perf:t,config:{}}),this._onErrorHandler=e=>{this.logManager.logException(e.error,{handled:!1,timestamp:this.perf.epochMillisFromOriginOffset(e.timeStamp)})},this._onUnhandledRejectionHandler=e=>{let t;e.reason&&e.reason instanceof Error?t=e.reason:(t=new Error("string"==typeof e.reason?e.reason:"Unhandled Rejected Promise"),t.stack=""),this.logManager.logException(t,{handled:!1,timestamp:this.perf.epochMillisFromOriginOffset(e.timeStamp)})},this._config.enabled&&this.enable()}disable(){window.removeEventListener("error",this._onErrorHandler),window.removeEventListener("unhandledrejection",this._onUnhandledRejectionHandler)}enable(){window.addEventListener("error",this._onErrorHandler),window.addEventListener("unhandledrejection",this._onUnhandledRejectionHandler)}}const Te=e=>{const t=e.nodeName.toLowerCase(),s=e.innerText.substring(0,30),n=e.innerText.length>30?"...":"";return`<${t}${e.className?` class="${e.className}"`:""}>${s}${n}</${t}>`};class Ee extends e.EmbraceInstrumentationBase{constructor({diag:e,perf:t}={}){super({instrumentationName:"SpanSessionBrowserActivityInstrumentation",instrumentationVersion:"1.0.0",diag:e,perf:t,config:{}}),this._onClickHandler=e=>{const t=e.target;if(t instanceof HTMLElement&&!t.hasAttribute("disabled"))try{const s=this.sessionManager.getSessionSpan();s&&s.addEvent("click",{"emb.type":"ux.tap","view.name":Te(t),"tap.coords":`${e.x.toString()},${e.y.toString()}`},this.perf.epochMillisFromOriginOffset(e.timeStamp))}catch(e){this._diag.error("failed to create new user interaction span event",e)}},this._config.enabled&&this.enable()}disable(){document.removeEventListener("click",this._onClickHandler)}enable(){document.addEventListener("click",this._onClickHandler)}}const be=["CLS","INP","LCP"],ve=["CLS","INP","LCP","FCP","TTFB"],we={CLS:p.onCLS,FCP:p.onFCP,LCP:p.onLCP,INP:p.onINP,TTFB:p.onTTFB,FID:void 0};class ye extends e.EmbraceInstrumentationBase{constructor({diag:e,perf:t,trackingLevel:s="core",listeners:n=we,urlDocument:r=window.document}={}){super({instrumentationName:"WebVitalsInstrumentation",instrumentationVersion:"1.0.0",diag:e,perf:t,config:{}}),this._listeners=n,this._urlDocument=r,this._metricsToTrack="core"===s?[...be]:[...ve],this._config.enabled&&this.enable()}disable(){}enable(){this._metricsToTrack.forEach((t=>{var s,n;null===(n=(s=this._listeners)[t])||void 0===n||n.call(s,(s=>{const n=this.sessionManager.getSessionSpan();if(!n)return;const r=this._getTimeForMetric(s),i=Object.assign({[e.KEY_EMB_TYPE]:e.EMB_TYPES.WebVital,[d.ATTR_URL_FULL]:this._urlDocument.URL,"emb.web_vital.navigation_type":s.navigationType,"emb.web_vital.name":s.name,"emb.web_vital.rating":s.rating,"emb.web_vital.id":s.id,"emb.web_vital.delta":s.delta,"emb.web_vital.value":s.value},((e,t)=>{const s={},n=[];if("CLS"===e){const e=t.attribution;n.push({key:"largestShiftTarget",value:e.largestShiftTarget},{key:"largestShiftValue",value:e.largestShiftValue})}else if("INP"===e){const e=t.attribution;n.push({key:"interactionTarget",value:e.interactionTarget},{key:"interactionType",value:e.interactionType},{key:"nextPaintTime",value:e.nextPaintTime},{key:"inputDelay",value:e.inputDelay},{key:"processingDuration",value:e.processingDuration},{key:"presentationDelay",value:e.presentationDelay},{key:"totalScriptDuration",value:e.totalScriptDuration},{key:"totalStyleAndLayoutDuration",value:e.totalStyleAndLayoutDuration},{key:"totalPaintDuration",value:e.totalPaintDuration},{key:"totalUnattributedDuration",value:e.totalUnattributedDuration},{key:"loadState",value:e.loadState})}else if("LCP"===e){const e=t.attribution;n.push({key:"target",value:e.target},{key:"url",value:e.url},{key:"timeToFirstByte",value:e.timeToFirstByte},{key:"resourceLoadDelay",value:e.resourceLoadDelay},{key:"resourceLoadDuration",value:e.resourceLoadDuration},{key:"elementRenderDelay",value:e.elementRenderDelay})}return n.forEach((e=>{void 0!==e.value&&(s[`emb.web_vital.attribution.${e.key}`]=e.value)})),s})(t,s));n.addEvent(`emb-web-vitals-report-${t}`,i,r)}))}))}_getTimeForMetric(e){return"CLS"===e.name&&e.attribution.largestShiftTime?this.perf.epochMillisFromOriginOffset(e.attribution.largestShiftTime):"INP"===e.name&&e.attribution.interactionTime?this.perf.epochMillisFromOriginOffset(e.attribution.interactionTime):this.perf.getNowMillis()}}const Ie=(e={})=>{var t,s,n,r,i,a;const o=[new _e(e["session-on-load"]),new de(e["session-visibility"]),new he(e["session-activity"]),new me(e["session-timeout"])];return(null===(t=e.omit)||void 0===t?void 0:t.has("exception"))||o.push(new Se(e.exception)),(null===(s=e.omit)||void 0===s?void 0:s.has("click"))||o.push(new Ee(e.click)),(null===(n=e.omit)||void 0===n?void 0:n.has("web-vital"))||o.push(new ye(e["web-vital"])),(null===(r=e.omit)||void 0===r?void 0:r.has("@opentelemetry/instrumentation-document-load"))||o.push(new m.DocumentLoadInstrumentation(e["@opentelemetry/instrumentation-document-load"])),(null===(i=e.omit)||void 0===i?void 0:i.has("@opentelemetry/instrumentation-fetch"))||o.push(new S.FetchInstrumentation(e["@opentelemetry/instrumentation-fetch"])),(null===(a=e.omit)||void 0===a?void 0:a.has("@opentelemetry/instrumentation-xml-http-request"))||o.push(new T.XMLHttpRequestInstrumentation(e["@opentelemetry/instrumentation-xml-http-request"])),o};const fe=new class{constructor({diagLogger:e=t.diag.createComponentLogger({namespace:"embrace-registry"})}={}){this._sdk=null,this.register=e=>{null!==this._sdk&&this._diag.warn("previously registered sdk will be overwritten"),this._sdk=e},this.clear=()=>{null===this._sdk&&this._diag.warn("sdk already cleared, this is a no-op"),this._sdk=null},this.registered=()=>this._sdk,this._diag=e}},Me=()=>{const e=new J;return R.setGlobalUserManager(e),e},De=()=>{const t=new G;return e.session.setGlobalSessionManager(t),t},Le=({sendingToEmbrace:e,appID:t,enduserPseudoID:s,resource:n,spanSessionManager:r,userManager:i,spanExporters:o,spanProcessors:c=[],propagator:u=null,contextManager:l=null})=>{const d=new $;I.setGlobalTraceManager(d);const g=[...c,E.createSessionSpanProcessor(r),new ne,new ae({userManager:i})];null==o||o.forEach((e=>{g.push(new a.BatchSpanProcessor(e))})),e&&t&&s&&g.push(new ee({exporter:new k({appID:t,userID:s})}));const h=new a.WebTracerProvider({resource:n,spanProcessors:g});return h.register({contextManager:l,propagator:u}),h},Re=({sendingToEmbrace:t,appID:n,enduserPseudoID:r,resource:a,userManager:o,logExporters:c,logProcessors:u,spanSessionManager:l})=>{const d=new V({spanSessionManager:l});e.log.setGlobalLogManager(d);const g=new i.LoggerProvider({resource:a}),h=[...u,new te({spanSessionManager:l}),new re,new ie({userManager:o})];null==c||c.forEach((e=>{h.push(new i.BatchLogRecordProcessor(e))})),t&&n&&r&&h.push(new i.BatchLogRecordProcessor(new A({appID:n,userID:r})));for(const e of h)g.addLogRecordProcessor(e);return s.logs.setGlobalLoggerProvider(g),g};var Pe=Object.freeze({__proto__:null,DiagLogLevel:t.DiagLogLevel,initSDK:({appID:s,appVersion:i,templateBundleID:a,resource:o=r.Resource.empty(),spanExporters:c=[],logExporters:u=[],spanProcessors:l=[],propagator:g=null,defaultInstrumentationConfig:h,instrumentations:p=[],contextManager:m=null,logProcessors:S=[],logLevel:T=t.DiagLogLevel.ERROR,diagLogger:E=t.diag.createComponentLogger({namespace:"embrace-sdk"})}={appID:""})=>{try{const b=fe.registered();if(null!==b)return E.warn("SDK has already been successfully initialized, skipping this invocation of initSDK"),b;if(t.diag.setLogger(new t.DiagConsoleLogger,{logLevel:T}),a&&32!==a.length)throw new Error("templateBundleID should be 32 characters long");const v=o.merge((({diagLogger:t,appVersion:s,templateBundleID:n,pageSessionStorage:i})=>{const a=null!=s?s:"EmbIOAppVersionX.X.X".trim();let o=new r.Resource({[d.ATTR_SERVICE_NAME]:ce,[d.ATTR_TELEMETRY_SDK_NAME]:ce,app_version:a,app_framework:1,bundle_id:null!=n?n:"EmbIOBundleIDfd6996f1007b363f87a",sdk_version:oe,[d.ATTR_TELEMETRY_SDK_VERSION]:oe,sdk_simple_version:1,sdk_platform:"web",[d.ATTR_TELEMETRY_SDK_LANGUAGE]:"webjs",[e.KEY_EMB_APP_INSTANCE_ID]:le(i,t)});const c=r.detectResourcesSync({detectors:[_.browserDetector]});return o=o.merge(c),o})({diagLogger:E,appVersion:i,templateBundleID:a,pageSessionStorage:window.sessionStorage})),w=!!s&&(e=>{if(void 0===e)throw new Error("appID is required when using Embrace exporter");if(5!==e.length)throw new Error("appID should be 5 characters long");return!0})(s);if(!w&&!u.length&&!c.length)throw new Error("when the embrace appID is omitted then at least one logExporter or spanExporter must be set");const y=Me(),I=y.getEmbraceUserId();if(w&&!I)throw new Error("userID is required when using Embrace exporter");const f=De(),M=Le({sendingToEmbrace:w,appID:s,enduserPseudoID:I,resource:v,spanSessionManager:f,userManager:y,spanExporters:c,spanProcessors:l,propagator:g,contextManager:m}),D=Re({sendingToEmbrace:w,appID:s,enduserPseudoID:I,resource:v,userManager:y,logExporters:u,logProcessors:S,spanSessionManager:f});n.registerInstrumentations({instrumentations:[...p,Ie(h)]}),E.info("successfully initialized the SDK");const L={flush:async()=>{await M.forceFlush(),await D.forceFlush()}};return fe.register(L),L}catch(e){const t=e instanceof Error?e.message:"Unknown error.";return E.error(`failed to initialize the SDK: ${t}`),!1}}});exports.log=e.log,exports.session=e.session,exports.sdk=Pe,exports.trace=I,exports.user=R;
//# sourceMappingURL=index.js.map