@groundcover/browser 0.0.28 → 0.0.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -140,7 +140,7 @@ type EventTypes = {
|
|
|
140
140
|
interface SDKOptions {
|
|
141
141
|
batchSize: number;
|
|
142
142
|
batchTimeout: number;
|
|
143
|
-
enabledEvents: Array<"dom" | "network" | "
|
|
143
|
+
enabledEvents: Array<"dom" | "network" | "exceptions" | "logs" | "pageload" | "navigation" | "performance">;
|
|
144
144
|
eventSampleRate: number;
|
|
145
145
|
sessionSampleRate: number;
|
|
146
146
|
environment: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -140,7 +140,7 @@ type EventTypes = {
|
|
|
140
140
|
interface SDKOptions {
|
|
141
141
|
batchSize: number;
|
|
142
142
|
batchTimeout: number;
|
|
143
|
-
enabledEvents: Array<"dom" | "network" | "
|
|
143
|
+
enabledEvents: Array<"dom" | "network" | "exceptions" | "logs" | "pageload" | "navigation" | "performance">;
|
|
144
144
|
eventSampleRate: number;
|
|
145
145
|
sessionSampleRate: number;
|
|
146
146
|
environment: string;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("error-stack-parser"),t=require("web-vitals");function n(e){return e&&e.__esModule?e:{default:e}}var s=n(e),i=console.log.bind(console),r=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&i(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},o=r.getInstance();function a(e){o.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var l={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,maskFields:[],enabledEvents:["dom","network","error","log"],tracePropagationUrls:[]},c=class{constructor(e){this.dsn=e.dsn,this.appId=e.appId,this.cluster=e.cluster,this.apiKey=e.apiKey,this.environment=e.environment,this.namespace=e.namespace,this.userIdentifier=e.userIdentifier||null,this.options={...l,...e.options}}getEndpoint(){return this.dsn}},h=class{constructor(){this.generateTraceId=u(16),this.generateSpanId=u(8),this.generateId=u(16)}},d=Array(32);function u(e){return function(){for(let t=0;t<2*e;t++)d[t]=Math.floor(16*Math.random())+48,d[t]>=58&&(d[t]+=39);return String.fromCharCode.apply(null,d.slice(0,2*e))}}var g=class e{constructor(){this.config=null,this.logger=r.getInstance(),this.sessionId=null,this.idGenerator=new h}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new c(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;const e=globalThis?.sessionStorage?.getItem("gcId");return e||""}setSessionId(e){this.sessionId=e,globalThis?.sessionStorage?.setItem("gcId",e)}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...e.options}),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},p="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},m=g.getInstance(),f=new h;function v(){const e=m?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function y(e,t=""){return Object.entries(e).reduce(((e,[n,s])=>{const i=t?`${t}.${n}`:n;return"object"==typeof s&&null!==s?Object.assign(e,y(s,i)):e[i]=s,e}),{})}function E(e){const t=1e6*Date.now(),n=f.generateId(),s=e.spanId||f.generateSpanId(),i=e.traceId||f.generateTraceId(),r=e.parentSpanId||"",o=y(e.attributes||{}),a={path:p?.location?.pathname,url:p?.location?.href,title:p?.document?.title},l={type:e.type,id:n,spanId:s,parentSpanId:r,traceId:i,attributes:{...o,location:a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var b=class{constructor(){this.logger=r.getInstance(),this.config=g.getInstance()}async send(e){const t=this.config.getConfig();if(t)try{t.options.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,s=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");fetch(s,{method:"POST",headers:{"Content-Type":"application/json",apikey:n},body:JSON.stringify(e)})}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},I=class e{constructor(){this.events=[],this.timeoutId=null,this.config=g.getInstance(),this.initialized=!1,this.transporter=new b}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",(()=>{this.flush()})),this.initialized=!0}catch(e){a(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend;if(t&&!t(e))return;this.events.push(e);const n=this.config.getConfig()?.options?.batchSize||100;this.events.length>=n&&"dom.event"!==e.type&&this.flush()}catch(e){a(e)}}flush(){try{if(0===this.events.length||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){a(e)}}scheduleFlush(){try{null!==this.timeoutId&&(p.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=p.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){a(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const s=navigator.platform||"unknown",i=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:s,language:navigator.language,mobile:i}}getSessionAttributes(){const e=this.detectBrowser();return{cluster:this.config.getConfig()?.cluster||"",env:this.config.getConfig()?.environment||"",namespace:this.config.getConfig()?.namespace||"",session_id:this.config.getSessionId(),user:this.config.getConfig()?.userIdentifier||{},"service.name":this.config.getConfig()?.appId,userAgent:navigator.userAgent,browser:e}}};I.instance=null;var w=I,T=class{constructor(){this.logger=r.getInstance(),this.eventsPool=w.getInstance()}};function L({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var _,S=class extends T{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.getAttribute("data-private")].some((e=>e)),this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>L({text:e.target.innerText||""}),this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){a(e)}};this.eventHandlers.push({type:e,handler:t}),p?.addEventListener(e,t)}))}catch(e){a(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),s=e.target,i=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return E({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:i,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:s.id,tagName:s.tagName,className:s.className,text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,s=t.maxAttempts||10,i=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===e.tagName?.toLowerCase())return"html";let r="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<s;){let e=a.tagName?.toLowerCase()||"";try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of i)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=a.tagName?.toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return r||"*"}},C=["log","info","warn","error","assert","trace"],q=class extends T{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),C.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){a(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){a(e)}}destroy(){try{if(!this.isInitialized)return;C.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){a(e)}}handleEvent(e,t){try{if(!v())return;const n=this.formatMessage(Array.isArray(e)?e:[e]);if(!n||n?.includes("groundcoverIgnore"))return;const s=this.buildEvent({message:n,level:t});this.queueEvent(s)}catch(e){a(e)}}buildEvent({message:e,level:t}){return E({type:"log",attributes:{message:L({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e)try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}catch(e){return a(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{C.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){a(e)}return e}},z=class extends T{constructor(){super(...arguments),this.config=g.getInstance(),this.idGenerator=new h,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),i=e.request.headers.traceparent,r=i?.split("-")?.[1]||"",o=i?.split("-")?.[2]||"",a={type:"HTTP",operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{url:{full:n},route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:e.request.body},response:{body:e.response.body}}};return E({type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?1e6*e.timestamp:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?1e6*e.end_time:void 0,span_name:`${e.method} ${t}`,attributes:a,traceId:r,spanId:o})}}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return a(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,s=globalThis.XMLHttpRequest.prototype.setRequestHeader;let i;globalThis.XMLHttpRequest.prototype.open=function(n,s,r=!0,o,a){if(i=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[n,s,r,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,s,r,o,a])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),s.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const s=this._requestUrl.toString();if(!s||e.shouldIgnoreRequest(s))return n.apply(this,t);if(e.shouldAddTraceHeader(s)){const t=e.getTraceparentHeader();t&&(this.setRequestHeader("traceparent",t.traceparent),this._requestHeaders.traceparent=t.traceparent)}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,s]=e.split(": ");t&&s&&(n[t.trim()]=s.trim())}));const s={timestamp:i,end_time:t,method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:n,body:this.responseText||this.response||""}};e.handleEvent(s)})),n.apply(this,t)}}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[s,i]=t;i={...i||{}};const r=i?.method||"GET",o=i?.body||"",a=s instanceof Request?s.url:s.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);if(i&&!i.headers&&(i.headers={}),i||(t[1]={},i=t[1]),l){const e=this.getTraceparentHeader();e&&(i?.headers instanceof Headers?i.headers.set("traceparent",e.traceparent):i.headers={...i.headers,traceparent:e.traceparent})}const c={};return i?.headers&&(i.headers instanceof Headers?i.headers.forEach(((e,t)=>{c[t]=e})):"object"==typeof i.headers&&Object.assign(c,i.headers)),e.apply(globalThis,t).then((async e=>{const t=Date.now(),s=e.clone();let i="";const l={};s.headers.forEach(((e,t)=>{l[t]=e}));try{i="text/event-stream"===l["content-type"]?"[unreadable response body]":await s.text()}catch(e){i="[unreadable response body]"}this.logger.log("[network-events-listener.patchFetch] called",{url:a});const h={method:r,url:a,timestamp:n,body:o.toString(),status:s.status,end_time:t,request:{headers:c,body:o.toString()},response:{headers:l,body:i}};return this.handleEvent(h),e})).catch((e=>{const t=Date.now();let n="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const i={method:r,url:a,body:o.toString(),status:0,end_time:t,request:{headers:c,body:o.toString()},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(i),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,s])=>{const i=n.toLowerCase();return t.includes(i)||/(token|key|secret|password)/i.test(i)?e[n]="[REDACTED]":e[n]=L({text:s}),e}),{})}getTraceparentHeader(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e}}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t||!t.options.tracePropagationUrls||!t.options.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls.some((t=>{const n=t.replace(/\*/g,".*"),s=new RegExp(`^${n}$`),i=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return s.test(i)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},R=class extends T{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const s=this.buildEvent(n,t);this.queueEvent(s)}catch(e){a(e)}}}initialize(){p?.addEventListener("error",this.handleEvent),p?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){p?.removeEventListener("error",this.handleEvent),p?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return E({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${L({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}enhanceError(e,t){const{filename:n,lineno:s,colno:i}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),s&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:s}),i&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:i})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(e){if(!e)return[];try{return s.default.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},x=class extends T{constructor(){super(...arguments),this.currentUrl=globalThis.location.href,this.mutationObserver=null}initialize(){if(p.MutationObserver){const e=p.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver((()=>{this.handleUrlChange()})),this.mutationObserver.observe(e,{childList:!0,subtree:!0,attributes:!0}))}p?.addEventListener("popstate",(()=>{this.handleUrlChange()}))}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){a(e)}}buildEvent(){return E({type:"navigation",attributes:{page_url:globalThis.location.href}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}handleUrlChange(){this.logger.log("[navigation-listener.handleUrlChange] called");const e=new URL(globalThis.location.href),t=new URL(this.currentUrl);e.pathname!==t.pathname&&(this.currentUrl=globalThis.location.href,this.handleEvent())}},N=class extends T{constructor(){super(),this.startTime=performance.now()}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),p?.addEventListener("load",(()=>{this.handleEvent()}))}catch(e){a(e)}}destroy(){p?.removeEventListener("load",this.handleEvent)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){a(e)}}buildEvent(){const e=performance.now()-this.startTime,t=performance.getEntriesByType("resource"),n={count:t.length,totalSize:0,totalDuration:0,byType:{}};t.forEach((e=>{const t=e,s=t.transferSize||0,i=t.duration,r=t.initiatorType;n.totalSize+=s,n.totalDuration+=i,n.byType[r]||(n.byType[r]={count:0,size:0,duration:0}),n.byType[r].count++,n.byType[r].size+=s,n.byType[r].duration+=i}));return E({type:"pageload",attributes:{page_url:p?.location?.href||"",page_load_time:e,page_referrer:p?.document?.referrer||"",page_resources:n}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}},k=class extends T{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}}}initialize(){t.onCLS(this.handleEvent),t.onLCP(this.handleEvent),t.onFCP(this.handleEvent),t.onTTFB(this.handleEvent),t.onINP(this.handleEvent)}destroy(){}buildEvent(e){return E({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}},H=class{constructor(){this.logger=r.getInstance(),this.eventsPool=w.getInstance(),this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.domEventsListener=new S,this.logEventsListener=new q,this.errorsEventsListener=new R,this.networkEventsListener=new z,this.navigationListener=new x,this.performanceListener=new k,this.pageLoadListener=new N,this.domEventsListener.initialize(),this.logEventsListener.initialize(),this.errorsEventsListener.initialize(),this.networkEventsListener.initialize(),this.navigationListener.initialize(),this.performanceListener.initialize(),this.pageLoadListener.initialize(),this.logger.log("[instrumentation-manager.instrument] initialized listeners")}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=E({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){a(e)}}captureException(e){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0})}catch(e){a(e)}}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy()}},M="gcSample",U=class{constructor(e){this.initialized=!1,this.logger=r.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new H,this.idGenerator=new h;if(!this.getSamplingDecision(e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=g.getInstance();t.initialize(e);w.getInstance().initialize();t.getSessionId()||t.setSessionId(this.idGenerator.generateId()),this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=globalThis.sessionStorage?.getItem(M);if(t){const e="1"===t;return this.logger.log("[session-manager] using stored sampling decision:",e),e}const n=!e||Math.random()<e;return globalThis?.sessionStorage?.setItem(M,n?"1":"0"),this.logger.log("[session-manager] stored new sampling decision:",n),n}catch(t){this.logger.log("[session-manager] session storage access failed:",t);const n=!e||Math.random()<e;return this.logger.log("[session-manager] using fallback sampling decision:",n),n}}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");g.getInstance().updateConfig({userIdentifier:e})}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}captureException(e){this.initialized?this.instrumentationManager.captureException(e):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),globalThis.sessionStorage?.removeItem("gcId"),this.initialized=!1)}};var j={init:function(e){try{_=new U({cluster:e?.cluster,environment:e?.environment,namespace:e?.namespace,dsn:e?.dsn,appId:e?.appId,userIdentifier:e?.userIdentifier,apiKey:e?.apiKey,options:e?.options})}catch(e){a(e)}},identifyUser:function(e){_?_.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){_&&_.sendCustomEvent(e)},captureException:function(e){_&&_.captureException(e)}};module.exports=j;
|
|
1
|
+
"use strict";var e=require("error-stack-parser"),t=require("web-vitals");function n(e){return e&&e.__esModule?e:{default:e}}var s=n(e),i=console.log.bind(console),r=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&i(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},o=r.getInstance();function a(e){o.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var l={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,maskFields:[],enabledEvents:[],tracePropagationUrls:[]},c=class{constructor(e){this.dsn=e.dsn,this.appId=e.appId,this.cluster=e.cluster,this.apiKey=e.apiKey,this.environment=e.environment,this.namespace=e.namespace,this.userIdentifier=e.userIdentifier||null,this.options={...l,...e.options}}getEndpoint(){return this.dsn}},d=class{constructor(){this.generateTraceId=u(16),this.generateSpanId=u(8),this.generateId=u(16)}},h=Array(32);function u(e){return function(){for(let t=0;t<2*e;t++)h[t]=Math.floor(16*Math.random())+48,h[t]>=58&&(h[t]+=39);return String.fromCharCode.apply(null,h.slice(0,2*e))}}var g=class e{constructor(){this.config=null,this.logger=r.getInstance(),this.sessionId=null,this.idGenerator=new d}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new c(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;const e=globalThis?.sessionStorage?.getItem("gcId");return e||""}setSessionId(e){this.sessionId=e,globalThis?.sessionStorage?.setItem("gcId",e)}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...e.options}),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},p="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},m=g.getInstance(),f=new d;function v(){const e=m?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function y(e,t=""){return Object.entries(e).reduce(((e,[n,s])=>{const i=t?`${t}.${n}`:n;return"object"==typeof s&&null!==s?Object.assign(e,y(s,i)):e[i]=s,e}),{})}function E(e){const t=1e6*Date.now(),n=f.generateId(),s=e.spanId||f.generateSpanId(),i=e.traceId||f.generateTraceId(),r=e.parentSpanId||"",o=y(e.attributes||{}),a={path:p?.location?.pathname,url:p?.location?.href,title:p?.document?.title},l={type:e.type,id:n,spanId:s,parentSpanId:r,traceId:i,attributes:{...o,location:a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var b=class{constructor(){this.logger=r.getInstance(),this.config=g.getInstance()}async send(e){const t=this.config.getConfig();if(t)try{t.options.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,s=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");fetch(s,{method:"POST",headers:{"Content-Type":"application/json",apikey:n},body:JSON.stringify(e)})}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},I=class e{constructor(){this.events=[],this.timeoutId=null,this.config=g.getInstance(),this.initialized=!1,this.transporter=new b}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",(()=>{this.flush()})),this.initialized=!0}catch(e){a(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend;if(t&&!t(e))return;this.events.push(e);const n=this.config.getConfig()?.options?.batchSize||100;this.events.length>=n&&"dom.event"!==e.type&&this.flush()}catch(e){a(e)}}flush(){try{if(0===this.events.length||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){a(e)}}scheduleFlush(){try{null!==this.timeoutId&&(p.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=p.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){a(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const s=navigator.platform||"unknown",i=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:s,language:navigator.language,mobile:i}}getSessionAttributes(){const e=this.detectBrowser();return{cluster:this.config.getConfig()?.cluster||"",env:this.config.getConfig()?.environment||"",namespace:this.config.getConfig()?.namespace||"",session_id:this.config.getSessionId(),user:this.config.getConfig()?.userIdentifier||{},"service.name":this.config.getConfig()?.appId,userAgent:navigator.userAgent,browser:e}}};I.instance=null;var w=I,T=class{constructor(){this.logger=r.getInstance(),this.eventsPool=w.getInstance()}};function L({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var _,S=class extends T{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.getAttribute("data-private")].some((e=>e)),this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>L({text:e.target.innerText||""}),this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){a(e)}};this.eventHandlers.push({type:e,handler:t}),p?.addEventListener(e,t)}))}catch(e){a(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),s=e.target,i=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return E({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:i,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:s.id,tagName:s.tagName,className:s.className,text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,s=t.maxAttempts||10,i=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===e.tagName?.toLowerCase())return"html";let r="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<s;){let e=a.tagName?.toLowerCase()||"";try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of i)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=a.tagName?.toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return r||"*"}},C=["log","info","warn","error","assert","trace"],q=class extends T{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),C.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){a(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){a(e)}}destroy(){try{if(!this.isInitialized)return;C.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){a(e)}}handleEvent(e,t){try{if(!v())return;const n=this.formatMessage(Array.isArray(e)?e:[e]);if(!n||n?.includes("groundcoverIgnore"))return;const s=this.buildEvent({message:n,level:t});this.queueEvent(s)}catch(e){a(e)}}buildEvent({message:e,level:t}){return E({type:"log",attributes:{message:L({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e)try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}catch(e){return a(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{C.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){a(e)}return e}},z=class extends T{constructor(){super(...arguments),this.config=g.getInstance(),this.idGenerator=new d,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),i=e.request.headers.traceparent,r=i?.split("-")?.[1]||"",o=i?.split("-")?.[2]||"",a={type:"HTTP",operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{url:{full:n},route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:e.request.body},response:{body:e.response.body}}};return E({type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?1e6*e.timestamp:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?1e6*e.end_time:void 0,span_name:`${e.method} ${t}`,attributes:a,traceId:r,spanId:o})}}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return a(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,s=globalThis.XMLHttpRequest.prototype.setRequestHeader;let i;globalThis.XMLHttpRequest.prototype.open=function(n,s,r=!0,o,a){if(i=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[n,s,r,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,s,r,o,a])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),s.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const s=this._requestUrl.toString();if(!s||e.shouldIgnoreRequest(s))return n.apply(this,t);if(e.shouldAddTraceHeader(s)){const t=e.getTraceparentHeader();t&&(this.setRequestHeader("traceparent",t.traceparent),this._requestHeaders.traceparent=t.traceparent)}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,s]=e.split(": ");t&&s&&(n[t.trim()]=s.trim())}));const s={timestamp:i,end_time:t,method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:n,body:this.responseText||this.response||""}};e.handleEvent(s)})),n.apply(this,t)}}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[s,i]=t;i={...i||{}};const r=i?.method||"GET",o=i?.body||"",a=s instanceof Request?s.url:s.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);if(i&&!i.headers&&(i.headers={}),i||(t[1]={},i=t[1]),l){const e=this.getTraceparentHeader();e&&(i?.headers instanceof Headers?i.headers.set("traceparent",e.traceparent):i.headers={...i.headers,traceparent:e.traceparent})}const c={};return i?.headers&&(i.headers instanceof Headers?i.headers.forEach(((e,t)=>{c[t]=e})):"object"==typeof i.headers&&Object.assign(c,i.headers)),e.apply(globalThis,t).then((async e=>{const t=Date.now(),s=e.clone();let i="";const l={};s.headers.forEach(((e,t)=>{l[t]=e}));try{i="text/event-stream"===l["content-type"]?"[unreadable response body]":await s.text()}catch(e){i="[unreadable response body]"}this.logger.log("[network-events-listener.patchFetch] called",{url:a});const d={method:r,url:a,timestamp:n,body:o.toString(),status:s.status,end_time:t,request:{headers:c,body:o.toString()},response:{headers:l,body:i}};return this.handleEvent(d),e})).catch((e=>{const t=Date.now();let n="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const i={method:r,url:a,body:o.toString(),status:0,end_time:t,request:{headers:c,body:o.toString()},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(i),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,s])=>{const i=n.toLowerCase();return t.includes(i)||/(token|key|secret|password)/i.test(i)?e[n]="[REDACTED]":e[n]=L({text:s}),e}),{})}getTraceparentHeader(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e}}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t||!t.options.tracePropagationUrls||!t.options.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls.some((t=>{const n=t.replace(/\*/g,".*"),s=new RegExp(`^${n}$`),i=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return s.test(i)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},x=class extends T{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const s=this.buildEvent(n,t);this.queueEvent(s)}catch(e){a(e)}}}initialize(){p?.addEventListener("error",this.handleEvent),p?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){p?.removeEventListener("error",this.handleEvent),p?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return E({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${L({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}enhanceError(e,t){const{filename:n,lineno:s,colno:i}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),s&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:s}),i&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:i})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(e){if(!e)return[];try{return s.default.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},R=class extends T{constructor(){super(...arguments),this.currentUrl=globalThis.location.href,this.mutationObserver=null}initialize(){if(p.MutationObserver){const e=p.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver((()=>{this.handleUrlChange()})),this.mutationObserver.observe(e,{childList:!0,subtree:!0,attributes:!0}))}p?.addEventListener("popstate",(()=>{this.handleUrlChange()}))}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){a(e)}}buildEvent(){return E({type:"navigation",attributes:{page_url:globalThis.location.href}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}handleUrlChange(){this.logger.log("[navigation-listener.handleUrlChange] called");const e=new URL(globalThis.location.href),t=new URL(this.currentUrl);e.pathname!==t.pathname&&(this.currentUrl=globalThis.location.href,this.handleEvent())}},k=class extends T{constructor(){super(),this.startTime=performance.now()}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),p?.addEventListener("load",(()=>{this.handleEvent()}))}catch(e){a(e)}}destroy(){p?.removeEventListener("load",this.handleEvent)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){a(e)}}buildEvent(){const e=performance.now()-this.startTime,t=performance.getEntriesByType("resource"),n={count:t.length,totalSize:0,totalDuration:0,byType:{}};t.forEach((e=>{const t=e,s=t.transferSize||0,i=t.duration,r=t.initiatorType;n.totalSize+=s,n.totalDuration+=i,n.byType[r]||(n.byType[r]={count:0,size:0,duration:0}),n.byType[r].count++,n.byType[r].size+=s,n.byType[r].duration+=i}));return E({type:"pageload",attributes:{page_url:p?.location?.href||"",page_load_time:e,page_referrer:p?.document?.referrer||"",page_resources:n}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}},N=class extends T{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!v())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){a(e)}}}initialize(){t.onCLS(this.handleEvent),t.onLCP(this.handleEvent),t.onFCP(this.handleEvent),t.onTTFB(this.handleEvent),t.onINP(this.handleEvent)}destroy(){}buildEvent(e){return E({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){a(e)}}},M=class{constructor(){this.logger=r.getInstance(),this.eventsPool=w.getInstance(),this.configManager=g.getInstance(),this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called");const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,s=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new k,this.pageLoadListener.initialize(),s.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new S,this.domEventsListener.initialize(),s.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new q,this.logEventsListener.initialize(),s.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new x,this.errorsEventsListener.initialize(),s.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new z,this.networkEventsListener.initialize(),s.push("network")),(n||t?.includes("navigation"))&&(this.navigationListener=new R,this.navigationListener.initialize(),s.push("navigation")),(n||t?.includes("performance"))&&(this.performanceListener=new N,this.performanceListener.initialize(),s.push("performance")),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",s)}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=E({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){a(e)}}captureException(e){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0})}catch(e){a(e)}}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy()}},H="gcSample",U=class{constructor(e){this.initialized=!1,this.logger=r.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new M,this.idGenerator=new d;if(!this.getSamplingDecision(e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=g.getInstance();t.initialize(e);w.getInstance().initialize();t.getSessionId()||t.setSessionId(this.idGenerator.generateId()),this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=globalThis.sessionStorage?.getItem(H);if(t){const e="1"===t;return this.logger.log("[session-manager] using stored sampling decision:",e),e}const n=!e||Math.random()<e;return globalThis?.sessionStorage?.setItem(H,n?"1":"0"),this.logger.log("[session-manager] stored new sampling decision:",n),n}catch(t){this.logger.log("[session-manager] session storage access failed:",t);const n=!e||Math.random()<e;return this.logger.log("[session-manager] using fallback sampling decision:",n),n}}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");g.getInstance().updateConfig({userIdentifier:e})}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}captureException(e){this.initialized?this.instrumentationManager.captureException(e):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),globalThis.sessionStorage?.removeItem("gcId"),this.initialized=!1)}};var j={init:function(e){try{_=new U({cluster:e?.cluster,environment:e?.environment,namespace:e?.namespace,dsn:e?.dsn,appId:e?.appId,userIdentifier:e?.userIdentifier,apiKey:e?.apiKey,options:e?.options})}catch(e){a(e)}},identifyUser:function(e){_?_.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){_&&_.sendCustomEvent(e)},captureException:function(e){_&&_.captureException(e)}};module.exports=j;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"error-stack-parser";import{onCLS as t,onLCP as n,onFCP as s,onTTFB as i,onINP as r}from"web-vitals";var o=console.log.bind(console),a=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&o(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},l=a.getInstance();function c(e){l.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var h={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,maskFields:[],enabledEvents:["dom","network","error","log"],tracePropagationUrls:[]},d=class{constructor(e){this.dsn=e.dsn,this.appId=e.appId,this.cluster=e.cluster,this.apiKey=e.apiKey,this.environment=e.environment,this.namespace=e.namespace,this.userIdentifier=e.userIdentifier||null,this.options={...h,...e.options}}getEndpoint(){return this.dsn}},u=class{constructor(){this.generateTraceId=p(16),this.generateSpanId=p(8),this.generateId=p(16)}},g=Array(32);function p(e){return function(){for(let t=0;t<2*e;t++)g[t]=Math.floor(16*Math.random())+48,g[t]>=58&&(g[t]+=39);return String.fromCharCode.apply(null,g.slice(0,2*e))}}var m=class e{constructor(){this.config=null,this.logger=a.getInstance(),this.sessionId=null,this.idGenerator=new u}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new d(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;const e=globalThis?.sessionStorage?.getItem("gcId");return e||""}setSessionId(e){this.sessionId=e,globalThis?.sessionStorage?.setItem("gcId",e)}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...e.options}),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},f="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},v=m.getInstance(),y=new u;function E(){const e=v?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function b(e,t=""){return Object.entries(e).reduce(((e,[n,s])=>{const i=t?`${t}.${n}`:n;return"object"==typeof s&&null!==s?Object.assign(e,b(s,i)):e[i]=s,e}),{})}function I(e){const t=1e6*Date.now(),n=y.generateId(),s=e.spanId||y.generateSpanId(),i=e.traceId||y.generateTraceId(),r=e.parentSpanId||"",o=b(e.attributes||{}),a={path:f?.location?.pathname,url:f?.location?.href,title:f?.document?.title},l={type:e.type,id:n,spanId:s,parentSpanId:r,traceId:i,attributes:{...o,location:a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var w=class{constructor(){this.logger=a.getInstance(),this.config=m.getInstance()}async send(e){const t=this.config.getConfig();if(t)try{t.options.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,s=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");fetch(s,{method:"POST",headers:{"Content-Type":"application/json",apikey:n},body:JSON.stringify(e)})}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},T=class e{constructor(){this.events=[],this.timeoutId=null,this.config=m.getInstance(),this.initialized=!1,this.transporter=new w}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",(()=>{this.flush()})),this.initialized=!0}catch(e){c(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend;if(t&&!t(e))return;this.events.push(e);const n=this.config.getConfig()?.options?.batchSize||100;this.events.length>=n&&"dom.event"!==e.type&&this.flush()}catch(e){c(e)}}flush(){try{if(0===this.events.length||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){c(e)}}scheduleFlush(){try{null!==this.timeoutId&&(f.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=f.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){c(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const s=navigator.platform||"unknown",i=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:s,language:navigator.language,mobile:i}}getSessionAttributes(){const e=this.detectBrowser();return{cluster:this.config.getConfig()?.cluster||"",env:this.config.getConfig()?.environment||"",namespace:this.config.getConfig()?.namespace||"",session_id:this.config.getSessionId(),user:this.config.getConfig()?.userIdentifier||{},"service.name":this.config.getConfig()?.appId,userAgent:navigator.userAgent,browser:e}}};T.instance=null;var L=T,S=class{constructor(){this.logger=a.getInstance(),this.eventsPool=L.getInstance()}};function _({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var C,q=class extends S{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.getAttribute("data-private")].some((e=>e)),this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>_({text:e.target.innerText||""}),this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){c(e)}};this.eventHandlers.push({type:e,handler:t}),f?.addEventListener(e,t)}))}catch(e){c(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),s=e.target,i=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return I({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:i,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:s.id,tagName:s.tagName,className:s.className,text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,s=t.maxAttempts||10,i=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===e.tagName?.toLowerCase())return"html";let r="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<s;){let e=a.tagName?.toLowerCase()||"";try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of i)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=a.tagName?.toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return r||"*"}},z=["log","info","warn","error","assert","trace"],R=class extends S{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),z.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){c(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){c(e)}}destroy(){try{if(!this.isInitialized)return;z.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){c(e)}}handleEvent(e,t){try{if(!E())return;const n=this.formatMessage(Array.isArray(e)?e:[e]);if(!n||n?.includes("groundcoverIgnore"))return;const s=this.buildEvent({message:n,level:t});this.queueEvent(s)}catch(e){c(e)}}buildEvent({message:e,level:t}){return I({type:"log",attributes:{message:_({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e)try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}catch(e){return c(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{z.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){c(e)}return e}},x=class extends S{constructor(){super(...arguments),this.config=m.getInstance(),this.idGenerator=new u,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),i=e.request.headers.traceparent,r=i?.split("-")?.[1]||"",o=i?.split("-")?.[2]||"",a={type:"HTTP",operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{url:{full:n},route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:e.request.body},response:{body:e.response.body}}};return I({type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?1e6*e.timestamp:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?1e6*e.end_time:void 0,span_name:`${e.method} ${t}`,attributes:a,traceId:r,spanId:o})}}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return c(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,s=globalThis.XMLHttpRequest.prototype.setRequestHeader;let i;globalThis.XMLHttpRequest.prototype.open=function(n,s,r=!0,o,a){if(i=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[n,s,r,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,s,r,o,a])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),s.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const s=this._requestUrl.toString();if(!s||e.shouldIgnoreRequest(s))return n.apply(this,t);if(e.shouldAddTraceHeader(s)){const t=e.getTraceparentHeader();t&&(this.setRequestHeader("traceparent",t.traceparent),this._requestHeaders.traceparent=t.traceparent)}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,s]=e.split(": ");t&&s&&(n[t.trim()]=s.trim())}));const s={timestamp:i,end_time:t,method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:n,body:this.responseText||this.response||""}};e.handleEvent(s)})),n.apply(this,t)}}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[s,i]=t;i={...i||{}};const r=i?.method||"GET",o=i?.body||"",a=s instanceof Request?s.url:s.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);if(i&&!i.headers&&(i.headers={}),i||(t[1]={},i=t[1]),l){const e=this.getTraceparentHeader();e&&(i?.headers instanceof Headers?i.headers.set("traceparent",e.traceparent):i.headers={...i.headers,traceparent:e.traceparent})}const c={};return i?.headers&&(i.headers instanceof Headers?i.headers.forEach(((e,t)=>{c[t]=e})):"object"==typeof i.headers&&Object.assign(c,i.headers)),e.apply(globalThis,t).then((async e=>{const t=Date.now(),s=e.clone();let i="";const l={};s.headers.forEach(((e,t)=>{l[t]=e}));try{i="text/event-stream"===l["content-type"]?"[unreadable response body]":await s.text()}catch(e){i="[unreadable response body]"}this.logger.log("[network-events-listener.patchFetch] called",{url:a});const h={method:r,url:a,timestamp:n,body:o.toString(),status:s.status,end_time:t,request:{headers:c,body:o.toString()},response:{headers:l,body:i}};return this.handleEvent(h),e})).catch((e=>{const t=Date.now();let n="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const i={method:r,url:a,body:o.toString(),status:0,end_time:t,request:{headers:c,body:o.toString()},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(i),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,s])=>{const i=n.toLowerCase();return t.includes(i)||/(token|key|secret|password)/i.test(i)?e[n]="[REDACTED]":e[n]=_({text:s}),e}),{})}getTraceparentHeader(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e}}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t||!t.options.tracePropagationUrls||!t.options.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls.some((t=>{const n=t.replace(/\*/g,".*"),s=new RegExp(`^${n}$`),i=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return s.test(i)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},k=class extends S{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const s=this.buildEvent(n,t);this.queueEvent(s)}catch(e){c(e)}}}initialize(){f?.addEventListener("error",this.handleEvent),f?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){f?.removeEventListener("error",this.handleEvent),f?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return I({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${_({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}enhanceError(e,t){const{filename:n,lineno:s,colno:i}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),s&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:s}),i&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:i})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(t){if(!t)return[];try{return e.parse(t).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},N=class extends S{constructor(){super(...arguments),this.currentUrl=globalThis.location.href,this.mutationObserver=null}initialize(){if(f.MutationObserver){const e=f.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver((()=>{this.handleUrlChange()})),this.mutationObserver.observe(e,{childList:!0,subtree:!0,attributes:!0}))}f?.addEventListener("popstate",(()=>{this.handleUrlChange()}))}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){c(e)}}buildEvent(){return I({type:"navigation",attributes:{page_url:globalThis.location.href}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}handleUrlChange(){this.logger.log("[navigation-listener.handleUrlChange] called");const e=new URL(globalThis.location.href),t=new URL(this.currentUrl);e.pathname!==t.pathname&&(this.currentUrl=globalThis.location.href,this.handleEvent())}},H=class extends S{constructor(){super(),this.startTime=performance.now()}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),f?.addEventListener("load",(()=>{this.handleEvent()}))}catch(e){c(e)}}destroy(){f?.removeEventListener("load",this.handleEvent)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){c(e)}}buildEvent(){const e=performance.now()-this.startTime,t=performance.getEntriesByType("resource"),n={count:t.length,totalSize:0,totalDuration:0,byType:{}};t.forEach((e=>{const t=e,s=t.transferSize||0,i=t.duration,r=t.initiatorType;n.totalSize+=s,n.totalDuration+=i,n.byType[r]||(n.byType[r]={count:0,size:0,duration:0}),n.byType[r].count++,n.byType[r].size+=s,n.byType[r].duration+=i}));return I({type:"pageload",attributes:{page_url:f?.location?.href||"",page_load_time:e,page_referrer:f?.document?.referrer||"",page_resources:n}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}},U=class extends S{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}}}initialize(){t(this.handleEvent),n(this.handleEvent),s(this.handleEvent),i(this.handleEvent),r(this.handleEvent)}destroy(){}buildEvent(e){return I({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}},M=class{constructor(){this.logger=a.getInstance(),this.eventsPool=L.getInstance(),this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.domEventsListener=new q,this.logEventsListener=new R,this.errorsEventsListener=new k,this.networkEventsListener=new x,this.navigationListener=new N,this.performanceListener=new U,this.pageLoadListener=new H,this.domEventsListener.initialize(),this.logEventsListener.initialize(),this.errorsEventsListener.initialize(),this.networkEventsListener.initialize(),this.navigationListener.initialize(),this.performanceListener.initialize(),this.pageLoadListener.initialize(),this.logger.log("[instrumentation-manager.instrument] initialized listeners")}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=I({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){c(e)}}captureException(e){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0})}catch(e){c(e)}}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy()}},j="gcSample",A=class{constructor(e){this.initialized=!1,this.logger=a.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new M,this.idGenerator=new u;if(!this.getSamplingDecision(e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=m.getInstance();t.initialize(e);L.getInstance().initialize();t.getSessionId()||t.setSessionId(this.idGenerator.generateId()),this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=globalThis.sessionStorage?.getItem(j);if(t){const e="1"===t;return this.logger.log("[session-manager] using stored sampling decision:",e),e}const n=!e||Math.random()<e;return globalThis?.sessionStorage?.setItem(j,n?"1":"0"),this.logger.log("[session-manager] stored new sampling decision:",n),n}catch(t){this.logger.log("[session-manager] session storage access failed:",t);const n=!e||Math.random()<e;return this.logger.log("[session-manager] using fallback sampling decision:",n),n}}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");m.getInstance().updateConfig({userIdentifier:e})}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}captureException(e){this.initialized?this.instrumentationManager.captureException(e):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),globalThis.sessionStorage?.removeItem("gcId"),this.initialized=!1)}};var O={init:function(e){try{C=new A({cluster:e?.cluster,environment:e?.environment,namespace:e?.namespace,dsn:e?.dsn,appId:e?.appId,userIdentifier:e?.userIdentifier,apiKey:e?.apiKey,options:e?.options})}catch(e){c(e)}},identifyUser:function(e){C?C.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){C&&C.sendCustomEvent(e)},captureException:function(e){C&&C.captureException(e)}};export{O as default};
|
|
1
|
+
import e from"error-stack-parser";import{onCLS as t,onLCP as n,onFCP as s,onTTFB as i,onINP as r}from"web-vitals";var o=console.log.bind(console),a=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&o(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},l=a.getInstance();function c(e){l.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var h={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,maskFields:[],enabledEvents:[],tracePropagationUrls:[]},d=class{constructor(e){this.dsn=e.dsn,this.appId=e.appId,this.cluster=e.cluster,this.apiKey=e.apiKey,this.environment=e.environment,this.namespace=e.namespace,this.userIdentifier=e.userIdentifier||null,this.options={...h,...e.options}}getEndpoint(){return this.dsn}},u=class{constructor(){this.generateTraceId=p(16),this.generateSpanId=p(8),this.generateId=p(16)}},g=Array(32);function p(e){return function(){for(let t=0;t<2*e;t++)g[t]=Math.floor(16*Math.random())+48,g[t]>=58&&(g[t]+=39);return String.fromCharCode.apply(null,g.slice(0,2*e))}}var m=class e{constructor(){this.config=null,this.logger=a.getInstance(),this.sessionId=null,this.idGenerator=new u}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new d(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;const e=globalThis?.sessionStorage?.getItem("gcId");return e||""}setSessionId(e){this.sessionId=e,globalThis?.sessionStorage?.setItem("gcId",e)}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...e.options}),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},f="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},v=m.getInstance(),y=new u;function E(){const e=v?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function b(e,t=""){return Object.entries(e).reduce(((e,[n,s])=>{const i=t?`${t}.${n}`:n;return"object"==typeof s&&null!==s?Object.assign(e,b(s,i)):e[i]=s,e}),{})}function I(e){const t=1e6*Date.now(),n=y.generateId(),s=e.spanId||y.generateSpanId(),i=e.traceId||y.generateTraceId(),r=e.parentSpanId||"",o=b(e.attributes||{}),a={path:f?.location?.pathname,url:f?.location?.href,title:f?.document?.title},l={type:e.type,id:n,spanId:s,parentSpanId:r,traceId:i,attributes:{...o,location:a}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var w=class{constructor(){this.logger=a.getInstance(),this.config=m.getInstance()}async send(e){const t=this.config.getConfig();if(t)try{t.options.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,s=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");fetch(s,{method:"POST",headers:{"Content-Type":"application/json",apikey:n},body:JSON.stringify(e)})}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},T=class e{constructor(){this.events=[],this.timeoutId=null,this.config=m.getInstance(),this.initialized=!1,this.transporter=new w}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",(()=>{this.flush()})),this.initialized=!0}catch(e){c(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend;if(t&&!t(e))return;this.events.push(e);const n=this.config.getConfig()?.options?.batchSize||100;this.events.length>=n&&"dom.event"!==e.type&&this.flush()}catch(e){c(e)}}flush(){try{if(0===this.events.length||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){c(e)}}scheduleFlush(){try{null!==this.timeoutId&&(f.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=f.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){c(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const s=navigator.platform||"unknown",i=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:s,language:navigator.language,mobile:i}}getSessionAttributes(){const e=this.detectBrowser();return{cluster:this.config.getConfig()?.cluster||"",env:this.config.getConfig()?.environment||"",namespace:this.config.getConfig()?.namespace||"",session_id:this.config.getSessionId(),user:this.config.getConfig()?.userIdentifier||{},"service.name":this.config.getConfig()?.appId,userAgent:navigator.userAgent,browser:e}}};T.instance=null;var L=T,S=class{constructor(){this.logger=a.getInstance(),this.eventsPool=L.getInstance()}};function _({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var C,q=class extends S{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.getShouldMaskText=e=>["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.getAttribute("data-private")].some((e=>e)),this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>_({text:e.target.innerText||""}),this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){c(e)}};this.eventHandlers.push({type:e,handler:t}),f?.addEventListener(e,t)}))}catch(e){c(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),s=e.target,i=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return I({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:i,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:s.id,tagName:s.tagName,className:s.className,text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,s=t.maxAttempts||10,i=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===e.tagName?.toLowerCase())return"html";let r="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<s;){let e=a.tagName?.toLowerCase()||"";try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of i)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=a.tagName?.toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return r||"*"}},z=["log","info","warn","error","assert","trace"],x=class extends S{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),z.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){c(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){c(e)}}destroy(){try{if(!this.isInitialized)return;z.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){c(e)}}handleEvent(e,t){try{if(!E())return;const n=this.formatMessage(Array.isArray(e)?e:[e]);if(!n||n?.includes("groundcoverIgnore"))return;const s=this.buildEvent({message:n,level:t});this.queueEvent(s)}catch(e){c(e)}}buildEvent({message:e,level:t}){return I({type:"log",attributes:{message:_({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e)try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}return String(e)})).join(" ")}catch(e){return c(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{z.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){c(e)}return e}},R=class extends S{constructor(){super(...arguments),this.config=m.getInstance(),this.idGenerator=new u,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),i=e.request.headers.traceparent,r=i?.split("-")?.[1]||"",o=i?.split("-")?.[2]||"",a={type:"HTTP",operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{url:{full:n},route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:e.request.body},response:{body:e.response.body}}};return I({type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?1e6*e.timestamp:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?1e6*e.end_time:void 0,span_name:`${e.method} ${t}`,attributes:a,traceId:r,spanId:o})}}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return c(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,s=globalThis.XMLHttpRequest.prototype.setRequestHeader;let i;globalThis.XMLHttpRequest.prototype.open=function(n,s,r=!0,o,a){if(i=Date.now(),e.shouldIgnoreRequest(s.toString()))return t.apply(this,[n,s,r,o,a]);const l=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,s,r,o,a])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),s.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const s=this._requestUrl.toString();if(!s||e.shouldIgnoreRequest(s))return n.apply(this,t);if(e.shouldAddTraceHeader(s)){const t=e.getTraceparentHeader();t&&(this.setRequestHeader("traceparent",t.traceparent),this._requestHeaders.traceparent=t.traceparent)}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,s]=e.split(": ");t&&s&&(n[t.trim()]=s.trim())}));const s={timestamp:i,end_time:t,method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:n,body:this.responseText||this.response||""}};e.handleEvent(s)})),n.apply(this,t)}}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[s,i]=t;i={...i||{}};const r=i?.method||"GET",o=i?.body||"",a=s instanceof Request?s.url:s.toString();if(this.shouldIgnoreRequest(a))return e.apply(globalThis,t);const l=this.shouldAddTraceHeader(a);if(i&&!i.headers&&(i.headers={}),i||(t[1]={},i=t[1]),l){const e=this.getTraceparentHeader();e&&(i?.headers instanceof Headers?i.headers.set("traceparent",e.traceparent):i.headers={...i.headers,traceparent:e.traceparent})}const c={};return i?.headers&&(i.headers instanceof Headers?i.headers.forEach(((e,t)=>{c[t]=e})):"object"==typeof i.headers&&Object.assign(c,i.headers)),e.apply(globalThis,t).then((async e=>{const t=Date.now(),s=e.clone();let i="";const l={};s.headers.forEach(((e,t)=>{l[t]=e}));try{i="text/event-stream"===l["content-type"]?"[unreadable response body]":await s.text()}catch(e){i="[unreadable response body]"}this.logger.log("[network-events-listener.patchFetch] called",{url:a});const h={method:r,url:a,timestamp:n,body:o.toString(),status:s.status,end_time:t,request:{headers:c,body:o.toString()},response:{headers:l,body:i}};return this.handleEvent(h),e})).catch((e=>{const t=Date.now();let n="NetworkError";const s=e.message||"Unknown network error";e instanceof TypeError&&s.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":s.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":s.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const i={method:r,url:a,body:o.toString(),status:0,end_time:t,request:{headers:c,body:o.toString()},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(i),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,s])=>{const i=n.toLowerCase();return t.includes(i)||/(token|key|secret|password)/i.test(i)?e[n]="[REDACTED]":e[n]=_({text:s}),e}),{})}getTraceparentHeader(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e}}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t||!t.options.tracePropagationUrls||!t.options.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls.some((t=>{const n=t.replace(/\*/g,".*"),s=new RegExp(`^${n}$`),i=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return s.test(i)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},k=class extends S{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const s=this.buildEvent(n,t);this.queueEvent(s)}catch(e){c(e)}}}initialize(){f?.addEventListener("error",this.handleEvent),f?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){f?.removeEventListener("error",this.handleEvent),f?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return I({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${_({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}enhanceError(e,t){const{filename:n,lineno:s,colno:i}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),s&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:s}),i&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:i})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(t){if(!t)return[];try{return e.parse(t).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},N=class extends S{constructor(){super(...arguments),this.currentUrl=globalThis.location.href,this.mutationObserver=null}initialize(){if(f.MutationObserver){const e=f.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver((()=>{this.handleUrlChange()})),this.mutationObserver.observe(e,{childList:!0,subtree:!0,attributes:!0}))}f?.addEventListener("popstate",(()=>{this.handleUrlChange()}))}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){c(e)}}buildEvent(){return I({type:"navigation",attributes:{page_url:globalThis.location.href}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}handleUrlChange(){this.logger.log("[navigation-listener.handleUrlChange] called");const e=new URL(globalThis.location.href),t=new URL(this.currentUrl);e.pathname!==t.pathname&&(this.currentUrl=globalThis.location.href,this.handleEvent())}},H=class extends S{constructor(){super(),this.startTime=performance.now()}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),f?.addEventListener("load",(()=>{this.handleEvent()}))}catch(e){c(e)}}destroy(){f?.removeEventListener("load",this.handleEvent)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){c(e)}}buildEvent(){const e=performance.now()-this.startTime,t=performance.getEntriesByType("resource"),n={count:t.length,totalSize:0,totalDuration:0,byType:{}};t.forEach((e=>{const t=e,s=t.transferSize||0,i=t.duration,r=t.initiatorType;n.totalSize+=s,n.totalDuration+=i,n.byType[r]||(n.byType[r]={count:0,size:0,duration:0}),n.byType[r].count++,n.byType[r].size+=s,n.byType[r].duration+=i}));return I({type:"pageload",attributes:{page_url:f?.location?.href||"",page_load_time:e,page_referrer:f?.document?.referrer||"",page_resources:n}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}},M=class extends S{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!E())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){c(e)}}}initialize(){t(this.handleEvent),n(this.handleEvent),s(this.handleEvent),i(this.handleEvent),r(this.handleEvent)}destroy(){}buildEvent(e){return I({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){c(e)}}},U=class{constructor(){this.logger=a.getInstance(),this.eventsPool=L.getInstance(),this.configManager=m.getInstance(),this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called");const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,s=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new H,this.pageLoadListener.initialize(),s.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new q,this.domEventsListener.initialize(),s.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new x,this.logEventsListener.initialize(),s.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new k,this.errorsEventsListener.initialize(),s.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new R,this.networkEventsListener.initialize(),s.push("network")),(n||t?.includes("navigation"))&&(this.navigationListener=new N,this.navigationListener.initialize(),s.push("navigation")),(n||t?.includes("performance"))&&(this.performanceListener=new M,this.performanceListener.initialize(),s.push("performance")),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",s)}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=I({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){c(e)}}captureException(e){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0})}catch(e){c(e)}}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy()}},j="gcSample",A=class{constructor(e){this.initialized=!1,this.logger=a.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new U,this.idGenerator=new u;if(!this.getSamplingDecision(e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=m.getInstance();t.initialize(e);L.getInstance().initialize();t.getSessionId()||t.setSessionId(this.idGenerator.generateId()),this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=globalThis.sessionStorage?.getItem(j);if(t){const e="1"===t;return this.logger.log("[session-manager] using stored sampling decision:",e),e}const n=!e||Math.random()<e;return globalThis?.sessionStorage?.setItem(j,n?"1":"0"),this.logger.log("[session-manager] stored new sampling decision:",n),n}catch(t){this.logger.log("[session-manager] session storage access failed:",t);const n=!e||Math.random()<e;return this.logger.log("[session-manager] using fallback sampling decision:",n),n}}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");m.getInstance().updateConfig({userIdentifier:e})}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}captureException(e){this.initialized?this.instrumentationManager.captureException(e):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),globalThis.sessionStorage?.removeItem("gcId"),this.initialized=!1)}};var O={init:function(e){try{C=new A({cluster:e?.cluster,environment:e?.environment,namespace:e?.namespace,dsn:e?.dsn,appId:e?.appId,userIdentifier:e?.userIdentifier,apiKey:e?.apiKey,options:e?.options})}catch(e){c(e)}},identifyUser:function(e){C?C.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){C&&C.sendCustomEvent(e)},captureException:function(e){C&&C.captureException(e)}};export{O as default};
|