@groundcover/browser 0.0.5 → 0.0.7
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/package.json +3 -2
- package/dist/index.d.mts +0 -43
- package/dist/index.d.ts +0 -43
- package/dist/index.js +0 -1
- package/dist/index.mjs +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@groundcover/browser",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.7",
|
|
4
4
|
"description": "groundcover browser experiments SDK",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -62,7 +62,8 @@
|
|
|
62
62
|
"tslib": "^2.8.1",
|
|
63
63
|
"tsup": "^8.4.0",
|
|
64
64
|
"typescript-eslint": "^8.22.0",
|
|
65
|
-
"vitest": "^3.0.5"
|
|
65
|
+
"vitest": "^3.0.5",
|
|
66
|
+
"prepublish": "pnpm run build:prod"
|
|
66
67
|
},
|
|
67
68
|
"dependencies": {
|
|
68
69
|
"error-stack-parser": "^2.1.4",
|
package/dist/index.d.mts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
type UserIdentifiers = {
|
|
2
|
-
id: string;
|
|
3
|
-
email: string;
|
|
4
|
-
role: string;
|
|
5
|
-
name: string;
|
|
6
|
-
organization: string;
|
|
7
|
-
properties: Record<string, unknown>;
|
|
8
|
-
};
|
|
9
|
-
type UserDefinedEventAttributes = {
|
|
10
|
-
event: string;
|
|
11
|
-
attributes?: Record<string, unknown>;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
interface SDKOptions {
|
|
15
|
-
batchSize: number;
|
|
16
|
-
batchTimeout: number;
|
|
17
|
-
enabledEvents: Array<"dom" | "network" | "error" | "log">;
|
|
18
|
-
sampleRate: number;
|
|
19
|
-
environment: string;
|
|
20
|
-
debug: boolean;
|
|
21
|
-
maskFields: string[];
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
declare function init(params: {
|
|
25
|
-
cluster: string;
|
|
26
|
-
environment: string;
|
|
27
|
-
appId: string;
|
|
28
|
-
userIdentifier?: Partial<UserIdentifiers>;
|
|
29
|
-
dsn: string;
|
|
30
|
-
options?: Partial<SDKOptions>;
|
|
31
|
-
apiKey: string;
|
|
32
|
-
}): void;
|
|
33
|
-
declare function identifyUser(userIdentifier: Partial<UserIdentifiers>): void;
|
|
34
|
-
declare function sendCustomEvent(params: UserDefinedEventAttributes): void;
|
|
35
|
-
declare function captureException(error: Error): void;
|
|
36
|
-
declare const _default: {
|
|
37
|
-
init: typeof init;
|
|
38
|
-
identifyUser: typeof identifyUser;
|
|
39
|
-
sendCustomEvent: typeof sendCustomEvent;
|
|
40
|
-
captureException: typeof captureException;
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
export { captureException, _default as default, sendCustomEvent };
|
package/dist/index.d.ts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
type UserIdentifiers = {
|
|
2
|
-
id: string;
|
|
3
|
-
email: string;
|
|
4
|
-
role: string;
|
|
5
|
-
name: string;
|
|
6
|
-
organization: string;
|
|
7
|
-
properties: Record<string, unknown>;
|
|
8
|
-
};
|
|
9
|
-
type UserDefinedEventAttributes = {
|
|
10
|
-
event: string;
|
|
11
|
-
attributes?: Record<string, unknown>;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
interface SDKOptions {
|
|
15
|
-
batchSize: number;
|
|
16
|
-
batchTimeout: number;
|
|
17
|
-
enabledEvents: Array<"dom" | "network" | "error" | "log">;
|
|
18
|
-
sampleRate: number;
|
|
19
|
-
environment: string;
|
|
20
|
-
debug: boolean;
|
|
21
|
-
maskFields: string[];
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
declare function init(params: {
|
|
25
|
-
cluster: string;
|
|
26
|
-
environment: string;
|
|
27
|
-
appId: string;
|
|
28
|
-
userIdentifier?: Partial<UserIdentifiers>;
|
|
29
|
-
dsn: string;
|
|
30
|
-
options?: Partial<SDKOptions>;
|
|
31
|
-
apiKey: string;
|
|
32
|
-
}): void;
|
|
33
|
-
declare function identifyUser(userIdentifier: Partial<UserIdentifiers>): void;
|
|
34
|
-
declare function sendCustomEvent(params: UserDefinedEventAttributes): void;
|
|
35
|
-
declare function captureException(error: Error): void;
|
|
36
|
-
declare const _default: {
|
|
37
|
-
init: typeof init;
|
|
38
|
-
identifyUser: typeof identifyUser;
|
|
39
|
-
sendCustomEvent: typeof sendCustomEvent;
|
|
40
|
-
captureException: typeof captureException;
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
export { captureException, _default as default, sendCustomEvent };
|
package/dist/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var te=require('error-stack-parser'),webVitals=require('web-vitals');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var te__default=/*#__PURE__*/_interopDefault(te);var j={batchSize:10,batchTimeout:1e4,sampleRate:1,environment:"development",debug:false,maskFields:[],enabledEvents:["dom","network","error","log"]};var w=class{constructor(r){this.dsn=r.dsn,this.appId=r.appId,this.cluster=r.cluster,this.apiKey=r.apiKey,this.environment=r.environment,this.userIdentifier=r.userIdentifier||null,this.options={...j,...r.options};}getEndpoint(){return this.dsn}};var V=console.log.bind(console),v=class i{constructor(){this.isDebugEnabled=false,this.prefix="";}static initialize(r){return i.instance||(i.instance=new i),r&&(i.instance.isDebugEnabled=r.debug??false,i.instance.prefix=r.prefix??""),i.instance}static getInstance(r){return i?.instance||i.initialize(r)}formatMessage(r){return `[${new Date().toISOString()}] ${this.prefix} ${r}`}log(r,...e){this.isDebugEnabled&&V(this.formatMessage(r),...e);}updateConfig(r){this.isDebugEnabled=r.debug??this.isDebugEnabled,this.prefix=r.prefix??this.prefix;}};var E=class i{constructor(){this.config=null;this.logger=v.getInstance();}static getInstance(){return i.instance||(i.instance=new i),i.instance}initialize(r){this.config||(this.config=new w(r));}getConfig(){if(!this.config)throw this.logger.log("[config-manager] configuration not initialized"),new Error("[config-manager] configuration not initialized");return this.config}updateConfig(r){if(this.logger.log("[config-manager] updateConfig called"),!this.config){this.logger.log("[config-manager] configuration not initialized");return}r?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...r.options}),r?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...r.userIdentifier});}};var d=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};var C=class{constructor(){this.generateTraceId=U(16);this.generateSpanId=U(8);this.generateId=U(16);}},T=Array(32);function U(i){return function(){for(let e=0;e<i*2;e++)T[e]=Math.floor(Math.random()*16)+48,T[e]>=58&&(T[e]+=39);return String.fromCharCode.apply(null,T.slice(0,i*2))}}var Z=E.getInstance(),H=new C;function Q(){return {path:d?.location?.pathname,url:d?.location?.href,title:d?.document?.title}}function b(){let i=Z.getConfig().options.sampleRate;return Math.random()<=i}function B(i,r=""){return Object.entries(i).reduce((e,[t,n])=>{let o=r?`${r}.${t}`:t;return typeof n=="object"&&n!==null?Object.assign(e,B(n,o)):e[o]=n,e},{})}function f(i){let r=Date.now()*1e6,e=H.generateId(),t=H.generateSpanId(),n=H.generateTraceId(),o=["exception","dom.event","performance","navigation","pageload","custom"],l=B(i.attributes||{},o.includes(i.type)?"rum":""),s=Q();return {type:i.type,timestamp:r,id:e,spanId:t,parentSpanId:"",traceId:n,attributes:{...l,location:s}}}function F(i,r={}){if(!i||!i.nodeType||i.nodeType!==Node.ELEMENT_NODE)return "";let e=r.root||document.body||document.documentElement,t=r.maxAttempts||10,n=r.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if(i.tagName?.toLowerCase()==="html")return "html";let o="",l=0,s=i,h=[];for(;s&&s!==e&&s!==document.documentElement&&l<t;){let u=s.tagName?.toLowerCase()||"";try{let c=s.getAttribute("id");if(c&&/^[a-zA-Z][\w-]*$/.test(c))return `#${c}`;if(s.classList?.length){let g=Array.from(s.classList).filter(p=>p&&typeof p=="string").map(p=>`.${p}`);g.length&&(u+=g.join(""));}for(let g of n)if(!(g==="id"||g==="class"))try{let p=s.getAttribute(g);p&&(u+=`[${g}="${p.replace(/"/g,'\\"')}"]`);}catch{}}catch{u=s.tagName?.toLowerCase()||"*";}h.unshift(u||"*"),o=h.join(" > ");try{if(e.querySelectorAll(o).length===1)return o}catch{h.shift(),o=h.join(" > ");}try{s=s.parentElement;}catch{break}l++;}return o||"*"}var ee=v.getInstance();function a(i){ee.log("[error-handler.handleError] called",i,{groundcoverIgnore:true});}var R=class{constructor(){this.logger=v.getInstance();this.config=E.getInstance();}async send(r){try{if(this.config.getConfig().options.debug){this.logger.log("Sending batch:",r,{groundcoverIgnore:!0});return}let e=this.config.getConfig().apiKey,t=this.buildEndpoint();if(!e){this.logger.log("No API key found");return}fetch(t,{method:"POST",headers:{"Content-Type":"application/json",apikey:e},body:JSON.stringify(r)});}catch(e){this.config.getConfig().options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:true});}}buildEndpoint(){let{dsn:r}=this.config.getConfig();return `${r}/json/rum`}};var I=class I{constructor(){this.events=[];this.timeoutId=null;this.config=E.getInstance();this.initialized=false;this.transporter=new R;}static getInstance(){return I.instance||(I.instance=new I),I.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",()=>{this.flush();}),this.initialized=!0;}catch(r){a(r);}}addEvent(r){if(!r||!this.initialized)return;this.events.push(r);let{batchSize:e}=this.config.getConfig().options;this.events.length>=e&&this.flush();}flush(){try{if(this.events.length===0||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush();}catch(r){a(r);}}scheduleFlush(){try{this.timeoutId!==null&&(d.clearTimeout(this.timeoutId),this.timeoutId=null);let{batchTimeout:r}=this.config.getConfig().options;this.timeoutId=d.setTimeout(()=>{this.timeoutId=null,this.flush();},r);}catch(r){a(r);}}generateSessionId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}detectBrowser(){let r=navigator.userAgent,e="unknown",t="unknown",n=navigator.platform||"unknown",o=/Mobile|Android|iPhone|iPad|iPod/i.test(r);return /Edg/.test(r)?(e="Edge",t=r.match(/Edg\/([\d.]+)/)?.[1]||t):/Chrome/.test(r)&&!/Chromium/.test(r)?(e="Chrome",t=r.match(/Chrome\/([\d.]+)/)?.[1]||t):/Firefox/.test(r)?(e="Firefox",t=r.match(/Firefox\/([\d.]+)/)?.[1]||t):/Safari/.test(r)&&!/Chrome/.test(r)?(e="Safari",t=r.match(/Version\/([\d.]+)/)?.[1]||t):/Trident/.test(r)?(e="Internet Explorer",/rv:([^)]+)\)/i.test(r)?t=r.match(/rv:([^)]+)\)/i)?.[1]||t:t=r.match(/MSIE ([^;]+)/)?.[1]||t):/OPR/.test(r)&&(e="Opera",t=r.match(/OPR\/([\d.]+)/)?.[1]||t),{name:e,version:t,platform:n,language:navigator.language,mobile:o}}getSessionAttributes(){let r=this.detectBrowser();return {cluster:this.config.getConfig().cluster||"",env:this.config.getConfig().environment||"",session_id:sessionStorage.getItem("gcId")||this.generateSessionId(),user:this.config.getConfig().userIdentifier||{},"service.name":this.config.getConfig().appId,userAgent:navigator.userAgent,browser:r}}};I.instance=null;var y=I;var m=class{constructor(){this.logger=v.getInstance();this.eventsPool=y.getInstance();}};var x=class extends m{constructor(){super(...arguments);this.eventHandlers=[];this.capturedEvents=["click","change","keydown","select","submit"];this.getShouldMaskText=e=>[e.target?.type==="password",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(n=>n);this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&e.key!=="Dead"){let t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return ""};this.getText=e=>e.target.innerText||"";this.getSelector=e=>e.target instanceof Element&&F(e.target)||"";this.getCoordinates=e=>{if({mouseup:true,mousedown:true,mousemove:true,mouseover:true}[e.type]){let{clientX:n,clientY:o}=e||{};return {clientX:n,clientY:o}}return null};}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach(e=>{let t=n=>{try{this.handleEvent(n);}catch(o){a(o);}};this.eventHandlers.push({type:e,handler:t}),d?.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(!b())return;let n=this.buildEvent(e);this.queueEvent(n);}catch(t){a(t);}}buildEvent(e){let t=this.getSelector(e),n=this.getCoordinates(e),o=e.target,l=this.getKeyCode(e),s=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");let h={selector:t,keyCode:l,type:e.type,coordinates:n||{clientX:0,clientY:0},target:{id:o.id,tagName:o.tagName,className:o.className,text:s}};return f({type:"dom.event",attributes:h})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}};var K=["log","info","warn","error","assert","trace"],z=class extends m{constructor(){super(...arguments);this.originalConsole=null;this.isInitialized=false;}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),K.forEach(e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e);}catch(n){a(n);}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t);}});}),this.isInitialized=!0;}catch(e){a(e);}}destroy(){try{if(!this.isInitialized)return;K.forEach(e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e]);}),this.isInitialized=!1;}catch(e){a(e);}}handleEvent(e,t){try{if(!b())return;let o=this.formatMessage(Array.isArray(e)?e:[e]);if(!o||o?.includes("groundcoverIgnore"))return;let l=this.buildEvent({message:o,level:t});this.queueEvent(l);}catch(n){a(n);}}buildEvent({message:e,level:t}){return f({type:"log",attributes:{message:e,level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map(t=>{if(t===void 0)return "undefined";if(t===null)return "null";if(typeof t=="object")try{return JSON.stringify(t)}catch{return Object.prototype.toString.call(t)}return String(t)}).join(" ")}catch(t){return a(t),"[Error formatting console message]"}}captureConsoleMethods(){let e={};try{K.forEach(t=>{console&&typeof console[t]=="function"&&(e[t]=console[t].bind(console));});}catch(t){a(t);}return e}};var A=class extends m{constructor(){super(...arguments);this.config=E.getInstance();this.handleEvent=e=>{try{if(e.url?.includes(this.config.getConfig().dsn)||!b())return;let n=this.buildEvent(e);this.queueEvent(n);}catch(t){a(t);}};this.buildEvent=e=>{let t="";try{t=new URL(e.url).pathname;}catch{}let n=this.formatHeaders(e.request.headers),o={type:"HTTP",spanName:`${e.method} ${t}`,operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:n,method:e.method},response:{headers:n,status_code:e.status?.toString()}},gc:{request:{body:e.request.body},response:{body:e.response.body}}};return f({type:"network",attributes: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;}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}patchXHR(){let e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,o=globalThis.XMLHttpRequest.prototype.setRequestHeader;globalThis.XMLHttpRequest.prototype.open=function(l,s,h=true,u,c){if(e.shouldIgnoreRequest(s.toString()))return t.apply(this,[l,s,h,u,c]);let g=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=l,this._requestUrl=g,this._requestHeaders={},t.apply(this,[l,s,h,u,c])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(l,s){return this._requestHeaders&&(this._requestHeaders[l]=s),o.apply(this,[l,s])},globalThis.XMLHttpRequest.prototype.send=function(...l){return !this._requestUrl||e.shouldIgnoreRequest(this._requestUrl.toString())?n.apply(this,l):(this._requestBody=l[0]||"",this.addEventListener("load",()=>{let s={};this.getAllResponseHeaders().split(/\r?\n/).forEach(u=>{let[c,g]=u.split(": ");c&&g&&(s[c.trim()]=g.trim());});let h={method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:s,body:this.responseText||this.response||""}};e.handleEvent(h);}),n.apply(this,l))};}patchFetch(){let e=globalThis.fetch;globalThis.fetch=(...t)=>{let[n,o]=t,l=o?.method||"GET",s=o?.body||"",h=n instanceof Request?n.url:n.toString();if(this.shouldIgnoreRequest(h))return e.apply(globalThis,t);let u={};return o?.headers&&(o.headers instanceof Headers?o.headers.forEach((c,g)=>{u[g]=c;}):typeof o.headers=="object"&&Object.assign(u,o.headers)),e.apply(globalThis,t).then(async c=>{let g=c.clone(),p="";try{p=await g.text();}catch{p="[unreadable response body]";}let S={};g.headers.forEach((_,J)=>{S[J]=_;});let O={method:l,url:h,body:s.toString(),status:g.status,request:{headers:u,body:s.toString()},response:{headers:S,body:p}};return this.handleEvent(O),c}).catch(c=>{let g=c.name||"NetworkError",p=c.message||"Unknown network error",S="UNKNOWN_ERROR";c instanceof TypeError&&p.includes("Failed to fetch")?S="ERR_NETWORK_FAILURE":p.includes("Name not resolved")?S="ERR_NAME_NOT_RESOLVED":p.includes("Connection refused")&&(S="ERR_CONNECTION_REFUSED");let O={method:l,url:h,body:s.toString(),status:0,request:{headers:u,body:s.toString()},response:{headers:{},body:""},error:{name:g,message:p,stack:c.stack,code:S}};throw this.handleEvent(O),c})};}formatHeaders(e){let t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce((n,[o,l])=>{let s=o.toLowerCase();return t.includes(s)||/(token|key|secret|password)/i.test(s)?n[o]="[REDACTED]":n[o]=l,n},{})}shouldIgnoreRequest(e){return [".tsx",".jsx",".css"].some(n=>e.toLowerCase().endsWith(n))}};var M=class extends m{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)n=this.createUnhandledRejectionError(e);else return;let o=this.buildEvent(n,t);this.queueEvent(o);}catch(n){a(n);}};}initialize(){d?.addEventListener("error",this.handleEvent),d?.addEventListener("unhandledrejection",this.handleEvent);}destroy(){d?.removeEventListener("error",this.handleEvent),d?.removeEventListener("unhandledrejection",this.handleEvent);}buildEvent(e,t){let n={type:e.name||"Error",message:e.message||"Unknown error",stacktrace:this.buildStackTrace(e),fingerprint:`${e.name}:${e.message}`,handled:t?.handled||false};return f({type:"exception",attributes:n})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}enhanceError(e,t){let{filename:n,lineno:o,colno:l}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),o&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:o}),l&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:l});}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else {let n=typeof e.reason=="object"?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:false});}return t}buildStackTrace(e){if(!e)return [];try{return te__default.default.parse(e).map(n=>({filename:n.fileName||"unknown",function:n.functionName||"anonymous",lineno:n.lineNumber||0,colno:n.columnNumber||0}))}catch{return []}}};var q=class extends m{constructor(){super(...arguments);this.currentUrl=globalThis.location.href;this.mutationObserver=null;}initialize(){if(d.MutationObserver){let e=d.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver(()=>{this.handleUrlChange();}),this.mutationObserver.observe(e,{childList:true,subtree:true}));}d?.addEventListener("popstate",()=>{this.handleUrlChange();});}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null;}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");let e=this.buildEvent();this.queueEvent(e);}catch(e){a(e);}}buildEvent(){let e={url:globalThis.location.href};return f({type:"navigation",attributes:e})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}handleUrlChange(){let e=globalThis.location.href;e!==this.currentUrl&&(this.currentUrl=e,this.handleEvent());}};var k=class extends m{constructor(){super(...arguments);this.handleEvent=e=>{try{if(!b())return;let n=this.buildEvent(e);this.queueEvent(n);}catch(t){a(t);}};}initialize(){webVitals.onCLS(this.handleEvent),webVitals.onLCP(this.handleEvent),webVitals.onFCP(this.handleEvent),webVitals.onTTFB(this.handleEvent),webVitals.onINP(this.handleEvent);}destroy(){webVitals.onCLS.clear(),webVitals.onLCP.clear(),webVitals.onFCP.clear(),webVitals.onTTFB.clear(),webVitals.onINP.clear();}buildEvent(e){let t={name:e.name,value:e.value,id:e.id,navigationType:e.navigationType||""};return f({type:"performance",attributes:t})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}};var N=class extends m{constructor(){super(),this.startTime=performance.now();}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),d?.addEventListener("load",()=>{this.handleEvent();});}catch(r){a(r);}}destroy(){d?.removeEventListener("load",this.handleEvent);}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");let r=this.buildEvent();this.queueEvent(r);}catch(r){a(r);}}buildEvent(){let r=performance.now()-this.startTime,e=performance.getEntriesByType("resource"),t={count:e.length,totalSize:0,totalDuration:0,byType:{}};e.forEach(o=>{let l=o,s=l.transferSize||0,h=l.duration,u=l.initiatorType;t.totalSize+=s,t.totalDuration+=h,t.byType[u]||(t.byType[u]={count:0,size:0,duration:0}),t.byType[u].count++,t.byType[u].size+=s,t.byType[u].duration+=h;});let n={url:d?.location?.href||"",loadTime:r,referrer:d?.document?.referrer||"",resources:t};return f({type:"pageload",attributes:n})}queueEvent(r){try{this.logger.log("[page-load-listener.queueEvent] called"),r&&this.eventsPool.addEvent(r);}catch(e){a(e);}}};var P=class{constructor(){this.logger=v.getInstance();this.eventsPool=y.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 x,this.logEventsListener=new z,this.errorsEventsListener=new M,this.networkEventsListener=new A,this.navigationListener=new q,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(r){this.logger.log("[instrumentation-manager.sendCustomEvent] called",r);try{let e=f({type:"custom",attributes:{event:r?.event,attributes:r?.attributes}});this.eventsPool.addEvent(e);}catch(e){a(e);}}captureException(r){try{this.logger.log("[instrumentation-manager.captureException] called",r),this.errorsEventsListener?.handleEvent(r,{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();}};var D=class{constructor(){this.initialized=false;this.logger=v.initialize({debug:false,prefix:"[groundcover]"}),this.instrumentationManager=new P,this.idGenerator=new C;}initialize(r){if(this.logger.log("[session-manager] initialize called"),this.initialized){this.logger.log("[session-manager] SDK already initialized");return}this.logger=v.initialize({debug:r.options?.debug||false,prefix:"[groundcover]"}),E.getInstance().initialize(r),y.getInstance().initialize();let n=this.idGenerator.generateId();window.sessionStorage.setItem("gcId",n),this.instrumentationManager.instrument(),this.initialized=true;}identifyUser(r){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized){this.logger.log("[session-manager] cannot identify user: SDK not initialized");return}E.getInstance().updateConfig({userIdentifier:r});}sendCustomEvent(r){if(!this.initialized){this.logger.log("[session-manager] cannot send custom event: SDK not initialized");return}this.instrumentationManager.sendCustomEvent(r);}captureException(r){if(!this.initialized){this.logger.log("[session-manager] Cannot capture exception: SDK not initialized");return}this.instrumentationManager.captureException(r);}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),window.sessionStorage.removeItem("gcId"),this.initialized=false);}};var L;function re(i){L=new D,L.initialize({cluster:i?.cluster,environment:i?.environment,dsn:i?.dsn,appId:i?.appId,userIdentifier:i?.userIdentifier,apiKey:i?.apiKey,options:i?.options});}function ne(i){if(!L){console.error("[groundcover] identifyUser user before Groundcover SDK initialization");return}L.identifyUser(i);}function ie(i){L&&L.sendCustomEvent(i);}function oe(i){L&&L.captureException(i);}var Pt={init:re,identifyUser:ne,sendCustomEvent:ie,captureException:oe};exports.captureException=oe;exports.default=Pt;exports.sendCustomEvent=ie;
|
package/dist/index.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import te from'error-stack-parser';import {onCLS,onLCP,onFCP,onTTFB,onINP}from'web-vitals';var j={batchSize:10,batchTimeout:1e4,sampleRate:1,environment:"development",debug:false,maskFields:[],enabledEvents:["dom","network","error","log"]};var w=class{constructor(r){this.dsn=r.dsn,this.appId=r.appId,this.cluster=r.cluster,this.apiKey=r.apiKey,this.environment=r.environment,this.userIdentifier=r.userIdentifier||null,this.options={...j,...r.options};}getEndpoint(){return this.dsn}};var V=console.log.bind(console),v=class i{constructor(){this.isDebugEnabled=false,this.prefix="";}static initialize(r){return i.instance||(i.instance=new i),r&&(i.instance.isDebugEnabled=r.debug??false,i.instance.prefix=r.prefix??""),i.instance}static getInstance(r){return i?.instance||i.initialize(r)}formatMessage(r){return `[${new Date().toISOString()}] ${this.prefix} ${r}`}log(r,...e){this.isDebugEnabled&&V(this.formatMessage(r),...e);}updateConfig(r){this.isDebugEnabled=r.debug??this.isDebugEnabled,this.prefix=r.prefix??this.prefix;}};var E=class i{constructor(){this.config=null;this.logger=v.getInstance();}static getInstance(){return i.instance||(i.instance=new i),i.instance}initialize(r){this.config||(this.config=new w(r));}getConfig(){if(!this.config)throw this.logger.log("[config-manager] configuration not initialized"),new Error("[config-manager] configuration not initialized");return this.config}updateConfig(r){if(this.logger.log("[config-manager] updateConfig called"),!this.config){this.logger.log("[config-manager] configuration not initialized");return}r?.options&&(this.logger.log("[config-manager] updating options"),this.config.options={...this.config.options,...r.options}),r?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...r.userIdentifier});}};var d=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};var C=class{constructor(){this.generateTraceId=U(16);this.generateSpanId=U(8);this.generateId=U(16);}},T=Array(32);function U(i){return function(){for(let e=0;e<i*2;e++)T[e]=Math.floor(Math.random()*16)+48,T[e]>=58&&(T[e]+=39);return String.fromCharCode.apply(null,T.slice(0,i*2))}}var Z=E.getInstance(),H=new C;function Q(){return {path:d?.location?.pathname,url:d?.location?.href,title:d?.document?.title}}function b(){let i=Z.getConfig().options.sampleRate;return Math.random()<=i}function B(i,r=""){return Object.entries(i).reduce((e,[t,n])=>{let o=r?`${r}.${t}`:t;return typeof n=="object"&&n!==null?Object.assign(e,B(n,o)):e[o]=n,e},{})}function f(i){let r=Date.now()*1e6,e=H.generateId(),t=H.generateSpanId(),n=H.generateTraceId(),o=["exception","dom.event","performance","navigation","pageload","custom"],l=B(i.attributes||{},o.includes(i.type)?"rum":""),s=Q();return {type:i.type,timestamp:r,id:e,spanId:t,parentSpanId:"",traceId:n,attributes:{...l,location:s}}}function F(i,r={}){if(!i||!i.nodeType||i.nodeType!==Node.ELEMENT_NODE)return "";let e=r.root||document.body||document.documentElement,t=r.maxAttempts||10,n=r.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if(i.tagName?.toLowerCase()==="html")return "html";let o="",l=0,s=i,h=[];for(;s&&s!==e&&s!==document.documentElement&&l<t;){let u=s.tagName?.toLowerCase()||"";try{let c=s.getAttribute("id");if(c&&/^[a-zA-Z][\w-]*$/.test(c))return `#${c}`;if(s.classList?.length){let g=Array.from(s.classList).filter(p=>p&&typeof p=="string").map(p=>`.${p}`);g.length&&(u+=g.join(""));}for(let g of n)if(!(g==="id"||g==="class"))try{let p=s.getAttribute(g);p&&(u+=`[${g}="${p.replace(/"/g,'\\"')}"]`);}catch{}}catch{u=s.tagName?.toLowerCase()||"*";}h.unshift(u||"*"),o=h.join(" > ");try{if(e.querySelectorAll(o).length===1)return o}catch{h.shift(),o=h.join(" > ");}try{s=s.parentElement;}catch{break}l++;}return o||"*"}var ee=v.getInstance();function a(i){ee.log("[error-handler.handleError] called",i,{groundcoverIgnore:true});}var R=class{constructor(){this.logger=v.getInstance();this.config=E.getInstance();}async send(r){try{if(this.config.getConfig().options.debug){this.logger.log("Sending batch:",r,{groundcoverIgnore:!0});return}let e=this.config.getConfig().apiKey,t=this.buildEndpoint();if(!e){this.logger.log("No API key found");return}fetch(t,{method:"POST",headers:{"Content-Type":"application/json",apikey:e},body:JSON.stringify(r)});}catch(e){this.config.getConfig().options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:true});}}buildEndpoint(){let{dsn:r}=this.config.getConfig();return `${r}/json/rum`}};var I=class I{constructor(){this.events=[];this.timeoutId=null;this.config=E.getInstance();this.initialized=false;this.transporter=new R;}static getInstance(){return I.instance||(I.instance=new I),I.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),globalThis.addEventListener("unload",()=>{this.flush();}),this.initialized=!0;}catch(r){a(r);}}addEvent(r){if(!r||!this.initialized)return;this.events.push(r);let{batchSize:e}=this.config.getConfig().options;this.events.length>=e&&this.flush();}flush(){try{if(this.events.length===0||!this.initialized)return;this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush();}catch(r){a(r);}}scheduleFlush(){try{this.timeoutId!==null&&(d.clearTimeout(this.timeoutId),this.timeoutId=null);let{batchTimeout:r}=this.config.getConfig().options;this.timeoutId=d.setTimeout(()=>{this.timeoutId=null,this.flush();},r);}catch(r){a(r);}}generateSessionId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}detectBrowser(){let r=navigator.userAgent,e="unknown",t="unknown",n=navigator.platform||"unknown",o=/Mobile|Android|iPhone|iPad|iPod/i.test(r);return /Edg/.test(r)?(e="Edge",t=r.match(/Edg\/([\d.]+)/)?.[1]||t):/Chrome/.test(r)&&!/Chromium/.test(r)?(e="Chrome",t=r.match(/Chrome\/([\d.]+)/)?.[1]||t):/Firefox/.test(r)?(e="Firefox",t=r.match(/Firefox\/([\d.]+)/)?.[1]||t):/Safari/.test(r)&&!/Chrome/.test(r)?(e="Safari",t=r.match(/Version\/([\d.]+)/)?.[1]||t):/Trident/.test(r)?(e="Internet Explorer",/rv:([^)]+)\)/i.test(r)?t=r.match(/rv:([^)]+)\)/i)?.[1]||t:t=r.match(/MSIE ([^;]+)/)?.[1]||t):/OPR/.test(r)&&(e="Opera",t=r.match(/OPR\/([\d.]+)/)?.[1]||t),{name:e,version:t,platform:n,language:navigator.language,mobile:o}}getSessionAttributes(){let r=this.detectBrowser();return {cluster:this.config.getConfig().cluster||"",env:this.config.getConfig().environment||"",session_id:sessionStorage.getItem("gcId")||this.generateSessionId(),user:this.config.getConfig().userIdentifier||{},"service.name":this.config.getConfig().appId,userAgent:navigator.userAgent,browser:r}}};I.instance=null;var y=I;var m=class{constructor(){this.logger=v.getInstance();this.eventsPool=y.getInstance();}};var x=class extends m{constructor(){super(...arguments);this.eventHandlers=[];this.capturedEvents=["click","change","keydown","select","submit"];this.getShouldMaskText=e=>[e.target?.type==="password",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(n=>n);this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&e.key!=="Dead"){let t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return ""};this.getText=e=>e.target.innerText||"";this.getSelector=e=>e.target instanceof Element&&F(e.target)||"";this.getCoordinates=e=>{if({mouseup:true,mousedown:true,mousemove:true,mouseover:true}[e.type]){let{clientX:n,clientY:o}=e||{};return {clientX:n,clientY:o}}return null};}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach(e=>{let t=n=>{try{this.handleEvent(n);}catch(o){a(o);}};this.eventHandlers.push({type:e,handler:t}),d?.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(!b())return;let n=this.buildEvent(e);this.queueEvent(n);}catch(t){a(t);}}buildEvent(e){let t=this.getSelector(e),n=this.getCoordinates(e),o=e.target,l=this.getKeyCode(e),s=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");let h={selector:t,keyCode:l,type:e.type,coordinates:n||{clientX:0,clientY:0},target:{id:o.id,tagName:o.tagName,className:o.className,text:s}};return f({type:"dom.event",attributes:h})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}};var K=["log","info","warn","error","assert","trace"],z=class extends m{constructor(){super(...arguments);this.originalConsole=null;this.isInitialized=false;}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),K.forEach(e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e);}catch(n){a(n);}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t);}});}),this.isInitialized=!0;}catch(e){a(e);}}destroy(){try{if(!this.isInitialized)return;K.forEach(e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e]);}),this.isInitialized=!1;}catch(e){a(e);}}handleEvent(e,t){try{if(!b())return;let o=this.formatMessage(Array.isArray(e)?e:[e]);if(!o||o?.includes("groundcoverIgnore"))return;let l=this.buildEvent({message:o,level:t});this.queueEvent(l);}catch(n){a(n);}}buildEvent({message:e,level:t}){return f({type:"log",attributes:{message:e,level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}formatMessage(e){if(!Array.isArray(e))return String(e);try{return e.map(t=>{if(t===void 0)return "undefined";if(t===null)return "null";if(typeof t=="object")try{return JSON.stringify(t)}catch{return Object.prototype.toString.call(t)}return String(t)}).join(" ")}catch(t){return a(t),"[Error formatting console message]"}}captureConsoleMethods(){let e={};try{K.forEach(t=>{console&&typeof console[t]=="function"&&(e[t]=console[t].bind(console));});}catch(t){a(t);}return e}};var A=class extends m{constructor(){super(...arguments);this.config=E.getInstance();this.handleEvent=e=>{try{if(e.url?.includes(this.config.getConfig().dsn)||!b())return;let n=this.buildEvent(e);this.queueEvent(n);}catch(t){a(t);}};this.buildEvent=e=>{let t="";try{t=new URL(e.url).pathname;}catch{}let n=this.formatHeaders(e.request.headers),o={type:"HTTP",spanName:`${e.method} ${t}`,operation:{name:e.method},resource_name:t,status:e.status?.toString(),subType:e.method,http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:n,method:e.method},response:{headers:n,status_code:e.status?.toString()}},gc:{request:{body:e.request.body},response:{body:e.response.body}}};return f({type:"network",attributes: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;}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}patchXHR(){let e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,o=globalThis.XMLHttpRequest.prototype.setRequestHeader;globalThis.XMLHttpRequest.prototype.open=function(l,s,h=true,u,c){if(e.shouldIgnoreRequest(s.toString()))return t.apply(this,[l,s,h,u,c]);let g=new URL(s.toString(),globalThis.location.href).href;return this._requestMethod=l,this._requestUrl=g,this._requestHeaders={},t.apply(this,[l,s,h,u,c])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(l,s){return this._requestHeaders&&(this._requestHeaders[l]=s),o.apply(this,[l,s])},globalThis.XMLHttpRequest.prototype.send=function(...l){return !this._requestUrl||e.shouldIgnoreRequest(this._requestUrl.toString())?n.apply(this,l):(this._requestBody=l[0]||"",this.addEventListener("load",()=>{let s={};this.getAllResponseHeaders().split(/\r?\n/).forEach(u=>{let[c,g]=u.split(": ");c&&g&&(s[c.trim()]=g.trim());});let h={method:this._requestMethod,url:this._requestUrl,body:this._requestBody,status:this.status,request:{headers:this._requestHeaders||{},body:this._requestBody},response:{headers:s,body:this.responseText||this.response||""}};e.handleEvent(h);}),n.apply(this,l))};}patchFetch(){let e=globalThis.fetch;globalThis.fetch=(...t)=>{let[n,o]=t,l=o?.method||"GET",s=o?.body||"",h=n instanceof Request?n.url:n.toString();if(this.shouldIgnoreRequest(h))return e.apply(globalThis,t);let u={};return o?.headers&&(o.headers instanceof Headers?o.headers.forEach((c,g)=>{u[g]=c;}):typeof o.headers=="object"&&Object.assign(u,o.headers)),e.apply(globalThis,t).then(async c=>{let g=c.clone(),p="";try{p=await g.text();}catch{p="[unreadable response body]";}let S={};g.headers.forEach((_,J)=>{S[J]=_;});let O={method:l,url:h,body:s.toString(),status:g.status,request:{headers:u,body:s.toString()},response:{headers:S,body:p}};return this.handleEvent(O),c}).catch(c=>{let g=c.name||"NetworkError",p=c.message||"Unknown network error",S="UNKNOWN_ERROR";c instanceof TypeError&&p.includes("Failed to fetch")?S="ERR_NETWORK_FAILURE":p.includes("Name not resolved")?S="ERR_NAME_NOT_RESOLVED":p.includes("Connection refused")&&(S="ERR_CONNECTION_REFUSED");let O={method:l,url:h,body:s.toString(),status:0,request:{headers:u,body:s.toString()},response:{headers:{},body:""},error:{name:g,message:p,stack:c.stack,code:S}};throw this.handleEvent(O),c})};}formatHeaders(e){let t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce((n,[o,l])=>{let s=o.toLowerCase();return t.includes(s)||/(token|key|secret|password)/i.test(s)?n[o]="[REDACTED]":n[o]=l,n},{})}shouldIgnoreRequest(e){return [".tsx",".jsx",".css"].some(n=>e.toLowerCase().endsWith(n))}};var M=class extends m{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)n=this.createUnhandledRejectionError(e);else return;let o=this.buildEvent(n,t);this.queueEvent(o);}catch(n){a(n);}};}initialize(){d?.addEventListener("error",this.handleEvent),d?.addEventListener("unhandledrejection",this.handleEvent);}destroy(){d?.removeEventListener("error",this.handleEvent),d?.removeEventListener("unhandledrejection",this.handleEvent);}buildEvent(e,t){let n={type:e.name||"Error",message:e.message||"Unknown error",stacktrace:this.buildStackTrace(e),fingerprint:`${e.name}:${e.message}`,handled:t?.handled||false};return f({type:"exception",attributes:n})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}enhanceError(e,t){let{filename:n,lineno:o,colno:l}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),o&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:o}),l&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:l});}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else {let n=typeof e.reason=="object"?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:false});}return t}buildStackTrace(e){if(!e)return [];try{return te.parse(e).map(n=>({filename:n.fileName||"unknown",function:n.functionName||"anonymous",lineno:n.lineNumber||0,colno:n.columnNumber||0}))}catch{return []}}};var q=class extends m{constructor(){super(...arguments);this.currentUrl=globalThis.location.href;this.mutationObserver=null;}initialize(){if(d.MutationObserver){let e=d.document.querySelector("body");e&&(this.mutationObserver=new MutationObserver(()=>{this.handleUrlChange();}),this.mutationObserver.observe(e,{childList:true,subtree:true}));}d?.addEventListener("popstate",()=>{this.handleUrlChange();});}destroy(){this.mutationObserver?.disconnect(),this.mutationObserver=null;}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");let e=this.buildEvent();this.queueEvent(e);}catch(e){a(e);}}buildEvent(){let e={url:globalThis.location.href};return f({type:"navigation",attributes:e})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}handleUrlChange(){let e=globalThis.location.href;e!==this.currentUrl&&(this.currentUrl=e,this.handleEvent());}};var k=class extends m{constructor(){super(...arguments);this.handleEvent=e=>{try{if(!b())return;let n=this.buildEvent(e);this.queueEvent(n);}catch(t){a(t);}};}initialize(){onCLS(this.handleEvent),onLCP(this.handleEvent),onFCP(this.handleEvent),onTTFB(this.handleEvent),onINP(this.handleEvent);}destroy(){onCLS.clear(),onLCP.clear(),onFCP.clear(),onTTFB.clear(),onINP.clear();}buildEvent(e){let t={name:e.name,value:e.value,id:e.id,navigationType:e.navigationType||""};return f({type:"performance",attributes:t})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e);}catch(t){a(t);}}};var N=class extends m{constructor(){super(),this.startTime=performance.now();}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),d?.addEventListener("load",()=>{this.handleEvent();});}catch(r){a(r);}}destroy(){d?.removeEventListener("load",this.handleEvent);}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");let r=this.buildEvent();this.queueEvent(r);}catch(r){a(r);}}buildEvent(){let r=performance.now()-this.startTime,e=performance.getEntriesByType("resource"),t={count:e.length,totalSize:0,totalDuration:0,byType:{}};e.forEach(o=>{let l=o,s=l.transferSize||0,h=l.duration,u=l.initiatorType;t.totalSize+=s,t.totalDuration+=h,t.byType[u]||(t.byType[u]={count:0,size:0,duration:0}),t.byType[u].count++,t.byType[u].size+=s,t.byType[u].duration+=h;});let n={url:d?.location?.href||"",loadTime:r,referrer:d?.document?.referrer||"",resources:t};return f({type:"pageload",attributes:n})}queueEvent(r){try{this.logger.log("[page-load-listener.queueEvent] called"),r&&this.eventsPool.addEvent(r);}catch(e){a(e);}}};var P=class{constructor(){this.logger=v.getInstance();this.eventsPool=y.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 x,this.logEventsListener=new z,this.errorsEventsListener=new M,this.networkEventsListener=new A,this.navigationListener=new q,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(r){this.logger.log("[instrumentation-manager.sendCustomEvent] called",r);try{let e=f({type:"custom",attributes:{event:r?.event,attributes:r?.attributes}});this.eventsPool.addEvent(e);}catch(e){a(e);}}captureException(r){try{this.logger.log("[instrumentation-manager.captureException] called",r),this.errorsEventsListener?.handleEvent(r,{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();}};var D=class{constructor(){this.initialized=false;this.logger=v.initialize({debug:false,prefix:"[groundcover]"}),this.instrumentationManager=new P,this.idGenerator=new C;}initialize(r){if(this.logger.log("[session-manager] initialize called"),this.initialized){this.logger.log("[session-manager] SDK already initialized");return}this.logger=v.initialize({debug:r.options?.debug||false,prefix:"[groundcover]"}),E.getInstance().initialize(r),y.getInstance().initialize();let n=this.idGenerator.generateId();window.sessionStorage.setItem("gcId",n),this.instrumentationManager.instrument(),this.initialized=true;}identifyUser(r){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized){this.logger.log("[session-manager] cannot identify user: SDK not initialized");return}E.getInstance().updateConfig({userIdentifier:r});}sendCustomEvent(r){if(!this.initialized){this.logger.log("[session-manager] cannot send custom event: SDK not initialized");return}this.instrumentationManager.sendCustomEvent(r);}captureException(r){if(!this.initialized){this.logger.log("[session-manager] Cannot capture exception: SDK not initialized");return}this.instrumentationManager.captureException(r);}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),window.sessionStorage.removeItem("gcId"),this.initialized=false);}};var L;function re(i){L=new D,L.initialize({cluster:i?.cluster,environment:i?.environment,dsn:i?.dsn,appId:i?.appId,userIdentifier:i?.userIdentifier,apiKey:i?.apiKey,options:i?.options});}function ne(i){if(!L){console.error("[groundcover] identifyUser user before Groundcover SDK initialization");return}L.identifyUser(i);}function ie(i){L&&L.sendCustomEvent(i);}function oe(i){L&&L.captureException(i);}var Pt={init:re,identifyUser:ne,sendCustomEvent:ie,captureException:oe};export{oe as captureException,Pt as default,ie as sendCustomEvent};
|