@aj-2000-test/goodlogs-sdk 0.4.3 → 0.4.5
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/{client-CaWt4mri.d.cts → client-CR9BnNN-.d.cts} +7 -0
- package/dist/{client-CaWt4mri.d.ts → client-CR9BnNN-.d.ts} +7 -0
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +6 -6
- package/dist/memory.d.cts +1 -1
- package/dist/memory.d.ts +1 -1
- package/dist/profiling.d.cts +1 -1
- package/dist/profiling.d.ts +1 -1
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/replay.cjs +1 -1
- package/dist/replay.d.cts +3 -1
- package/dist/replay.d.ts +3 -1
- package/dist/replay.js +1 -1
- package/package.json +1 -1
|
@@ -32,6 +32,9 @@ interface GoodLogsOptions {
|
|
|
32
32
|
/** Deployment environment (e.g. "production", "staging"). Defaults to "production".
|
|
33
33
|
* Can also be set later via setEnvironment(). */
|
|
34
34
|
environment?: string;
|
|
35
|
+
/** Enable verbose console logging for debugging SDK behavior.
|
|
36
|
+
* Logs session lifecycle, flush events, replay chunks, errors, and timing. */
|
|
37
|
+
debug?: boolean;
|
|
35
38
|
}
|
|
36
39
|
interface LogEntry {
|
|
37
40
|
severity: Severity;
|
|
@@ -130,6 +133,8 @@ declare class GoodLogs {
|
|
|
130
133
|
private originalFetch;
|
|
131
134
|
/** Backup of XMLHttpRequest.prototype.{open,send} so detach() can restore. */
|
|
132
135
|
private xhrPatched;
|
|
136
|
+
/** Debug mode — logs SDK internals to console. */
|
|
137
|
+
_debug: boolean;
|
|
133
138
|
private logBuffer;
|
|
134
139
|
private eventBuffer;
|
|
135
140
|
private errorBuffer;
|
|
@@ -165,6 +170,8 @@ declare class GoodLogs {
|
|
|
165
170
|
getSessionId(): string;
|
|
166
171
|
/** Start a new session (e.g., on navigation reset). */
|
|
167
172
|
newSession(): void;
|
|
173
|
+
/** Debug logger — only emits when debug:true is set. */
|
|
174
|
+
_log(tag: string, data?: Record<string, unknown>): void;
|
|
168
175
|
/** Set a specific session ID. */
|
|
169
176
|
setSessionId(id: string): void;
|
|
170
177
|
/** Set the application release/version. Attached to all subsequent telemetry. */
|
|
@@ -32,6 +32,9 @@ interface GoodLogsOptions {
|
|
|
32
32
|
/** Deployment environment (e.g. "production", "staging"). Defaults to "production".
|
|
33
33
|
* Can also be set later via setEnvironment(). */
|
|
34
34
|
environment?: string;
|
|
35
|
+
/** Enable verbose console logging for debugging SDK behavior.
|
|
36
|
+
* Logs session lifecycle, flush events, replay chunks, errors, and timing. */
|
|
37
|
+
debug?: boolean;
|
|
35
38
|
}
|
|
36
39
|
interface LogEntry {
|
|
37
40
|
severity: Severity;
|
|
@@ -130,6 +133,8 @@ declare class GoodLogs {
|
|
|
130
133
|
private originalFetch;
|
|
131
134
|
/** Backup of XMLHttpRequest.prototype.{open,send} so detach() can restore. */
|
|
132
135
|
private xhrPatched;
|
|
136
|
+
/** Debug mode — logs SDK internals to console. */
|
|
137
|
+
_debug: boolean;
|
|
133
138
|
private logBuffer;
|
|
134
139
|
private eventBuffer;
|
|
135
140
|
private errorBuffer;
|
|
@@ -165,6 +170,8 @@ declare class GoodLogs {
|
|
|
165
170
|
getSessionId(): string;
|
|
166
171
|
/** Start a new session (e.g., on navigation reset). */
|
|
167
172
|
newSession(): void;
|
|
173
|
+
/** Debug logger — only emits when debug:true is set. */
|
|
174
|
+
_log(tag: string, data?: Record<string, unknown>): void;
|
|
168
175
|
/** Set a specific session ID. */
|
|
169
176
|
setSessionId(id: string): void;
|
|
170
177
|
/** Set the application release/version. Attached to all subsequent telemetry. */
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';var S=(
|
|
2
|
-
`);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let
|
|
3
|
-
`)){let
|
|
1
|
+
'use strict';var S=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var C={us:"https://goodlogs-api-us.happyhill-a7c56143.centralindia.azurecontainerapps.io",eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function B(o){let e=o.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function y(o,e){if(e)return e;let t=B(o);return C[t]||C.eu}var G=5e3,F=50,v="0.4.5",w="gl_anon_id",_="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let e=Math.random()*16|0;return (o==="x"?e:e&3|8).toString(16)})}function U(){let o={$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||(typeof screen<"u"&&(o.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(o.$language=navigator.language??""),typeof location<"u"&&(o.$url=location.href,o.$path=location.pathname,o.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(o.$referrer=document.referrer),document.title&&(o.$title=document.title))),o}function M(o,e){let t={$session_id:o,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(t.$url=location.href,t.$path=location.pathname),t}function D(o,e,t,n,r){let s=M(o,e);return t&&(s.$release=t),s.$environment=n,r.email&&(s.$user_email=r.email),r.name&&(s.$user_name=r.name),s}function K(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
|
|
2
|
+
`);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let n=e[t]?.trim();if(!n||n.includes("goodlogs")&&(n.includes("client.")||n.includes("index.")))continue;let r=n.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(r){let s=r[1]||"<anonymous>",i=r[2]?.replace(/^.*[/\\]/,"")??"",d=r[3];return `${s}@${i}:${d}`}}}catch{}}function X(o){let e=[],t=o;for(;t&&t.tagName;){let n=t.tagName.toLowerCase();if(n==="html"||n==="body"){e.unshift(n);break}if(t.id){e.unshift(`#${t.id}`);break}let r=1,s=t;for(;s?.previousElementSibling;)s.previousElementSibling.tagName?.toLowerCase()===n&&r++,s=s.previousElementSibling;e.unshift(r>1?`${n}:nth-of-type(${r})`:n),t=t.parentElement;}return e.join(" > ").slice(0,200)}function V(){if(typeof localStorage<"u"){let o=localStorage.getItem(w);if(o)return o;let e=b();return localStorage.setItem(w,e),e}return b()}function z(){if(typeof sessionStorage<"u"){let o=sessionStorage.getItem(_);if(o)return o;let e=b();return sessionStorage.setItem(_,e),e}return b()}function W(){let o="";for(let e=0;e<32;e++)o+=(Math.random()*16|0).toString(16);return o}function J(){let o="";for(let e=0;e<16;e++)o+=(Math.random()*16|0).toString(16);return o}function Y(o,e){switch(o){case "lcp":return e<=2500?"good":e<=4e3?"needs-improvement":"poor";case "inp":return e<=200?"good":e<=500?"needs-improvement":"poor";case "cls":return e<=.1?"good":e<=.25?"needs-improvement":"poor";case "fcp":return e<=1800?"good":e<=3e3?"needs-improvement":"poor";case "ttfb":return e<=800?"good":e<=1800?"needs-improvement":"poor";case "dns":return e<=20?"good":e<=100?"needs-improvement":"poor";case "tcp":return e<=50?"good":e<=200?"needs-improvement":"poor";case "download":return e<=100?"good":e<=500?"needs-improvement":"poor";case "dom_processing":return e<=500?"good":e<=1500?"needs-improvement":"poor";case "page_load":return e<=1e3?"good":e<=3e3?"needs-improvement":"poor";default:return}}function Q(o){if(!o)return [];let e=[];for(let t of o.split(`
|
|
3
|
+
`)){let n=t.trim();if(!n||n.startsWith("Error")||n.startsWith("at Error"))continue;let r=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(n);if(r){let s=r[1]?.trim(),i=r[2];e.push({function:s&&s!=="<anonymous>"?s:void 0,filename:i,lineno:Number(r[3]),colno:Number(r[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")&&!i.startsWith("internal/")});continue}if(r=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(n),r){let s=r[1]?.trim(),i=r[2];e.push({function:s||void 0,filename:i,lineno:Number(r[3]),colno:Number(r[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")});}}return e}var R=class R{constructor(e){this.userProperties={};this.originalFetch=null;this.xhrPatched=false;this._debug=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??G,this.batchSize=e.batchSize??F,this.defaultContext=e.defaultContext??{},this.onError=e.onError??(()=>{}),this.disabled=e.disabled??false,this.telemetry=e.telemetry??true,this.useEnvelope=e.useEnvelope??false,this.autoFetch=e.autoFetch??(this.useEnvelope&&e.autocapture!==false),this.release=e.release??null,this.environment=e.environment??"production",this._debug=e.debug??false,this.anonymousId=V(),this.sessionId=z(),this._debug&&this._log("init",{endpoint:this.endpoint,sessionId:this.sessionId,distinctId:this.anonymousId,release:this.release,env:this.environment,envelope:this.useEnvelope,autoFetch:this.autoFetch}),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),!this.disabled&&typeof setTimeout<"u"&&setTimeout(()=>{!this.release&&typeof console<"u"&&console.warn("[GoodLogs] No release version set. Set `release` in options or call gl.setRelease('1.2.3') for release health tracking.");},5e3),this.disabled||(this.startTimer(),this.attachPageLifecycle(),e.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(e,t,n){if(this.disabled)return;let r=65536,s=t;t.length>r&&(s=t.slice(0,r-100)+`
|
|
4
4
|
|
|
5
|
-
[truncated \u2014 original ${t.length} chars, limit ${
|
|
6
|
-
`);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(e,t,r=0){try{let n=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:e});if(n.status===429||n.status===503){if(r<4){let s=Math.min(1e3*Math.pow(2,r),8e3),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),this.postEnvelopeWithRetry(e,t,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!n.ok){let s=await n.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${n.status}: ${s}`)),n.status>=500&&r===0)for(let o of t)o.kind==="log"?this.logBuffer.push(o.entry):o.kind==="event"?this.eventBuffer.push(o.entry):o.kind==="error"?this.errorBuffer.push(o.entry):o.kind==="vital"?this.vitalBuffer.push(o.entry):this.spanBuffer.push(o.entry);}}catch(n){if(r===0)for(let s of t)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(n instanceof Error?n:new Error(String(n)));}}async postWithRetry(e,t,r,n=0){try{let s=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:t})});if(s.status===429||s.status===503){if(n<4){let d=Math.min(1e3*Math.pow(2,n),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(e,t,r,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&n===0&&r(t);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=t.slice(o.accepted??0);d.length>0&&r(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));n===0&&r(t),this.onError(o);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let e=(t,r)=>{if(this.useEnvelope)this.captureVital(t.toLowerCase(),r);else {let n=t==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:t,[n]:t==="CLS"?r:Math.round(r)}});}};try{new PerformanceObserver(t=>{let r=t.getEntries()[0];r&&e("FCP",r.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let r=t.getEntries(),n=r[r.length-1];n&&e("LCP",n.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let t=0;if(new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(t+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let r=()=>{t>0&&e("CLS",Math.round(t*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();});}}catch{}try{new PerformanceObserver(t=>{for(let r of t.getEntries()){let n=r;n.responseStart&&n.responseStart>0&&e("TTFB",n.responseStart);let s=l=>l&&Number.isFinite(l)&&l>0?l:0,o=s(n.domainLookupEnd)-s(n.domainLookupStart);o>0&&this.captureVital("dns",o);let d=s(n.connectEnd)-s(n.connectStart);d>0&&this.captureVital("tcp",d);let a=s(n.responseEnd)-s(n.responseStart);a>0&&this.captureVital("download",a);let u=s(n.domComplete)-s(n.responseEnd);u>0&&this.captureVital("dom_processing",u);let c=s(n.loadEventEnd)-s(n.fetchStart);c>0&&this.captureVital("page_load",c);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let t=performance.getEntriesByType?.("navigation")?.[0];t?.responseStart&&e("TTFB",t.responseStart);let r=u=>u&&Number.isFinite(u)&&u>0?u:0,n=r(t?.domainLookupEnd)-r(t?.domainLookupStart);n>0&&this.captureVital("dns",n);let s=r(t?.connectEnd)-r(t?.connectStart);s>0&&this.captureVital("tcp",s);let o=r(t?.responseEnd)-r(t?.responseStart);o>0&&this.captureVital("download",o);let d=r(t?.domComplete)-r(t?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=r(t?.loadEventEnd)-r(t?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(t=>{for(let r of t.getEntries()){let n=r.duration;n>0&&e("INP",n);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let e=(t="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,t));};if(typeof history<"u"){let t=history.pushState,r=history.replaceState;history.pushState=function(...n){t.apply(this,n),e("push");},history.replaceState=function(...n){r.apply(this,n),e("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>e("popstate"));}startNavTransaction(e,t){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:e,attributes:{"navigation.type":t,"http.url":typeof location<"u"?location.href:e}});let r=this.navTransaction;setTimeout(()=>{this.navTransaction===r&&(r.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let e=globalThis;typeof e.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=t=>{let r=t,n=r.error??new Error(r.message??"Uncaught error");try{this.captureException(n,{tags:{source:"window.onerror"},extra:r.filename?{filename:r.filename,lineno:r.lineno,colno:r.colno}:void 0});}catch{}},this.rejectionHandler=t=>{let n=t.reason,s=n;if(!(n instanceof Error)){let o;if(typeof n=="string")o=n;else try{o=JSON.stringify(n);}catch{o=String(n);}s=new Error(o);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},e.addEventListener("error",this.errorHandler),e.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let e=globalThis;typeof e.removeEventListener=="function"&&(this.errorHandler&&(e.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(e.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let e=globalThis;if(this.originalFetch)return;this.originalFetch=e.fetch;let t=e.fetch.bind(globalThis),r=this;e.fetch=function(s,o){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let l=s;d=l.url??"",a=l.method??a;}let u=o??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(r.endpoint))return t(s,u);let c=r.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:r.navTransaction??void 0});try{let l=`00-${c.trace_id}-${c.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:l},t(s,f).then(h=>{let p=h;return typeof p.status=="number"&&c.setAttribute("http.status_code",p.status),c.setStatus(p.ok===!1?"error":"ok"),c.finish(),h}).catch(h=>{throw c.setStatus("error"),c.setAttribute("error.message",h instanceof Error?h.message:String(h)),c.finish(),h})}catch(l){throw c.setStatus("error"),c.finish(),l}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let t=globalThis.XMLHttpRequest;if(!t||!t.prototype)return;let r=Symbol.for("goodlogs.xhr.patched"),n=t.prototype;if(n[r]){this.xhrPatched=true;return}let s=n.open,o=n.setRequestHeader,d=n.send,a=this;n.open=function(c,l,...f){return this.__gl_method=typeof c=="string"?c.toUpperCase():"GET",this.__gl_url=typeof l=="string"?l:String(l??""),this.__gl_headers_set=false,s.apply(this,[c,l,...f])},n.setRequestHeader=function(c,l){return this.__gl_headers_set=true,o.apply(this,[c,l])},n.send=function(c){let l=this.__gl_url||"",f=this.__gl_method||"GET";if(l.startsWith(a.endpoint))return d.apply(this,[c]);let g=a.startSpan({op:"http.client",name:`${f} ${l}`,attributes:{"http.method":f,"http.url":l},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;o.apply(this,["traceparent",m]);}catch{}let h=(m,_,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(_?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[c])},n[r]=true,n.__gl_orig_open=s,n.__gl_orig_set_header=o,n.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let t=globalThis.XMLHttpRequest?.prototype;if(!t)return;let r=Symbol.for("goodlogs.xhr.patched");t.__gl_orig_open&&(t.open=t.__gl_orig_open),t.__gl_orig_set_header&&(t.setRequestHeader=t.__gl_orig_set_header),t.__gl_orig_send&&(t.send=t.__gl_orig_send),delete t.__gl_orig_open,delete t.__gl_orig_set_header,delete t.__gl_orig_send,delete t[r],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let r=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!r)return;let n=r.getAttribute?.("data-gl-event"),s=r.tagName?.toLowerCase()??"",o=(r.textContent??"").trim().slice(0,50),d=r.getAttribute?.("href")??void 0,a=(r.className??"").toString().slice(0,80);this.track(n||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:d,$element_classes:a||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:r,body:JSON.stringify({batch:e.map(n=>({severity:n.severity,message:n.message,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:r,body:JSON.stringify({batch:t.map(n=>({event:n.event,distinctId:n.distinctId,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,r){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...r,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var I=R;var L=class{constructor(e){if(!e.apiKey)throw new Error("apiKey is required");if(!e.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint),this.timeout=e.timeout??3e4,this.alerts=new $(this),this.slos=new P(this),this.ai=new A(this);}async _request(e,t,r){let n=`${this.endpoint}${t}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(n,{method:e,headers:s,body:r?JSON.stringify(r):void 0,signal:o.signal});if(!a.ok){let u=await a.json().catch(()=>({})),c=u?.error?.message??`API error ${a.status}`;throw new T(a.status,c,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(e){return this._request("GET",e)}_post(e,t){return this._request("POST",e,t)}_put(e,t){return this._request("PUT",e,t)}_delete(e){return this._request("DELETE",e)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(e){return this._post("/v1/gql/query",{q:e})}gqlBatch(e){return this._post("/v1/gql",{queries:e})}gqlAutocomplete(e,t){let r=`/v1/gql/autocomplete?q=${encodeURIComponent(e)}`;return t!==void 0&&(r+=`&cursor=${t}`),this._get(r)}nl2gql(e,t){return this._post("/v1/gql/nl",{prompt:e,mode:t})}},$=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/alerts")}create(e){return this.client._post("/v1/alerts",e)}update(e,t){return this.client._put(`/v1/alerts/${e}`,t)}delete(e){return this.client._delete(`/v1/alerts/${e}`)}mute(e,t){return this.client._post(`/v1/alerts/${e}/mute`,{minutes:t})}},P=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/slos")}create(e){return this.client._post("/v1/slos",e)}update(e,t){return this.client._put(`/v1/slos/${e}`,t)}delete(e){return this.client._delete(`/v1/slos/${e}`)}},A=class{constructor(e){this.client=e;}chat(e,t){return this.client._post("/v1/ai/chat",{message:e,session_id:t})}},T=class extends Error{constructor(t,r,n){super(r);this.status=t;this.code=n;this.name="GoodLogsApiError";}};var q="0.1.0";function Q(i,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":q};e?.token&&(r.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:r,body:JSON.stringify({source:i.source,event:i.event,level:i.level??"info",metadata:{...i.metadata,sdk_version:q}}),keepalive:true}).catch(()=>{});}function C(i){if(!i)return null;let e=i.trim().split("-");if(e.length!==4)return null;let[t,r,n,s]=e;return t.length!==2||r.length!==32||n.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(r)||!/^[0-9a-f]+$/.test(n)?null:{trace_id:r,parent_span_id:n}}function N(i,e){if(!i)return;let t=i[e]??i[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function Z(i){return function(t,r,n){let s=(t.method??"GET").toUpperCase(),o=t.originalUrl??t.url??"",d=C(N(t.headers,"traceparent")),a=i.startTransaction({op:"http.server",name:`${s} ${o}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":o}}),u=false,c=()=>{if(u)return;u=true;let l=t.route?.path;l&&a.setAttribute("http.route",l);let f=r.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};r.on("finish",c),r.on("close",c),t.goodlogs={span:a},n();}}function ee(i){return function(t,r,n){t.addHook("onRequest",(s,o,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",c=C(N(s.headers,"traceparent")),l=i.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:c?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=l,d();}),t.addHook("onResponse",(s,o,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let c=o.statusCode??o.raw?.statusCode??200;a.setAttribute("http.status_code",c),a.setStatus(c>=500?"error":"ok"),a.finish();}d();}),n();}}function te(i){return {intercept(e,t){let r=e.switchToHttp(),n=r.getRequest(),s=r.getResponse(),o=(n.method??"GET").toUpperCase(),d=n.originalUrl??n.url??"",a=C(N(n.headers,"traceparent")),u=i.startTransaction({op:"http.server",name:`${o} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":o,"http.url":d}}),c=false,l=(g,h)=>{if(c)return;c=true;let p=n.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>l()),s.on("close",()=>l());let f=t.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),l(500,true);},complete:()=>l()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function ne(i){let e=globalThis.process;if(!e||typeof e.on!="function")return;let t=e,r=Symbol.for("goodlogs.node-process.patched");t[r]||(e.on("uncaughtException",n=>{try{i.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),i.flush();}catch{}}),e.on("unhandledRejection",n=>{try{let s=n instanceof Error?n:new Error(typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[r]=true);}var H=globalThis.URL;function E(i){return !!H&&i instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function re(...i){let e=i[0],t=i[1],r="GET",n="";if(typeof e=="string")n=e,t&&typeof t=="object"&&!E(t)&&(r=String(t.method??r).toUpperCase());else if(E(e))n=e.toString(),t&&typeof t=="object"&&!E(t)&&(r=String(t.method??r).toUpperCase());else if(e&&typeof e=="object"){let o=e;r=String(o.method??r).toUpperCase();let d=(o.protocol??"http:").replace(":",""),a=o.hostname??o.host??"localhost",u=o.port?`:${o.port}`:"";n=`${d}://${a}${u}${o.path??"/"}`;}return {method:r,url:n,isOurs:o=>!!o&&n.startsWith(o)}}function se(i,e,t){let r=i[0]&&typeof i[0]=="object"&&!E(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!E(i[1])?i[1]:void 0;r&&(r.headers||(r.headers={}),!(e in r.headers)&&!(e.toLowerCase()in r.headers)&&(r.headers[e]=t));}function oe(i,e){let t=e?.endpoint??i.endpoint??"",r=n=>{let s=n;if(s[j])return;s[j]=true;let o=n.request.bind(n);n.request=function(...a){let{method:u,url:c,isOurs:l}=re(...a);if(!c||l(t))return o(...a);let f=i.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});se(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,_)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),_?(f.setAttribute("error.message",_.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=o(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let n=S("http");r(n);}catch{}try{let n=S("https");r(n);}catch{}}}
|
|
7
|
-
exports.GoodLogs
|
|
5
|
+
[truncated \u2014 original ${t.length} chars, limit ${r}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${r} chars`)));let i=K(),d={severity:e,message:s,properties:{...this.defaultContext,...D(this.sessionId,this.anonymousId,this.release,this.environment,this.userProperties),...i?{code_location:i}:{},...n},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}fatal(e,t){this.log("fatal",e,t);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(w,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(_,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(_,this.sessionId),this._debug&&this._log("newSession",{sessionId:this.sessionId});}_log(e,t){if(!this._debug||typeof console>"u")return;let n=new Date().toISOString().slice(11,23);t?console.log(`%c[GL ${n}]%c ${e}`,"color:#10b981;font-weight:bold","color:inherit",t):console.log(`%c[GL ${n}]%c ${e}`,"color:#10b981;font-weight:bold","color:inherit");}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(_,e);}setRelease(e){this.release=e;}getRelease(){return this.release}setEnvironment(e){this.environment=e;}getEnvironment(){return this.environment}setUser(e){this.identify(e.id),this.userProperties={...e};}getUser(){return {...this.userProperties}}track(e,t){if(this.disabled)return;let{distinctId:n,...r}=t??{},s={event:e,distinctId:n??this.anonymousId,properties:{...U(),...r,$session_id:this.sessionId,...this.release?{$release:this.release}:{},$environment:this.environment},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this._debug&&this._log("track",{event:e,sessionId:this.sessionId}),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(e){if(this.disabled)return;let t={ts:e.ts??new Date().toISOString(),...e};this.breadcrumbBuffer.push(t),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(e,t){if(this.disabled)return;let n=this.buildErrorEntry(e,t);this._debug&&this._log("captureException",{message:n.message,type:n.exception_type,sessionId:this.sessionId,traceId:n.trace_id}),this.useEnvelope?(this.errorBuffer.push(n),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(n.message,{exception_type:n.exception_type,frames:n.frames});}captureMessage(e,t){if(this.disabled)return;let n={level:t?.level??"info",message:e,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:t?.fingerprint,tags:{session_id:this.sessionId,...t?.tags},extra:t?.extra,user_id:t?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(n),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(e);}buildErrorEntry(e,t){let n,r,s=[];if(e instanceof Error)n=e.name,r=e.message,s=Q(e.stack);else if(typeof e=="string")r=e;else try{r=JSON.stringify(e);}catch{r=String(e);}return {level:t?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:n,message:r,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:t?.fingerprint,tags:{session_id:this.sessionId,...t?.tags},extra:t?.extra,user_id:t?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id,release:this.release??void 0,environment:this.environment}}captureVital(e,t,n){if(this.disabled||!Number.isFinite(t)||t<0)return;let r=n?.rating??Y(e,t),s={metric:e,value_ms:e==="cls"?t:Math.round(t),rating:r,route:n?.route??(typeof location<"u"?location.pathname:void 0),page_url:typeof location<"u"?location.href:void 0,session_id:this.sessionId,user_id:this.anonymousId,attributes:n?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:e.toUpperCase(),$value_ms:s.value_ms,$rating:r}});}startTransaction(e){return this.makeSpan(void 0,e)}startSpan(e){return this.makeSpan(void 0,e)}makeSpan(e,t){let n=t?.trace_id??t?.parent?.trace_id??e?.trace_id??W(),r=J(),s=t?.parent?.span_id??e?.span_id,i=Date.now(),d=new Date(i).toISOString(),a={...t?.attributes??{}},u="unset",l=[],c=false,f=this,g={span_id:r,trace_id:n,setAttribute(h,p){a[h]=p;},setStatus(h){u=h;},addEvent(h,p){l.push({ts:new Date().toISOString(),name:h,attributes:p});},startChild(h){return f.makeSpan(g,h)},finish(){if(c)return;c=true;let h=Date.now(),p={span_id:r,trace_id:n,parent_span_id:s,name:t?.name,op:t?.op,status:u==="unset"?"ok":u,kind:t?.kind,attributes:a,events:l,start_time:d,end_time:new Date(h).toISOString(),timestamp:d,duration_ms:h-i};f.useEnvelope&&(f.spanBuffer.push(p),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n=this.errorBuffer.splice(0),r=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0);this._debug&&(e.length||t.length||n.length||r.length||s.length)&&this._log("flush",{logs:e.length,events:t.length,errors:n.length,vitals:r.length,spans:s.length});let i=[];this.useEnvelope?(e.length>0||t.length>0||n.length>0||r.length>0||s.length>0)&&i.push(this.sendEnvelope(e,t,n,r,s)):(e.length>0&&i.push(this.sendLogs(e)),t.length>0&&i.push(this.sendEvents(t))),await Promise.all(i);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),this.detachFetchInstrumentation(),this.detachXhrInstrumentation(),this.detachGlobalErrorHandlers(),this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),await this.flush();}async sendLogs(e){for(let n=0;n<e.length;n+=500){let s=e.slice(n,n+500).map(i=>({severity:i.severity,message:i.message,properties:i.properties,timestamp:i.timestamp}));await this.postWithRetry("/v1/logs",s,i=>{for(let d of i)this.logBuffer.push({severity:d.severity,message:d.message,properties:d.properties,timestamp:d.timestamp});});}}async sendEvents(e){for(let n=0;n<e.length;n+=500){let s=e.slice(n,n+500).map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}));await this.postWithRetry("/v1/events",s,i=>{for(let d of i)this.eventBuffer.push({event:d.event,distinctId:d.distinctId,properties:d.properties,timestamp:d.timestamp});});}}async sendEnvelope(e,t,n,r,s){let d=[...e.map(a=>({kind:"log",entry:a})),...t.map(a=>({kind:"event",entry:a})),...n.map(a=>({kind:"error",entry:a})),...r.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let u=d.slice(a,a+1e3),l=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),c=u.map(g=>{if(g.kind==="log"){let p=g.entry;return JSON.stringify({type:"log",severity:p.severity,message:p.message,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="event"){let p=g.entry;return JSON.stringify({type:"event",event:p.event,distinctId:p.distinctId,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="error"){let p=g.entry;return JSON.stringify({type:"error",...p})}if(g.kind==="vital"){let p=g.entry;return JSON.stringify({type:"vital",...p})}let h=g.entry;return JSON.stringify({type:"span",...h})}),f=[l,...c].join(`
|
|
6
|
+
`);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(e,t,n=0){try{let r=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:e});if(r.status===429||r.status===503){if(n<4){let s=Math.min(1e3*Math.pow(2,n),8e3),i=Math.random()*500;return await new Promise(d=>setTimeout(d,s+i)),this.postEnvelopeWithRetry(e,t,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!r.ok){let s=await r.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${r.status}: ${s}`)),r.status>=500&&n===0)for(let i of t)i.kind==="log"?this.logBuffer.push(i.entry):i.kind==="event"?this.eventBuffer.push(i.entry):i.kind==="error"?this.errorBuffer.push(i.entry):i.kind==="vital"?this.vitalBuffer.push(i.entry):this.spanBuffer.push(i.entry);}}catch(r){if(n===0)for(let s of t)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(r instanceof Error?r:new Error(String(r)));}}async postWithRetry(e,t,n,r=0){try{let s=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:t})});if(s.status===429||s.status===503){if(r<4){let d=Math.min(1e3*Math.pow(2,r),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(e,t,n,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&r===0&&n(t);return}let i=await s.json().catch(()=>null);if(i&&i.rejected&&i.rejected>0){let d=t.slice(i.accepted??0);d.length>0&&n(d);}}catch(s){let i=s instanceof Error?s:new Error(String(s));r===0&&n(t),this.onError(i);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let e=(t,n)=>{if(this.useEnvelope)this.captureVital(t.toLowerCase(),n);else {let r=t==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:t,[r]:t==="CLS"?n:Math.round(n)}});}};try{new PerformanceObserver(t=>{let n=t.getEntries()[0];n&&e("FCP",n.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let n=t.getEntries(),r=n[n.length-1];r&&e("LCP",r.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let t=0;if(new PerformanceObserver(n=>{for(let r of n.getEntries())r.hadRecentInput||(t+=r.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let n=()=>{t>0&&e("CLS",Math.round(t*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n();});}}catch{}try{new PerformanceObserver(t=>{for(let n of t.getEntries()){let r=n;r.responseStart&&r.responseStart>0&&e("TTFB",r.responseStart);let s=c=>c&&Number.isFinite(c)&&c>0?c:0,i=s(r.domainLookupEnd)-s(r.domainLookupStart);i>0&&this.captureVital("dns",i);let d=s(r.connectEnd)-s(r.connectStart);d>0&&this.captureVital("tcp",d);let a=s(r.responseEnd)-s(r.responseStart);a>0&&this.captureVital("download",a);let u=s(r.domComplete)-s(r.responseEnd);u>0&&this.captureVital("dom_processing",u);let l=s(r.loadEventEnd)-s(r.fetchStart);l>0&&this.captureVital("page_load",l);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let t=performance.getEntriesByType?.("navigation")?.[0];t?.responseStart&&e("TTFB",t.responseStart);let n=u=>u&&Number.isFinite(u)&&u>0?u:0,r=n(t?.domainLookupEnd)-n(t?.domainLookupStart);r>0&&this.captureVital("dns",r);let s=n(t?.connectEnd)-n(t?.connectStart);s>0&&this.captureVital("tcp",s);let i=n(t?.responseEnd)-n(t?.responseStart);i>0&&this.captureVital("download",i);let d=n(t?.domComplete)-n(t?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=n(t?.loadEventEnd)-n(t?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(t=>{for(let n of t.getEntries()){let r=n.duration;r>0&&e("INP",r);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let e=(t="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,t));};if(typeof history<"u"){let t=history.pushState,n=history.replaceState;history.pushState=function(...r){t.apply(this,r),e("push");},history.replaceState=function(...r){n.apply(this,r),e("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>e("popstate"));}startNavTransaction(e,t){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:e,attributes:{"navigation.type":t,"http.url":typeof location<"u"?location.href:e}});let n=this.navTransaction;setTimeout(()=>{this.navTransaction===n&&(n.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let e=globalThis;typeof e.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=t=>{let n=t,r=n.error??new Error(n.message??"Uncaught error");try{this.captureException(r,{tags:{source:"window.onerror"},extra:n.filename?{filename:n.filename,lineno:n.lineno,colno:n.colno}:void 0});}catch{}},this.rejectionHandler=t=>{let r=t.reason,s=r;if(!(r instanceof Error)){let i;if(typeof r=="string")i=r;else try{i=JSON.stringify(r);}catch{i=String(r);}s=new Error(i);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},e.addEventListener("error",this.errorHandler),e.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let e=globalThis;typeof e.removeEventListener=="function"&&(this.errorHandler&&(e.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(e.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let e=globalThis;if(this.originalFetch)return;this.originalFetch=e.fetch;let t=e.fetch.bind(globalThis),n=this;e.fetch=function(s,i){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let c=s;d=c.url??"",a=c.method??a;}let u=i??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(n.endpoint))return t(s,u);let l=n.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:n.navTransaction??void 0});try{let c=`00-${l.trace_id}-${l.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:c},t(s,f).then(h=>{let p=h;return typeof p.status=="number"&&l.setAttribute("http.status_code",p.status),l.setStatus(p.ok===!1?"error":"ok"),l.finish(),h}).catch(h=>{throw l.setStatus("error"),l.setAttribute("error.message",h instanceof Error?h.message:String(h)),l.finish(),h})}catch(c){throw l.setStatus("error"),l.finish(),c}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let t=globalThis.XMLHttpRequest;if(!t||!t.prototype)return;let n=Symbol.for("goodlogs.xhr.patched"),r=t.prototype;if(r[n]){this.xhrPatched=true;return}let s=r.open,i=r.setRequestHeader,d=r.send,a=this;r.open=function(l,c,...f){return this.__gl_method=typeof l=="string"?l.toUpperCase():"GET",this.__gl_url=typeof c=="string"?c:String(c??""),this.__gl_headers_set=false,s.apply(this,[l,c,...f])},r.setRequestHeader=function(l,c){return this.__gl_headers_set=true,i.apply(this,[l,c])},r.send=function(l){let c=this.__gl_url||"",f=this.__gl_method||"GET";if(c.startsWith(a.endpoint))return d.apply(this,[l]);let g=a.startSpan({op:"http.client",name:`${f} ${c}`,attributes:{"http.method":f,"http.url":c},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;i.apply(this,["traceparent",m]);}catch{}let h=(m,E,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(E?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[l])},r[n]=true,r.__gl_orig_open=s,r.__gl_orig_set_header=i,r.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let t=globalThis.XMLHttpRequest?.prototype;if(!t)return;let n=Symbol.for("goodlogs.xhr.patched");t.__gl_orig_open&&(t.open=t.__gl_orig_open),t.__gl_orig_set_header&&(t.setRequestHeader=t.__gl_orig_set_header),t.__gl_orig_send&&(t.send=t.__gl_orig_send),delete t.__gl_orig_open,delete t.__gl_orig_set_header,delete t.__gl_orig_send,delete t[n],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let t=e,n=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!n)return;let r=n.getAttribute?.("data-gl-event"),s=n.tagName?.toLowerCase()??"",i=(n.textContent??"").trim().slice(0,50),d=n.getAttribute?.("href")??void 0,a=(n.className??"").toString().slice(0,80),u=globalThis,l=u.innerWidth,c=u.innerHeight,f=u.scrollY,g=typeof document<"u"?document.documentElement?.scrollHeight:void 0;this.track(r||"$click",{properties:{$element_tag:s,$element_text:i||void 0,$element_href:d,$element_classes:a||void 0,$element_selector:X(n),$click_x:t.clientX,$click_y:t.clientY,$page_x:t.pageX,$page_y:t.pageY,$viewport_w:l,$viewport_h:c,$scroll_y:f,$doc_h:g,$url:typeof location<"u"?location.href:void 0,$pathname:typeof location<"u"?location.pathname:void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:n,body:JSON.stringify({batch:e.map(r=>({severity:r.severity,message:r.message,properties:r.properties,timestamp:r.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:n,body:JSON.stringify({batch:t.map(r=>({event:r.event,distinctId:r.distinctId,properties:r.properties,timestamp:r.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,n){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...n,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var $=R;var x=class{constructor(e){if(!e.apiKey)throw new Error("apiKey is required");if(!e.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint),this.timeout=e.timeout??3e4,this.alerts=new L(this),this.slos=new P(this),this.ai=new A(this);}async _request(e,t,n){let r=`${this.endpoint}${t}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=new AbortController,d=setTimeout(()=>i.abort(),this.timeout);try{let a=await fetch(r,{method:e,headers:s,body:n?JSON.stringify(n):void 0,signal:i.signal});if(!a.ok){let u=await a.json().catch(()=>({})),l=u?.error?.message??`API error ${a.status}`;throw new T(a.status,l,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(e){return this._request("GET",e)}_post(e,t){return this._request("POST",e,t)}_put(e,t){return this._request("PUT",e,t)}_delete(e){return this._request("DELETE",e)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(e){return this._post("/v1/gql/query",{q:e})}gqlBatch(e){return this._post("/v1/gql",{queries:e})}gqlAutocomplete(e,t){let n=`/v1/gql/autocomplete?q=${encodeURIComponent(e)}`;return t!==void 0&&(n+=`&cursor=${t}`),this._get(n)}nl2gql(e,t){return this._post("/v1/gql/nl",{prompt:e,mode:t})}},L=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/alerts")}create(e){return this.client._post("/v1/alerts",e)}update(e,t){return this.client._put(`/v1/alerts/${e}`,t)}delete(e){return this.client._delete(`/v1/alerts/${e}`)}mute(e,t){return this.client._post(`/v1/alerts/${e}/mute`,{minutes:t})}},P=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/slos")}create(e){return this.client._post("/v1/slos",e)}update(e,t){return this.client._put(`/v1/slos/${e}`,t)}delete(e){return this.client._delete(`/v1/slos/${e}`)}},A=class{constructor(e){this.client=e;}chat(e,t){return this.client._post("/v1/ai/chat",{message:e,session_id:t})}},T=class extends Error{constructor(t,n,r){super(n);this.status=t;this.code=r;this.name="GoodLogsApiError";}};var H="0.1.0";function Z(o,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":H};e?.token&&(n.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:n,body:JSON.stringify({source:o.source,event:o.event,level:o.level??"info",metadata:{...o.metadata,sdk_version:H}}),keepalive:true}).catch(()=>{});}function I(o){if(!o)return null;let e=o.trim().split("-");if(e.length!==4)return null;let[t,n,r,s]=e;return t.length!==2||n.length!==32||r.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(n)||!/^[0-9a-f]+$/.test(r)?null:{trace_id:n,parent_span_id:r}}function N(o,e){if(!o)return;let t=o[e]??o[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function ee(o){return function(t,n,r){let s=(t.method??"GET").toUpperCase(),i=t.originalUrl??t.url??"",d=I(N(t.headers,"traceparent")),a=o.startTransaction({op:"http.server",name:`${s} ${i}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":i}}),u=false,l=()=>{if(u)return;u=true;let c=t.route?.path;c&&a.setAttribute("http.route",c);let f=n.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};n.on("finish",l),n.on("close",l),t.goodlogs={span:a},r();}}function te(o){return function(t,n,r){t.addHook("onRequest",(s,i,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",l=I(N(s.headers,"traceparent")),c=o.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:l?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=c,d();}),t.addHook("onResponse",(s,i,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let l=i.statusCode??i.raw?.statusCode??200;a.setAttribute("http.status_code",l),a.setStatus(l>=500?"error":"ok"),a.finish();}d();}),r();}}function ne(o){return {intercept(e,t){let n=e.switchToHttp(),r=n.getRequest(),s=n.getResponse(),i=(r.method??"GET").toUpperCase(),d=r.originalUrl??r.url??"",a=I(N(r.headers,"traceparent")),u=o.startTransaction({op:"http.server",name:`${i} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":i,"http.url":d}}),l=false,c=(g,h)=>{if(l)return;l=true;let p=r.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>c()),s.on("close",()=>c());let f=t.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),c(500,true);},complete:()=>c()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function re(o){let e=globalThis.process;if(!e||typeof e.on!="function")return;let t=e,n=Symbol.for("goodlogs.node-process.patched");t[n]||(e.on("uncaughtException",r=>{try{o.captureException(r instanceof Error?r:new Error(String(r)),{tags:{source:"uncaughtException"},level:"fatal"}),o.flush();}catch{}}),e.on("unhandledRejection",r=>{try{let s=r instanceof Error?r:new Error(typeof r=="string"?r:(()=>{try{return JSON.stringify(r)}catch{return String(r)}})());o.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[n]=true);}var q=globalThis.URL;function k(o){return !!q&&o instanceof q}var j=Symbol.for("goodlogs.node-http.patched");function se(...o){let e=o[0],t=o[1],n="GET",r="";if(typeof e=="string")r=e,t&&typeof t=="object"&&!k(t)&&(n=String(t.method??n).toUpperCase());else if(k(e))r=e.toString(),t&&typeof t=="object"&&!k(t)&&(n=String(t.method??n).toUpperCase());else if(e&&typeof e=="object"){let i=e;n=String(i.method??n).toUpperCase();let d=(i.protocol??"http:").replace(":",""),a=i.hostname??i.host??"localhost",u=i.port?`:${i.port}`:"";r=`${d}://${a}${u}${i.path??"/"}`;}return {method:n,url:r,isOurs:i=>!!i&&r.startsWith(i)}}function ie(o,e,t){let n=o[0]&&typeof o[0]=="object"&&!k(o[0])?o[0]:o[1]&&typeof o[1]=="object"&&!k(o[1])?o[1]:void 0;n&&(n.headers||(n.headers={}),!(e in n.headers)&&!(e.toLowerCase()in n.headers)&&(n.headers[e]=t));}function oe(o,e){let t=e?.endpoint??o.endpoint??"",n=r=>{let s=r;if(s[j])return;s[j]=true;let i=r.request.bind(r);r.request=function(...a){let{method:u,url:l,isOurs:c}=se(...a);if(!l||c(t))return i(...a);let f=o.startTransaction({op:"http.client",name:`${u} ${l}`,attributes:{"http.method":u,"http.url":l}});ie(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,E)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),E?(f.setAttribute("error.message",E.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=i(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let r=S("http");n(r);}catch{}try{let r=S("https");n(r);}catch{}}}
|
|
7
|
+
exports.GoodLogs=$;exports.GoodLogsApiError=T;exports.GoodLogsClient=x;exports.REGION_URLS=C;exports.goodlogsExpress=ee;exports.goodlogsFastify=te;exports.goodlogsNestInterceptor=ne;exports.instrumentNodeHttp=oe;exports.instrumentNodeProcess=re;exports.parseTraceparent=I;exports.resolveEndpoint=y;exports.resolveRegion=B;exports.sendTelemetry=Z;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as GoodLogs } from './client-
|
|
2
|
-
export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-
|
|
1
|
+
import { G as GoodLogs } from './client-CR9BnNN-.cjs';
|
|
2
|
+
export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-CR9BnNN-.cjs';
|
|
3
3
|
|
|
4
4
|
interface LogRecord {
|
|
5
5
|
id: number;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as GoodLogs } from './client-
|
|
2
|
-
export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-
|
|
1
|
+
import { G as GoodLogs } from './client-CR9BnNN-.js';
|
|
2
|
+
export { C as CaptureContext, E as ErrorBreadcrumb, a as ErrorEntry, b as ErrorFrame, c as EventEntry, d as GoodLogsOptions, L as LogEntry, S as Severity } from './client-CR9BnNN-.js';
|
|
3
3
|
|
|
4
4
|
interface LogRecord {
|
|
5
5
|
id: number;
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var S=(
|
|
2
|
-
`);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let
|
|
3
|
-
`)){let
|
|
1
|
+
var S=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var C={us:"https://goodlogs-api-us.happyhill-a7c56143.centralindia.azurecontainerapps.io",eu:"https://goodlogs-api-eu.yellowmeadow-422296f6.japaneast.azurecontainerapps.io",ap:"https://goodlogs-api-ap.delightfulsand-90b72c09.southeastasia.azurecontainerapps.io"};function B(o){let e=o.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function y(o,e){if(e)return e;let t=B(o);return C[t]||C.eu}var G=5e3,F=50,v="0.4.5",w="gl_anon_id",_="gl_session_id";function b(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let e=Math.random()*16|0;return (o==="x"?e:e&3|8).toString(16)})}function U(){let o={$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||(typeof screen<"u"&&(o.$screen=`${screen.width}x${screen.height}`),typeof navigator<"u"&&(o.$language=navigator.language??""),typeof location<"u"&&(o.$url=location.href,o.$path=location.pathname,o.$page=location.pathname.split("/").filter(Boolean).pop()||"/"),typeof document<"u"&&(document.referrer&&(o.$referrer=document.referrer),document.title&&(o.$title=document.title))),o}function M(o,e){let t={$session_id:o,$distinct_id:e,$goodlogs_sdk:"js",$goodlogs_sdk_version:v};return typeof navigator>"u"||typeof location<"u"&&(t.$url=location.href,t.$path=location.pathname),t}function D(o,e,t,n,r){let s=M(o,e);return t&&(s.$release=t),s.$environment=n,r.email&&(s.$user_email=r.email),r.name&&(s.$user_name=r.name),s}function K(){if(!(typeof document<"u"))try{let e=new Error().stack?.split(`
|
|
2
|
+
`);if(!e)return;for(let t=3;t<Math.min(e.length,8);t++){let n=e[t]?.trim();if(!n||n.includes("goodlogs")&&(n.includes("client.")||n.includes("index.")))continue;let r=n.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):\d+\)?/);if(r){let s=r[1]||"<anonymous>",i=r[2]?.replace(/^.*[/\\]/,"")??"",d=r[3];return `${s}@${i}:${d}`}}}catch{}}function X(o){let e=[],t=o;for(;t&&t.tagName;){let n=t.tagName.toLowerCase();if(n==="html"||n==="body"){e.unshift(n);break}if(t.id){e.unshift(`#${t.id}`);break}let r=1,s=t;for(;s?.previousElementSibling;)s.previousElementSibling.tagName?.toLowerCase()===n&&r++,s=s.previousElementSibling;e.unshift(r>1?`${n}:nth-of-type(${r})`:n),t=t.parentElement;}return e.join(" > ").slice(0,200)}function V(){if(typeof localStorage<"u"){let o=localStorage.getItem(w);if(o)return o;let e=b();return localStorage.setItem(w,e),e}return b()}function z(){if(typeof sessionStorage<"u"){let o=sessionStorage.getItem(_);if(o)return o;let e=b();return sessionStorage.setItem(_,e),e}return b()}function W(){let o="";for(let e=0;e<32;e++)o+=(Math.random()*16|0).toString(16);return o}function J(){let o="";for(let e=0;e<16;e++)o+=(Math.random()*16|0).toString(16);return o}function Y(o,e){switch(o){case "lcp":return e<=2500?"good":e<=4e3?"needs-improvement":"poor";case "inp":return e<=200?"good":e<=500?"needs-improvement":"poor";case "cls":return e<=.1?"good":e<=.25?"needs-improvement":"poor";case "fcp":return e<=1800?"good":e<=3e3?"needs-improvement":"poor";case "ttfb":return e<=800?"good":e<=1800?"needs-improvement":"poor";case "dns":return e<=20?"good":e<=100?"needs-improvement":"poor";case "tcp":return e<=50?"good":e<=200?"needs-improvement":"poor";case "download":return e<=100?"good":e<=500?"needs-improvement":"poor";case "dom_processing":return e<=500?"good":e<=1500?"needs-improvement":"poor";case "page_load":return e<=1e3?"good":e<=3e3?"needs-improvement":"poor";default:return}}function Q(o){if(!o)return [];let e=[];for(let t of o.split(`
|
|
3
|
+
`)){let n=t.trim();if(!n||n.startsWith("Error")||n.startsWith("at Error"))continue;let r=/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/.exec(n);if(r){let s=r[1]?.trim(),i=r[2];e.push({function:s&&s!=="<anonymous>"?s:void 0,filename:i,lineno:Number(r[3]),colno:Number(r[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")&&!i.startsWith("internal/")});continue}if(r=/^([^@]*)@(.+?):(\d+):(\d+)$/.exec(n),r){let s=r[1]?.trim(),i=r[2];e.push({function:s||void 0,filename:i,lineno:Number(r[3]),colno:Number(r[4]),abs_path:i,in_app:!i.includes("node_modules/")&&!i.includes("/dist/")});}}return e}var R=class R{constructor(e){this.userProperties={};this.originalFetch=null;this.xhrPatched=false;this._debug=false;this.logBuffer=[];this.eventBuffer=[];this.errorBuffer=[];this.vitalBuffer=[];this.spanBuffer=[];this.breadcrumbBuffer=[];this.timer=null;this.visibilityHandler=null;this.clickHandler=null;this.lastPath="";this.navTransaction=null;this.errorHandler=null;this.rejectionHandler=null;this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint).replace(/\/+$/,""),this.flushInterval=e.flushInterval??G,this.batchSize=e.batchSize??F,this.defaultContext=e.defaultContext??{},this.onError=e.onError??(()=>{}),this.disabled=e.disabled??false,this.telemetry=e.telemetry??true,this.useEnvelope=e.useEnvelope??false,this.autoFetch=e.autoFetch??(this.useEnvelope&&e.autocapture!==false),this.release=e.release??null,this.environment=e.environment??"production",this._debug=e.debug??false,this.anonymousId=V(),this.sessionId=z(),this._debug&&this._log("init",{endpoint:this.endpoint,sessionId:this.sessionId,distinctId:this.anonymousId,release:this.release,env:this.environment,envelope:this.useEnvelope,autoFetch:this.autoFetch}),this.disabled&&typeof console<"u"&&console.warn("[GoodLogs] SDK is disabled. No events or logs will be sent."),!this.disabled&&typeof setTimeout<"u"&&setTimeout(()=>{!this.release&&typeof console<"u"&&console.warn("[GoodLogs] No release version set. Set `release` in options or call gl.setRelease('1.2.3') for release health tracking.");},5e3),this.disabled||(this.startTimer(),this.attachPageLifecycle(),e.autocapture!==false&&(this.attachClickCapture(),this.captureWebVitals(),this.attachPageviewCapture(),this.attachGlobalErrorHandlers()),this.autoFetch&&(this.attachFetchInstrumentation(),this.attachXhrInstrumentation()),this.sendTelemetry("init","info"));}log(e,t,n){if(this.disabled)return;let r=65536,s=t;t.length>r&&(s=t.slice(0,r-100)+`
|
|
4
4
|
|
|
5
|
-
[truncated \u2014 original ${t.length} chars, limit ${
|
|
6
|
-
`);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(e,t,r=0){try{let n=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:e});if(n.status===429||n.status===503){if(r<4){let s=Math.min(1e3*Math.pow(2,r),8e3),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),this.postEnvelopeWithRetry(e,t,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!n.ok){let s=await n.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${n.status}: ${s}`)),n.status>=500&&r===0)for(let o of t)o.kind==="log"?this.logBuffer.push(o.entry):o.kind==="event"?this.eventBuffer.push(o.entry):o.kind==="error"?this.errorBuffer.push(o.entry):o.kind==="vital"?this.vitalBuffer.push(o.entry):this.spanBuffer.push(o.entry);}}catch(n){if(r===0)for(let s of t)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(n instanceof Error?n:new Error(String(n)));}}async postWithRetry(e,t,r,n=0){try{let s=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:t})});if(s.status===429||s.status===503){if(n<4){let d=Math.min(1e3*Math.pow(2,n),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(e,t,r,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&n===0&&r(t);return}let o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=t.slice(o.accepted??0);d.length>0&&r(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));n===0&&r(t),this.onError(o);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let e=(t,r)=>{if(this.useEnvelope)this.captureVital(t.toLowerCase(),r);else {let n=t==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:t,[n]:t==="CLS"?r:Math.round(r)}});}};try{new PerformanceObserver(t=>{let r=t.getEntries()[0];r&&e("FCP",r.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let r=t.getEntries(),n=r[r.length-1];n&&e("LCP",n.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let t=0;if(new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(t+=n.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let r=()=>{t>0&&e("CLS",Math.round(t*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&r();});}}catch{}try{new PerformanceObserver(t=>{for(let r of t.getEntries()){let n=r;n.responseStart&&n.responseStart>0&&e("TTFB",n.responseStart);let s=l=>l&&Number.isFinite(l)&&l>0?l:0,o=s(n.domainLookupEnd)-s(n.domainLookupStart);o>0&&this.captureVital("dns",o);let d=s(n.connectEnd)-s(n.connectStart);d>0&&this.captureVital("tcp",d);let a=s(n.responseEnd)-s(n.responseStart);a>0&&this.captureVital("download",a);let u=s(n.domComplete)-s(n.responseEnd);u>0&&this.captureVital("dom_processing",u);let c=s(n.loadEventEnd)-s(n.fetchStart);c>0&&this.captureVital("page_load",c);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let t=performance.getEntriesByType?.("navigation")?.[0];t?.responseStart&&e("TTFB",t.responseStart);let r=u=>u&&Number.isFinite(u)&&u>0?u:0,n=r(t?.domainLookupEnd)-r(t?.domainLookupStart);n>0&&this.captureVital("dns",n);let s=r(t?.connectEnd)-r(t?.connectStart);s>0&&this.captureVital("tcp",s);let o=r(t?.responseEnd)-r(t?.responseStart);o>0&&this.captureVital("download",o);let d=r(t?.domComplete)-r(t?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=r(t?.loadEventEnd)-r(t?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(t=>{for(let r of t.getEntries()){let n=r.duration;n>0&&e("INP",n);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let e=(t="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,t));};if(typeof history<"u"){let t=history.pushState,r=history.replaceState;history.pushState=function(...n){t.apply(this,n),e("push");},history.replaceState=function(...n){r.apply(this,n),e("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>e("popstate"));}startNavTransaction(e,t){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:e,attributes:{"navigation.type":t,"http.url":typeof location<"u"?location.href:e}});let r=this.navTransaction;setTimeout(()=>{this.navTransaction===r&&(r.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let e=globalThis;typeof e.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=t=>{let r=t,n=r.error??new Error(r.message??"Uncaught error");try{this.captureException(n,{tags:{source:"window.onerror"},extra:r.filename?{filename:r.filename,lineno:r.lineno,colno:r.colno}:void 0});}catch{}},this.rejectionHandler=t=>{let n=t.reason,s=n;if(!(n instanceof Error)){let o;if(typeof n=="string")o=n;else try{o=JSON.stringify(n);}catch{o=String(n);}s=new Error(o);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},e.addEventListener("error",this.errorHandler),e.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let e=globalThis;typeof e.removeEventListener=="function"&&(this.errorHandler&&(e.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(e.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let e=globalThis;if(this.originalFetch)return;this.originalFetch=e.fetch;let t=e.fetch.bind(globalThis),r=this;e.fetch=function(s,o){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let l=s;d=l.url??"",a=l.method??a;}let u=o??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(r.endpoint))return t(s,u);let c=r.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:r.navTransaction??void 0});try{let l=`00-${c.trace_id}-${c.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:l},t(s,f).then(h=>{let p=h;return typeof p.status=="number"&&c.setAttribute("http.status_code",p.status),c.setStatus(p.ok===!1?"error":"ok"),c.finish(),h}).catch(h=>{throw c.setStatus("error"),c.setAttribute("error.message",h instanceof Error?h.message:String(h)),c.finish(),h})}catch(l){throw c.setStatus("error"),c.finish(),l}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let t=globalThis.XMLHttpRequest;if(!t||!t.prototype)return;let r=Symbol.for("goodlogs.xhr.patched"),n=t.prototype;if(n[r]){this.xhrPatched=true;return}let s=n.open,o=n.setRequestHeader,d=n.send,a=this;n.open=function(c,l,...f){return this.__gl_method=typeof c=="string"?c.toUpperCase():"GET",this.__gl_url=typeof l=="string"?l:String(l??""),this.__gl_headers_set=false,s.apply(this,[c,l,...f])},n.setRequestHeader=function(c,l){return this.__gl_headers_set=true,o.apply(this,[c,l])},n.send=function(c){let l=this.__gl_url||"",f=this.__gl_method||"GET";if(l.startsWith(a.endpoint))return d.apply(this,[c]);let g=a.startSpan({op:"http.client",name:`${f} ${l}`,attributes:{"http.method":f,"http.url":l},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;o.apply(this,["traceparent",m]);}catch{}let h=(m,_,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(_?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[c])},n[r]=true,n.__gl_orig_open=s,n.__gl_orig_set_header=o,n.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let t=globalThis.XMLHttpRequest?.prototype;if(!t)return;let r=Symbol.for("goodlogs.xhr.patched");t.__gl_orig_open&&(t.open=t.__gl_orig_open),t.__gl_orig_set_header&&(t.setRequestHeader=t.__gl_orig_set_header),t.__gl_orig_send&&(t.send=t.__gl_orig_send),delete t.__gl_orig_open,delete t.__gl_orig_set_header,delete t.__gl_orig_send,delete t[r],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let r=e.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!r)return;let n=r.getAttribute?.("data-gl-event"),s=r.tagName?.toLowerCase()??"",o=(r.textContent??"").trim().slice(0,50),d=r.getAttribute?.("href")??void 0,a=(r.className??"").toString().slice(0,80);this.track(n||"$click",{properties:{$element_tag:s,$element_text:o||void 0,$element_href:d,$element_classes:a||void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:r,body:JSON.stringify({batch:e.map(n=>({severity:n.severity,message:n.message,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:r,body:JSON.stringify({batch:t.map(n=>({event:n.event,distinctId:n.distinctId,properties:n.properties,timestamp:n.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,r){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...r,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var I=R;var L=class{constructor(e){if(!e.apiKey)throw new Error("apiKey is required");if(!e.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint),this.timeout=e.timeout??3e4,this.alerts=new $(this),this.slos=new P(this),this.ai=new A(this);}async _request(e,t,r){let n=`${this.endpoint}${t}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(n,{method:e,headers:s,body:r?JSON.stringify(r):void 0,signal:o.signal});if(!a.ok){let u=await a.json().catch(()=>({})),c=u?.error?.message??`API error ${a.status}`;throw new T(a.status,c,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(e){return this._request("GET",e)}_post(e,t){return this._request("POST",e,t)}_put(e,t){return this._request("PUT",e,t)}_delete(e){return this._request("DELETE",e)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(e){return this._post("/v1/gql/query",{q:e})}gqlBatch(e){return this._post("/v1/gql",{queries:e})}gqlAutocomplete(e,t){let r=`/v1/gql/autocomplete?q=${encodeURIComponent(e)}`;return t!==void 0&&(r+=`&cursor=${t}`),this._get(r)}nl2gql(e,t){return this._post("/v1/gql/nl",{prompt:e,mode:t})}},$=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/alerts")}create(e){return this.client._post("/v1/alerts",e)}update(e,t){return this.client._put(`/v1/alerts/${e}`,t)}delete(e){return this.client._delete(`/v1/alerts/${e}`)}mute(e,t){return this.client._post(`/v1/alerts/${e}/mute`,{minutes:t})}},P=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/slos")}create(e){return this.client._post("/v1/slos",e)}update(e,t){return this.client._put(`/v1/slos/${e}`,t)}delete(e){return this.client._delete(`/v1/slos/${e}`)}},A=class{constructor(e){this.client=e;}chat(e,t){return this.client._post("/v1/ai/chat",{message:e,session_id:t})}},T=class extends Error{constructor(t,r,n){super(r);this.status=t;this.code=n;this.name="GoodLogsApiError";}};var q="0.1.0";function Q(i,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),r={"Content-Type":"application/json","X-GoodLogs-SDK":q};e?.token&&(r.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:r,body:JSON.stringify({source:i.source,event:i.event,level:i.level??"info",metadata:{...i.metadata,sdk_version:q}}),keepalive:true}).catch(()=>{});}function C(i){if(!i)return null;let e=i.trim().split("-");if(e.length!==4)return null;let[t,r,n,s]=e;return t.length!==2||r.length!==32||n.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(r)||!/^[0-9a-f]+$/.test(n)?null:{trace_id:r,parent_span_id:n}}function N(i,e){if(!i)return;let t=i[e]??i[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function Z(i){return function(t,r,n){let s=(t.method??"GET").toUpperCase(),o=t.originalUrl??t.url??"",d=C(N(t.headers,"traceparent")),a=i.startTransaction({op:"http.server",name:`${s} ${o}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":o}}),u=false,c=()=>{if(u)return;u=true;let l=t.route?.path;l&&a.setAttribute("http.route",l);let f=r.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};r.on("finish",c),r.on("close",c),t.goodlogs={span:a},n();}}function ee(i){return function(t,r,n){t.addHook("onRequest",(s,o,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",c=C(N(s.headers,"traceparent")),l=i.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:c?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=l,d();}),t.addHook("onResponse",(s,o,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let c=o.statusCode??o.raw?.statusCode??200;a.setAttribute("http.status_code",c),a.setStatus(c>=500?"error":"ok"),a.finish();}d();}),n();}}function te(i){return {intercept(e,t){let r=e.switchToHttp(),n=r.getRequest(),s=r.getResponse(),o=(n.method??"GET").toUpperCase(),d=n.originalUrl??n.url??"",a=C(N(n.headers,"traceparent")),u=i.startTransaction({op:"http.server",name:`${o} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":o,"http.url":d}}),c=false,l=(g,h)=>{if(c)return;c=true;let p=n.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>l()),s.on("close",()=>l());let f=t.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),l(500,true);},complete:()=>l()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function ne(i){let e=globalThis.process;if(!e||typeof e.on!="function")return;let t=e,r=Symbol.for("goodlogs.node-process.patched");t[r]||(e.on("uncaughtException",n=>{try{i.captureException(n instanceof Error?n:new Error(String(n)),{tags:{source:"uncaughtException"},level:"fatal"}),i.flush();}catch{}}),e.on("unhandledRejection",n=>{try{let s=n instanceof Error?n:new Error(typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[r]=true);}var H=globalThis.URL;function E(i){return !!H&&i instanceof H}var j=Symbol.for("goodlogs.node-http.patched");function re(...i){let e=i[0],t=i[1],r="GET",n="";if(typeof e=="string")n=e,t&&typeof t=="object"&&!E(t)&&(r=String(t.method??r).toUpperCase());else if(E(e))n=e.toString(),t&&typeof t=="object"&&!E(t)&&(r=String(t.method??r).toUpperCase());else if(e&&typeof e=="object"){let o=e;r=String(o.method??r).toUpperCase();let d=(o.protocol??"http:").replace(":",""),a=o.hostname??o.host??"localhost",u=o.port?`:${o.port}`:"";n=`${d}://${a}${u}${o.path??"/"}`;}return {method:r,url:n,isOurs:o=>!!o&&n.startsWith(o)}}function se(i,e,t){let r=i[0]&&typeof i[0]=="object"&&!E(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!E(i[1])?i[1]:void 0;r&&(r.headers||(r.headers={}),!(e in r.headers)&&!(e.toLowerCase()in r.headers)&&(r.headers[e]=t));}function oe(i,e){let t=e?.endpoint??i.endpoint??"",r=n=>{let s=n;if(s[j])return;s[j]=true;let o=n.request.bind(n);n.request=function(...a){let{method:u,url:c,isOurs:l}=re(...a);if(!c||l(t))return o(...a);let f=i.startTransaction({op:"http.client",name:`${u} ${c}`,attributes:{"http.method":u,"http.url":c}});se(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,_)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),_?(f.setAttribute("error.message",_.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=o(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let n=S("http");r(n);}catch{}try{let n=S("https");r(n);}catch{}}}
|
|
7
|
-
export{
|
|
5
|
+
[truncated \u2014 original ${t.length} chars, limit ${r}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${r} chars`)));let i=K(),d={severity:e,message:s,properties:{...this.defaultContext,...D(this.sessionId,this.anonymousId,this.release,this.environment,this.userProperties),...i?{code_location:i}:{},...n},timestamp:new Date().toISOString()};this.logBuffer.push(d),this.logBuffer.length>=this.batchSize&&this.flush();}debug(e,t){this.log("debug",e,t);}info(e,t){this.log("info",e,t);}warn(e,t){this.log("warn",e,t);}error(e,t){this.log("error",e,t);}fatal(e,t){this.log("fatal",e,t);}identify(e){this.anonymousId=e,typeof localStorage<"u"&&localStorage.setItem(w,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(w,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(_,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(_,this.sessionId),this._debug&&this._log("newSession",{sessionId:this.sessionId});}_log(e,t){if(!this._debug||typeof console>"u")return;let n=new Date().toISOString().slice(11,23);t?console.log(`%c[GL ${n}]%c ${e}`,"color:#10b981;font-weight:bold","color:inherit",t):console.log(`%c[GL ${n}]%c ${e}`,"color:#10b981;font-weight:bold","color:inherit");}setSessionId(e){this.sessionId=e,typeof sessionStorage<"u"&&sessionStorage.setItem(_,e);}setRelease(e){this.release=e;}getRelease(){return this.release}setEnvironment(e){this.environment=e;}getEnvironment(){return this.environment}setUser(e){this.identify(e.id),this.userProperties={...e};}getUser(){return {...this.userProperties}}track(e,t){if(this.disabled)return;let{distinctId:n,...r}=t??{},s={event:e,distinctId:n??this.anonymousId,properties:{...U(),...r,$session_id:this.sessionId,...this.release?{$release:this.release}:{},$environment:this.environment},timestamp:new Date().toISOString()};this.eventBuffer.push(s),this._debug&&this._log("track",{event:e,sessionId:this.sessionId}),this.eventBuffer.length>=this.batchSize&&this.flush();}addBreadcrumb(e){if(this.disabled)return;let t={ts:e.ts??new Date().toISOString(),...e};this.breadcrumbBuffer.push(t),this.breadcrumbBuffer.length>R.MAX_BREADCRUMBS&&this.breadcrumbBuffer.shift();}captureException(e,t){if(this.disabled)return;let n=this.buildErrorEntry(e,t);this._debug&&this._log("captureException",{message:n.message,type:n.exception_type,sessionId:this.sessionId,traceId:n.trace_id}),this.useEnvelope?(this.errorBuffer.push(n),this.errorBuffer.length>=this.batchSize&&this.flush()):this.error(n.message,{exception_type:n.exception_type,frames:n.frames});}captureMessage(e,t){if(this.disabled)return;let n={level:t?.level??"info",message:e,platform:typeof document<"u"?"browser":"node",frames:[],breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:t?.fingerprint,tags:{session_id:this.sessionId,...t?.tags},extra:t?.extra,user_id:t?.user_id??this.anonymousId,timestamp:new Date().toISOString()};this.useEnvelope?(this.errorBuffer.push(n),this.errorBuffer.length>=this.batchSize&&this.flush()):this.warn(e);}buildErrorEntry(e,t){let n,r,s=[];if(e instanceof Error)n=e.name,r=e.message,s=Q(e.stack);else if(typeof e=="string")r=e;else try{r=JSON.stringify(e);}catch{r=String(e);}return {level:t?.level??"error",platform:typeof document<"u"?"browser":"node",exception_type:n,message:r,frames:s,breadcrumbs:this.breadcrumbBuffer.slice(),fingerprint:t?.fingerprint,tags:{session_id:this.sessionId,...t?.tags},extra:t?.extra,user_id:t?.user_id??this.anonymousId,timestamp:new Date().toISOString(),trace_id:this.navTransaction?.trace_id,span_id:this.navTransaction?.span_id,release:this.release??void 0,environment:this.environment}}captureVital(e,t,n){if(this.disabled||!Number.isFinite(t)||t<0)return;let r=n?.rating??Y(e,t),s={metric:e,value_ms:e==="cls"?t:Math.round(t),rating:r,route:n?.route??(typeof location<"u"?location.pathname:void 0),page_url:typeof location<"u"?location.href:void 0,session_id:this.sessionId,user_id:this.anonymousId,attributes:n?.attributes,timestamp:new Date().toISOString()};this.useEnvelope?(this.vitalBuffer.push(s),this.vitalBuffer.length>=this.batchSize&&this.flush()):this.track("$web_vital",{properties:{$metric:e.toUpperCase(),$value_ms:s.value_ms,$rating:r}});}startTransaction(e){return this.makeSpan(void 0,e)}startSpan(e){return this.makeSpan(void 0,e)}makeSpan(e,t){let n=t?.trace_id??t?.parent?.trace_id??e?.trace_id??W(),r=J(),s=t?.parent?.span_id??e?.span_id,i=Date.now(),d=new Date(i).toISOString(),a={...t?.attributes??{}},u="unset",l=[],c=false,f=this,g={span_id:r,trace_id:n,setAttribute(h,p){a[h]=p;},setStatus(h){u=h;},addEvent(h,p){l.push({ts:new Date().toISOString(),name:h,attributes:p});},startChild(h){return f.makeSpan(g,h)},finish(){if(c)return;c=true;let h=Date.now(),p={span_id:r,trace_id:n,parent_span_id:s,name:t?.name,op:t?.op,status:u==="unset"?"ok":u,kind:t?.kind,attributes:a,events:l,start_time:d,end_time:new Date(h).toISOString(),timestamp:d,duration_ms:h-i};f.useEnvelope&&(f.spanBuffer.push(p),f.spanBuffer.length>=f.batchSize&&f.flush());}};return g}async flush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n=this.errorBuffer.splice(0),r=this.vitalBuffer.splice(0),s=this.spanBuffer.splice(0);this._debug&&(e.length||t.length||n.length||r.length||s.length)&&this._log("flush",{logs:e.length,events:t.length,errors:n.length,vitals:r.length,spans:s.length});let i=[];this.useEnvelope?(e.length>0||t.length>0||n.length>0||r.length>0||s.length>0)&&i.push(this.sendEnvelope(e,t,n,r,s)):(e.length>0&&i.push(this.sendLogs(e)),t.length>0&&i.push(this.sendEvents(t))),await Promise.all(i);}async shutdown(){this.stopTimer(),this.detachPageLifecycle(),this.detachClickCapture(),this.detachFetchInstrumentation(),this.detachXhrInstrumentation(),this.detachGlobalErrorHandlers(),this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),await this.flush();}async sendLogs(e){for(let n=0;n<e.length;n+=500){let s=e.slice(n,n+500).map(i=>({severity:i.severity,message:i.message,properties:i.properties,timestamp:i.timestamp}));await this.postWithRetry("/v1/logs",s,i=>{for(let d of i)this.logBuffer.push({severity:d.severity,message:d.message,properties:d.properties,timestamp:d.timestamp});});}}async sendEvents(e){for(let n=0;n<e.length;n+=500){let s=e.slice(n,n+500).map(i=>({event:i.event,distinctId:i.distinctId,properties:i.properties,timestamp:i.timestamp}));await this.postWithRetry("/v1/events",s,i=>{for(let d of i)this.eventBuffer.push({event:d.event,distinctId:d.distinctId,properties:d.properties,timestamp:d.timestamp});});}}async sendEnvelope(e,t,n,r,s){let d=[...e.map(a=>({kind:"log",entry:a})),...t.map(a=>({kind:"event",entry:a})),...n.map(a=>({kind:"error",entry:a})),...r.map(a=>({kind:"vital",entry:a})),...s.map(a=>({kind:"span",entry:a}))];for(let a=0;a<d.length;a+=1e3){let u=d.slice(a,a+1e3),l=JSON.stringify({v:1,sdk:`js@${v}`,sent_at:new Date().toISOString()}),c=u.map(g=>{if(g.kind==="log"){let p=g.entry;return JSON.stringify({type:"log",severity:p.severity,message:p.message,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="event"){let p=g.entry;return JSON.stringify({type:"event",event:p.event,distinctId:p.distinctId,properties:p.properties,timestamp:p.timestamp})}if(g.kind==="error"){let p=g.entry;return JSON.stringify({type:"error",...p})}if(g.kind==="vital"){let p=g.entry;return JSON.stringify({type:"vital",...p})}let h=g.entry;return JSON.stringify({type:"span",...h})}),f=[l,...c].join(`
|
|
6
|
+
`);await this.postEnvelopeWithRetry(f,u);}}async postEnvelopeWithRetry(e,t,n=0){try{let r=await fetch(`${this.endpoint}/v1/envelope`,{method:"POST",headers:{"Content-Type":"application/x-goodlogs-envelope+ndjson",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:e});if(r.status===429||r.status===503){if(n<4){let s=Math.min(1e3*Math.pow(2,n),8e3),i=Math.random()*500;return await new Promise(d=>setTimeout(d,s+i)),this.postEnvelopeWithRetry(e,t,n+1)}this.onError(new Error(`GoodLogs rate limited after ${n} retries`));return}if(!r.ok){let s=await r.text().catch(()=>"");if(this.onError(new Error(`GoodLogs envelope error ${r.status}: ${s}`)),r.status>=500&&n===0)for(let i of t)i.kind==="log"?this.logBuffer.push(i.entry):i.kind==="event"?this.eventBuffer.push(i.entry):i.kind==="error"?this.errorBuffer.push(i.entry):i.kind==="vital"?this.vitalBuffer.push(i.entry):this.spanBuffer.push(i.entry);}}catch(r){if(n===0)for(let s of t)s.kind==="log"?this.logBuffer.push(s.entry):s.kind==="event"?this.eventBuffer.push(s.entry):s.kind==="error"?this.errorBuffer.push(s.entry):s.kind==="vital"?this.vitalBuffer.push(s.entry):this.spanBuffer.push(s.entry);this.onError(r instanceof Error?r:new Error(String(r)));}}async postWithRetry(e,t,n,r=0){try{let s=await fetch(`${this.endpoint}${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({batch:t})});if(s.status===429||s.status===503){if(r<4){let d=Math.min(1e3*Math.pow(2,r),8e3),a=Math.random()*500;return await new Promise(u=>setTimeout(u,d+a)),this.postWithRetry(e,t,n,r+1)}this.onError(new Error(`GoodLogs rate limited after ${r} retries`));return}if(!s.ok){let d=await s.text().catch(()=>""),a=new Error(`GoodLogs API error ${s.status}: ${d}`);this.onError(a),s.status>=500&&r===0&&n(t);return}let i=await s.json().catch(()=>null);if(i&&i.rejected&&i.rejected>0){let d=t.slice(i.accepted??0);d.length>0&&n(d);}}catch(s){let i=s instanceof Error?s:new Error(String(s));r===0&&n(t),this.onError(i);}}startTimer(){this.timer=setInterval(()=>{this.flush();},this.flushInterval);let e=this.timer;typeof e?.unref=="function"&&e.unref();}stopTimer(){this.timer!==null&&(clearInterval(this.timer),this.timer=null);}attachPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush();},document.addEventListener("visibilitychange",this.visibilityHandler));}captureWebVitals(){if(typeof PerformanceObserver>"u")return;let e=(t,n)=>{if(this.useEnvelope)this.captureVital(t.toLowerCase(),n);else {let r=t==="CLS"?"$value":"$value_ms";this.track("$web_vital",{properties:{$metric:t,[r]:t==="CLS"?n:Math.round(n)}});}};try{new PerformanceObserver(t=>{let n=t.getEntries()[0];n&&e("FCP",n.startTime);}).observe({type:"paint",buffered:!0});}catch{}try{new PerformanceObserver(t=>{let n=t.getEntries(),r=n[n.length-1];r&&e("LCP",r.startTime);}).observe({type:"largest-contentful-paint",buffered:!0});}catch{}try{let t=0;if(new PerformanceObserver(n=>{for(let r of n.getEntries())r.hadRecentInput||(t+=r.value);}).observe({type:"layout-shift",buffered:!0}),typeof document<"u"){let n=()=>{t>0&&e("CLS",Math.round(t*1e3)/1e3);};document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&n();});}}catch{}try{new PerformanceObserver(t=>{for(let n of t.getEntries()){let r=n;r.responseStart&&r.responseStart>0&&e("TTFB",r.responseStart);let s=c=>c&&Number.isFinite(c)&&c>0?c:0,i=s(r.domainLookupEnd)-s(r.domainLookupStart);i>0&&this.captureVital("dns",i);let d=s(r.connectEnd)-s(r.connectStart);d>0&&this.captureVital("tcp",d);let a=s(r.responseEnd)-s(r.responseStart);a>0&&this.captureVital("download",a);let u=s(r.domComplete)-s(r.responseEnd);u>0&&this.captureVital("dom_processing",u);let l=s(r.loadEventEnd)-s(r.fetchStart);l>0&&this.captureVital("page_load",l);}}).observe({type:"navigation",buffered:!0});}catch{try{if(typeof performance<"u"){let t=performance.getEntriesByType?.("navigation")?.[0];t?.responseStart&&e("TTFB",t.responseStart);let n=u=>u&&Number.isFinite(u)&&u>0?u:0,r=n(t?.domainLookupEnd)-n(t?.domainLookupStart);r>0&&this.captureVital("dns",r);let s=n(t?.connectEnd)-n(t?.connectStart);s>0&&this.captureVital("tcp",s);let i=n(t?.responseEnd)-n(t?.responseStart);i>0&&this.captureVital("download",i);let d=n(t?.domComplete)-n(t?.responseEnd);d>0&&this.captureVital("dom_processing",d);let a=n(t?.loadEventEnd)-n(t?.fetchStart);a>0&&this.captureVital("page_load",a);}}catch{}}try{new PerformanceObserver(t=>{for(let n of t.getEntries()){let r=n.duration;r>0&&e("INP",r);}}).observe({type:"event",buffered:!0});}catch{}}attachPageviewCapture(){if(typeof document>"u"||typeof location>"u")return;this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,"initial");let e=(t="push")=>{typeof location<"u"&&location.pathname!==this.lastPath&&(this.lastPath=location.pathname,this.track("$pageview"),this.startNavTransaction(this.lastPath,t));};if(typeof history<"u"){let t=history.pushState,n=history.replaceState;history.pushState=function(...r){t.apply(this,r),e("push");},history.replaceState=function(...r){n.apply(this,r),e("replace");};}typeof addEventListener<"u"&&addEventListener("popstate",()=>e("popstate"));}startNavTransaction(e,t){try{this.navTransaction&&(this.navTransaction.finish(),this.navTransaction=null),this.navTransaction=this.startTransaction({op:"navigation",name:e,attributes:{"navigation.type":t,"http.url":typeof location<"u"?location.href:e}});let n=this.navTransaction;setTimeout(()=>{this.navTransaction===n&&(n.finish(),this.navTransaction=null);},3e4);}catch{}}attachGlobalErrorHandlers(){let e=globalThis;typeof e.addEventListener=="function"&&(this.errorHandler||this.rejectionHandler||(this.errorHandler=t=>{let n=t,r=n.error??new Error(n.message??"Uncaught error");try{this.captureException(r,{tags:{source:"window.onerror"},extra:n.filename?{filename:n.filename,lineno:n.lineno,colno:n.colno}:void 0});}catch{}},this.rejectionHandler=t=>{let r=t.reason,s=r;if(!(r instanceof Error)){let i;if(typeof r=="string")i=r;else try{i=JSON.stringify(r);}catch{i=String(r);}s=new Error(i);}try{this.captureException(s,{tags:{source:"unhandledrejection"}});}catch{}},e.addEventListener("error",this.errorHandler),e.addEventListener("unhandledrejection",this.rejectionHandler)));}detachGlobalErrorHandlers(){let e=globalThis;typeof e.removeEventListener=="function"&&(this.errorHandler&&(e.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(e.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null));}attachFetchInstrumentation(){if(typeof fetch>"u")return;let e=globalThis;if(this.originalFetch)return;this.originalFetch=e.fetch;let t=e.fetch.bind(globalThis),n=this;e.fetch=function(s,i){let d="",a="GET";if(typeof s=="string")d=s;else if(s&&typeof s=="object"){let c=s;d=c.url??"",a=c.method??a;}let u=i??{};if(u.method?a=String(u.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(n.endpoint))return t(s,u);let l=n.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:n.navTransaction??void 0});try{let c=`00-${l.trace_id}-${l.span_id}-01`,f={...u},g=f.headers??{};return f.headers={...g,traceparent:c},t(s,f).then(h=>{let p=h;return typeof p.status=="number"&&l.setAttribute("http.status_code",p.status),l.setStatus(p.ok===!1?"error":"ok"),l.finish(),h}).catch(h=>{throw l.setStatus("error"),l.setAttribute("error.message",h instanceof Error?h.message:String(h)),l.finish(),h})}catch(c){throw l.setStatus("error"),l.finish(),c}};}detachFetchInstrumentation(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null);}attachXhrInstrumentation(){let t=globalThis.XMLHttpRequest;if(!t||!t.prototype)return;let n=Symbol.for("goodlogs.xhr.patched"),r=t.prototype;if(r[n]){this.xhrPatched=true;return}let s=r.open,i=r.setRequestHeader,d=r.send,a=this;r.open=function(l,c,...f){return this.__gl_method=typeof l=="string"?l.toUpperCase():"GET",this.__gl_url=typeof c=="string"?c:String(c??""),this.__gl_headers_set=false,s.apply(this,[l,c,...f])},r.setRequestHeader=function(l,c){return this.__gl_headers_set=true,i.apply(this,[l,c])},r.send=function(l){let c=this.__gl_url||"",f=this.__gl_method||"GET";if(c.startsWith(a.endpoint))return d.apply(this,[l]);let g=a.startSpan({op:"http.client",name:`${f} ${c}`,attributes:{"http.method":f,"http.url":c},parent:a.navTransaction??void 0});try{let m=`00-${g.trace_id}-${g.span_id}-01`;i.apply(this,["traceparent",m]);}catch{}let h=(m,E,O)=>{m&&g.setAttribute("http.status_code",m),O&&g.setAttribute("error.message",O),g.setStatus(E?"ok":"error"),g.finish();},p=this.addEventListener;return typeof p=="function"?(p.call(this,"load",()=>{let m=Number(this.status||0);h(m,m>0&&m<500);}),p.call(this,"error",()=>h(0,false,"network error")),p.call(this,"abort",()=>h(0,false,"aborted")),p.call(this,"timeout",()=>h(0,false,"timeout"))):h(0,true),d.apply(this,[l])},r[n]=true,r.__gl_orig_open=s,r.__gl_orig_set_header=i,r.__gl_orig_send=d,this.xhrPatched=true;}detachXhrInstrumentation(){if(!this.xhrPatched)return;let t=globalThis.XMLHttpRequest?.prototype;if(!t)return;let n=Symbol.for("goodlogs.xhr.patched");t.__gl_orig_open&&(t.open=t.__gl_orig_open),t.__gl_orig_set_header&&(t.setRequestHeader=t.__gl_orig_set_header),t.__gl_orig_send&&(t.send=t.__gl_orig_send),delete t.__gl_orig_open,delete t.__gl_orig_set_header,delete t.__gl_orig_send,delete t[n],this.xhrPatched=false;}attachClickCapture(){typeof document>"u"||(this.clickHandler=e=>{let t=e,n=t.target?.closest?.("a, button, [data-gl-event], [role='button']");if(!n)return;let r=n.getAttribute?.("data-gl-event"),s=n.tagName?.toLowerCase()??"",i=(n.textContent??"").trim().slice(0,50),d=n.getAttribute?.("href")??void 0,a=(n.className??"").toString().slice(0,80),u=globalThis,l=u.innerWidth,c=u.innerHeight,f=u.scrollY,g=typeof document<"u"?document.documentElement?.scrollHeight:void 0;this.track(r||"$click",{properties:{$element_tag:s,$element_text:i||void 0,$element_href:d,$element_classes:a||void 0,$element_selector:X(n),$click_x:t.clientX,$click_y:t.clientY,$page_x:t.pageX,$page_y:t.pageY,$viewport_w:l,$viewport_h:c,$scroll_y:f,$doc_h:g,$url:typeof location<"u"?location.href:void 0,$pathname:typeof location<"u"?location.pathname:void 0}});},document.addEventListener("click",this.clickHandler));}detachClickCapture(){this.clickHandler&&typeof document<"u"&&(document.removeEventListener("click",this.clickHandler),this.clickHandler=null);}detachPageLifecycle(){this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null);}keepaliveFlush(){let e=this.logBuffer.splice(0),t=this.eventBuffer.splice(0),n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`};e.length>0&&fetch(`${this.endpoint}/v1/logs`,{method:"POST",headers:n,body:JSON.stringify({batch:e.map(r=>({severity:r.severity,message:r.message,properties:r.properties,timestamp:r.timestamp}))}),keepalive:true}).catch(()=>{}),t.length>0&&fetch(`${this.endpoint}/v1/events`,{method:"POST",headers:n,body:JSON.stringify({batch:t.map(r=>({event:r.event,distinctId:r.distinctId,properties:r.properties,timestamp:r.timestamp}))}),keepalive:true}).catch(()=>{});}sendTelemetry(e,t,n){!this.telemetry||this.disabled||fetch(`${this.endpoint}/v1/telemetry`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-GoodLogs-SDK":`js/${v}`},body:JSON.stringify({source:"sdk",event:e,level:t,metadata:{...n,sdk_version:v}}),keepalive:true}).catch(()=>{});}};R.MAX_BREADCRUMBS=50;var $=R;var x=class{constructor(e){if(!e.apiKey)throw new Error("apiKey is required");if(!e.apiKey.startsWith("gl_sk_"))throw new Error("GoodLogsClient requires a secret API key (gl_sk_...)");this.apiKey=e.apiKey,this.endpoint=y(e.apiKey,e.endpoint),this.timeout=e.timeout??3e4,this.alerts=new L(this),this.slos=new P(this),this.ai=new A(this);}async _request(e,t,n){let r=`${this.endpoint}${t}`,s={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},i=new AbortController,d=setTimeout(()=>i.abort(),this.timeout);try{let a=await fetch(r,{method:e,headers:s,body:n?JSON.stringify(n):void 0,signal:i.signal});if(!a.ok){let u=await a.json().catch(()=>({})),l=u?.error?.message??`API error ${a.status}`;throw new T(a.status,l,u?.error?.code)}return a.status===204?void 0:await a.json()}finally{clearTimeout(d);}}_get(e){return this._request("GET",e)}_post(e,t){return this._request("POST",e,t)}_put(e,t){return this._request("PUT",e,t)}_delete(e){return this._request("DELETE",e)}info(){return this._get("/v1/info")}schema(){return this._get("/v1/schema")}gql(e){return this._post("/v1/gql/query",{q:e})}gqlBatch(e){return this._post("/v1/gql",{queries:e})}gqlAutocomplete(e,t){let n=`/v1/gql/autocomplete?q=${encodeURIComponent(e)}`;return t!==void 0&&(n+=`&cursor=${t}`),this._get(n)}nl2gql(e,t){return this._post("/v1/gql/nl",{prompt:e,mode:t})}},L=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/alerts")}create(e){return this.client._post("/v1/alerts",e)}update(e,t){return this.client._put(`/v1/alerts/${e}`,t)}delete(e){return this.client._delete(`/v1/alerts/${e}`)}mute(e,t){return this.client._post(`/v1/alerts/${e}/mute`,{minutes:t})}},P=class{constructor(e){this.client=e;}list(){return this.client._get("/v1/slos")}create(e){return this.client._post("/v1/slos",e)}update(e,t){return this.client._put(`/v1/slos/${e}`,t)}delete(e){return this.client._delete(`/v1/slos/${e}`)}},A=class{constructor(e){this.client=e;}chat(e,t){return this.client._post("/v1/ai/chat",{message:e,session_id:t})}},T=class extends Error{constructor(t,n,r){super(n);this.status=t;this.code=r;this.name="GoodLogsApiError";}};var H="0.1.0";function Z(o,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":H};e?.token&&(n.Authorization=`Bearer ${e.token}`),fetch(`${t}/v1/telemetry`,{method:"POST",headers:n,body:JSON.stringify({source:o.source,event:o.event,level:o.level??"info",metadata:{...o.metadata,sdk_version:H}}),keepalive:true}).catch(()=>{});}function I(o){if(!o)return null;let e=o.trim().split("-");if(e.length!==4)return null;let[t,n,r,s]=e;return t.length!==2||n.length!==32||r.length!==16||s.length!==2||!/^[0-9a-f]+$/.test(n)||!/^[0-9a-f]+$/.test(r)?null:{trace_id:n,parent_span_id:r}}function N(o,e){if(!o)return;let t=o[e]??o[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function ee(o){return function(t,n,r){let s=(t.method??"GET").toUpperCase(),i=t.originalUrl??t.url??"",d=I(N(t.headers,"traceparent")),a=o.startTransaction({op:"http.server",name:`${s} ${i}`,trace_id:d?.trace_id,attributes:{"http.method":s,"http.url":i}}),u=false,l=()=>{if(u)return;u=true;let c=t.route?.path;c&&a.setAttribute("http.route",c);let f=n.statusCode??200;a.setAttribute("http.status_code",f),a.setStatus(f>=500?"error":"ok"),a.finish();};n.on("finish",l),n.on("close",l),t.goodlogs={span:a},r();}}function te(o){return function(t,n,r){t.addHook("onRequest",(s,i,d)=>{let a=(s.method??"GET").toUpperCase(),u=s.url??"",l=I(N(s.headers,"traceparent")),c=o.startTransaction({op:"http.server",name:`${a} ${u}`,trace_id:l?.trace_id,attributes:{"http.method":a,"http.url":u}});s.__goodlogsSpan=c,d();}),t.addHook("onResponse",(s,i,d)=>{let a=s.__goodlogsSpan;if(a){let u=s.routerPath??s.routeOptions?.url;u&&a.setAttribute("http.route",u);let l=i.statusCode??i.raw?.statusCode??200;a.setAttribute("http.status_code",l),a.setStatus(l>=500?"error":"ok"),a.finish();}d();}),r();}}function ne(o){return {intercept(e,t){let n=e.switchToHttp(),r=n.getRequest(),s=n.getResponse(),i=(r.method??"GET").toUpperCase(),d=r.originalUrl??r.url??"",a=I(N(r.headers,"traceparent")),u=o.startTransaction({op:"http.server",name:`${i} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":i,"http.url":d}}),l=false,c=(g,h)=>{if(l)return;l=true;let p=r.route?.path;p&&u.setAttribute("http.route",p);let m=g??s.statusCode??200;u.setAttribute("http.status_code",m),u.setStatus(h||m>=500?"error":"ok"),u.finish();};s.on("finish",()=>c()),s.on("close",()=>c());let f=t.handle();if(f&&typeof f.subscribe=="function"){let g=f.subscribe({next:()=>{},error:h=>{u.setAttribute("error.message",h instanceof Error?h.message:String(h)),c(500,true);},complete:()=>c()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function re(o){let e=globalThis.process;if(!e||typeof e.on!="function")return;let t=e,n=Symbol.for("goodlogs.node-process.patched");t[n]||(e.on("uncaughtException",r=>{try{o.captureException(r instanceof Error?r:new Error(String(r)),{tags:{source:"uncaughtException"},level:"fatal"}),o.flush();}catch{}}),e.on("unhandledRejection",r=>{try{let s=r instanceof Error?r:new Error(typeof r=="string"?r:(()=>{try{return JSON.stringify(r)}catch{return String(r)}})());o.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[n]=true);}var q=globalThis.URL;function k(o){return !!q&&o instanceof q}var j=Symbol.for("goodlogs.node-http.patched");function se(...o){let e=o[0],t=o[1],n="GET",r="";if(typeof e=="string")r=e,t&&typeof t=="object"&&!k(t)&&(n=String(t.method??n).toUpperCase());else if(k(e))r=e.toString(),t&&typeof t=="object"&&!k(t)&&(n=String(t.method??n).toUpperCase());else if(e&&typeof e=="object"){let i=e;n=String(i.method??n).toUpperCase();let d=(i.protocol??"http:").replace(":",""),a=i.hostname??i.host??"localhost",u=i.port?`:${i.port}`:"";r=`${d}://${a}${u}${i.path??"/"}`;}return {method:n,url:r,isOurs:i=>!!i&&r.startsWith(i)}}function ie(o,e,t){let n=o[0]&&typeof o[0]=="object"&&!k(o[0])?o[0]:o[1]&&typeof o[1]=="object"&&!k(o[1])?o[1]:void 0;n&&(n.headers||(n.headers={}),!(e in n.headers)&&!(e.toLowerCase()in n.headers)&&(n.headers[e]=t));}function oe(o,e){let t=e?.endpoint??o.endpoint??"",n=r=>{let s=r;if(s[j])return;s[j]=true;let i=r.request.bind(r);r.request=function(...a){let{method:u,url:l,isOurs:c}=se(...a);if(!l||c(t))return i(...a);let f=o.startTransaction({op:"http.client",name:`${u} ${l}`,attributes:{"http.method":u,"http.url":l}});ie(a,"traceparent",`00-${f.trace_id}-${f.span_id}-01`);let g=false,h=(m,E)=>{g||(g=true,typeof m=="number"&&f.setAttribute("http.status_code",m),E?(f.setAttribute("error.message",E.message),f.setStatus("error")):f.setStatus(typeof m=="number"&&m>=500?"error":"ok"),f.finish());},p=i(...a);return p.on("response",m=>h(m.statusCode)),p.on("error",m=>h(void 0,m)),p.on("close",()=>h()),p};};if(typeof S=="function"){try{let r=S("http");n(r);}catch{}try{let r=S("https");n(r);}catch{}}}
|
|
7
|
+
export{$ as GoodLogs,T as GoodLogsApiError,x as GoodLogsClient,C as REGION_URLS,ee as goodlogsExpress,te as goodlogsFastify,ne as goodlogsNestInterceptor,oe as instrumentNodeHttp,re as instrumentNodeProcess,I as parseTraceparent,y as resolveEndpoint,B as resolveRegion,Z as sendTelemetry};
|
package/dist/memory.d.cts
CHANGED
package/dist/memory.d.ts
CHANGED
package/dist/profiling.d.cts
CHANGED
package/dist/profiling.d.ts
CHANGED
package/dist/react.d.cts
CHANGED
package/dist/react.d.ts
CHANGED
package/dist/replay.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var G=new Set([1,3,6]);function V(o){return o.every(n=>{if(n.type!==3)return false;let i=n.data?.source;return i!==void 0&&G.has(i)})}var y=null;async function W(o,n={}){if(typeof document>"u")return null;if(y)return y;let i=n.sampleRate??1;if(i<1&&Math.random()>i)return null;let u=n.rrwebRecord??await Q();if(!u)return null;let l=o.endpoint,f=o.apiKey,g=o,q=n.debug??g._debug??false,r=(e,t)=>{if(!q||typeof console>"u")return;let a=new Date().toISOString().slice(11,23);t?console.log(`%c[GL:replay ${a}]%c ${e}`,"color:#f59e0b;font-weight:bold","color:inherit",t):console.log(`%c[GL:replay ${a}]%c ${e}`,"color:#f59e0b;font-weight:bold","color:inherit");},D=n.flushIntervalMs??5e3,T=n.flushBytes??5e5,S=n.sessionTimeoutMs??1800*1e3,I=n.maxSessionMs??3600*1e3;r("config",{flushIntervalMs:D,flushBytes:T,sessionTimeoutMs:S/1e3+"s",maxSessionMs:I/1e3+"s"});let s=g.sessionId,d=[],b=0,M=0,k=false,w=false,c=Date.now(),m=Date.now(),x=null,O=()=>{r("session:announce",{sessionId:s,distinctId:g.getDistinctId()}),v(l,f,{session_id:s,distinct_id:g.getDistinctId(),started_at:new Date(m).toISOString(),start_url:typeof location<"u"?location.href:null,last_url:typeof location<"u"?location.href:null},n.onError);},B=()=>{let e=s;r("session:seal",{sessionId:e,queueSize:d.length}),p(true),v(l,f,{session_id:e,ended_at:new Date().toISOString()},n.onError);},p=async(e=false)=>{if(d.length===0)return;if(!e&&V(d)){d=[],b=0;return}let t=d,a=t[0].timestamp,R=t[t.length-1].timestamp,P=t.length,E=s;d=[],b=0;let z=M++;try{let h=JSON.stringify(t),K=await F(h);r("chunk:upload",{sessionId:E,seq:z,events:P,bytes:h.length,range:`${new Date(a).toISOString()} \u2192 ${new Date(R).toISOString()}`});let J=`${l}/v1/replay/chunks?session_id=${encodeURIComponent(E)}&seq=${z}&start_ts=${encodeURIComponent(new Date(a).toISOString())}&end_ts=${encodeURIComponent(new Date(R).toISOString())}&event_count=${P}`;await fetch(J,{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/gzip","Content-Encoding":"gzip"},body:K,keepalive:!0});}catch(h){n.onError?.(h);}v(l,f,{session_id:E,last_url:typeof location<"u"?location.href:null,last_activity_at:new Date(R).toISOString(),has_error:k||void 0},n.onError);},_=()=>{let e=Date.now()-m,t=Date.now()-c;r("session:rotate",{oldSessionId:s,elapsed:Math.round(e/1e3)+"s",idle:Math.round(t/1e3)+"s"}),B();try{x?.();}catch(a){n.onError?.(a);}g.newSession(),s=g.getSessionId(),M=0,k=false,c=Date.now(),m=Date.now(),O(),$();},$=()=>{x=u({emit:e=>{if(w)return;e.type===3&&G.has(e.data?.source??-1)||(c=Date.now()),d.push(e),b+=256,b>=T&&p();},checkoutEveryNms:6e4,maskAllInputs:n.maskAllInputs??true,blockSelector:n.blockSelector??"[data-gl-block]",maskTextSelector:n.maskTextSelector??"[data-gl-mask]",sampling:{mousemove:50,mouseInteraction:true,scroll:150,input:"last"}});},U=setInterval(()=>{globalThis.__gl_replay_has_error__&&(k=true);},1e3),H=()=>{if(!w){r("stop",{sessionId:s}),w=true,clearInterval(N),clearInterval(j),clearInterval(U),document?.removeEventListener("visibilitychange",C),typeof window<"u"&&window.removeEventListener("beforeunload",L);try{x?.();}catch(e){n.onError?.(e);}B(),y=null;}};r("start",{sessionId:s,sampleRate:i}),O(),$();let N=setInterval(()=>{p();},D),j=setInterval(()=>{if(w)return;let e=Date.now();if(e-c>S){r("watchdog:idle-timeout",{idle:Math.round((e-c)/1e3)+"s"}),_();return}if(e-m>I){r("watchdog:max-duration",{elapsed:Math.round((e-m)/1e3)+"s"}),_();return}},1e4),C=()=>{if(!w){if(document?.visibilityState==="hidden")r("visibility:hidden",{sessionId:s}),p(true),v(l,f,{session_id:s,ended_at:new Date().toISOString()},n.onError);else if(document?.visibilityState==="visible"){let e=Date.now(),t=e-c,a=e-m;r("visibility:visible",{idle:Math.round(t/1e3)+"s",elapsed:Math.round(a/1e3)+"s"}),t>S||a>I?_():c=e;}}};document.addEventListener("visibilitychange",C);let L=()=>{p(true),v(l,f,{session_id:s,ended_at:new Date().toISOString()},n.onError);};typeof window<"u"&&window.addEventListener("beforeunload",L);let A={get sessionId(){return s},flush:()=>p(true),stop:H};return y=A,A}async function v(o,n,i,u){try{await fetch(`${o}/v1/replay/sessions`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0});}catch(l){u?.(l);}}async function F(o){if(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u")return o;let i=new Blob([o]).stream().pipeThrough(new CompressionStream("gzip")),u=await new Response(i).arrayBuffer();return new Blob([u],{type:"application/gzip"})}async function Q(){try{let o=await import('rrweb');return o.record??o.default?.record??null}catch{return null}}exports.startReplay=W;
|
package/dist/replay.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { G as GoodLogs } from './client-
|
|
1
|
+
import { G as GoodLogs } from './client-CR9BnNN-.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Session Replay (rrweb) — optional, tree-split.
|
|
@@ -49,6 +49,8 @@ interface ReplayOptions {
|
|
|
49
49
|
/** Max session duration before rotation (default 60 min). */
|
|
50
50
|
maxSessionMs?: number;
|
|
51
51
|
onError?: (e: unknown) => void;
|
|
52
|
+
/** Enable verbose console logging for replay debugging. */
|
|
53
|
+
debug?: boolean;
|
|
52
54
|
}
|
|
53
55
|
interface ReplayHandle {
|
|
54
56
|
stop: () => void;
|
package/dist/replay.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { G as GoodLogs } from './client-
|
|
1
|
+
import { G as GoodLogs } from './client-CR9BnNN-.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Session Replay (rrweb) — optional, tree-split.
|
|
@@ -49,6 +49,8 @@ interface ReplayOptions {
|
|
|
49
49
|
/** Max session duration before rotation (default 60 min). */
|
|
50
50
|
maxSessionMs?: number;
|
|
51
51
|
onError?: (e: unknown) => void;
|
|
52
|
+
/** Enable verbose console logging for replay debugging. */
|
|
53
|
+
debug?: boolean;
|
|
52
54
|
}
|
|
53
55
|
interface ReplayHandle {
|
|
54
56
|
stop: () => void;
|
package/dist/replay.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var G=new Set([1,3,6]);function V(o){return o.every(n=>{if(n.type!==3)return false;let i=n.data?.source;return i!==void 0&&G.has(i)})}var y=null;async function W(o,n={}){if(typeof document>"u")return null;if(y)return y;let i=n.sampleRate??1;if(i<1&&Math.random()>i)return null;let u=n.rrwebRecord??await Q();if(!u)return null;let l=o.endpoint,f=o.apiKey,g=o,q=n.debug??g._debug??false,r=(e,t)=>{if(!q||typeof console>"u")return;let a=new Date().toISOString().slice(11,23);t?console.log(`%c[GL:replay ${a}]%c ${e}`,"color:#f59e0b;font-weight:bold","color:inherit",t):console.log(`%c[GL:replay ${a}]%c ${e}`,"color:#f59e0b;font-weight:bold","color:inherit");},D=n.flushIntervalMs??5e3,T=n.flushBytes??5e5,S=n.sessionTimeoutMs??1800*1e3,I=n.maxSessionMs??3600*1e3;r("config",{flushIntervalMs:D,flushBytes:T,sessionTimeoutMs:S/1e3+"s",maxSessionMs:I/1e3+"s"});let s=g.sessionId,d=[],b=0,M=0,k=false,w=false,c=Date.now(),m=Date.now(),x=null,O=()=>{r("session:announce",{sessionId:s,distinctId:g.getDistinctId()}),v(l,f,{session_id:s,distinct_id:g.getDistinctId(),started_at:new Date(m).toISOString(),start_url:typeof location<"u"?location.href:null,last_url:typeof location<"u"?location.href:null},n.onError);},B=()=>{let e=s;r("session:seal",{sessionId:e,queueSize:d.length}),p(true),v(l,f,{session_id:e,ended_at:new Date().toISOString()},n.onError);},p=async(e=false)=>{if(d.length===0)return;if(!e&&V(d)){d=[],b=0;return}let t=d,a=t[0].timestamp,R=t[t.length-1].timestamp,P=t.length,E=s;d=[],b=0;let z=M++;try{let h=JSON.stringify(t),K=await F(h);r("chunk:upload",{sessionId:E,seq:z,events:P,bytes:h.length,range:`${new Date(a).toISOString()} \u2192 ${new Date(R).toISOString()}`});let J=`${l}/v1/replay/chunks?session_id=${encodeURIComponent(E)}&seq=${z}&start_ts=${encodeURIComponent(new Date(a).toISOString())}&end_ts=${encodeURIComponent(new Date(R).toISOString())}&event_count=${P}`;await fetch(J,{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/gzip","Content-Encoding":"gzip"},body:K,keepalive:!0});}catch(h){n.onError?.(h);}v(l,f,{session_id:E,last_url:typeof location<"u"?location.href:null,last_activity_at:new Date(R).toISOString(),has_error:k||void 0},n.onError);},_=()=>{let e=Date.now()-m,t=Date.now()-c;r("session:rotate",{oldSessionId:s,elapsed:Math.round(e/1e3)+"s",idle:Math.round(t/1e3)+"s"}),B();try{x?.();}catch(a){n.onError?.(a);}g.newSession(),s=g.getSessionId(),M=0,k=false,c=Date.now(),m=Date.now(),O(),$();},$=()=>{x=u({emit:e=>{if(w)return;e.type===3&&G.has(e.data?.source??-1)||(c=Date.now()),d.push(e),b+=256,b>=T&&p();},checkoutEveryNms:6e4,maskAllInputs:n.maskAllInputs??true,blockSelector:n.blockSelector??"[data-gl-block]",maskTextSelector:n.maskTextSelector??"[data-gl-mask]",sampling:{mousemove:50,mouseInteraction:true,scroll:150,input:"last"}});},U=setInterval(()=>{globalThis.__gl_replay_has_error__&&(k=true);},1e3),H=()=>{if(!w){r("stop",{sessionId:s}),w=true,clearInterval(N),clearInterval(j),clearInterval(U),document?.removeEventListener("visibilitychange",C),typeof window<"u"&&window.removeEventListener("beforeunload",L);try{x?.();}catch(e){n.onError?.(e);}B(),y=null;}};r("start",{sessionId:s,sampleRate:i}),O(),$();let N=setInterval(()=>{p();},D),j=setInterval(()=>{if(w)return;let e=Date.now();if(e-c>S){r("watchdog:idle-timeout",{idle:Math.round((e-c)/1e3)+"s"}),_();return}if(e-m>I){r("watchdog:max-duration",{elapsed:Math.round((e-m)/1e3)+"s"}),_();return}},1e4),C=()=>{if(!w){if(document?.visibilityState==="hidden")r("visibility:hidden",{sessionId:s}),p(true),v(l,f,{session_id:s,ended_at:new Date().toISOString()},n.onError);else if(document?.visibilityState==="visible"){let e=Date.now(),t=e-c,a=e-m;r("visibility:visible",{idle:Math.round(t/1e3)+"s",elapsed:Math.round(a/1e3)+"s"}),t>S||a>I?_():c=e;}}};document.addEventListener("visibilitychange",C);let L=()=>{p(true),v(l,f,{session_id:s,ended_at:new Date().toISOString()},n.onError);};typeof window<"u"&&window.addEventListener("beforeunload",L);let A={get sessionId(){return s},flush:()=>p(true),stop:H};return y=A,A}async function v(o,n,i,u){try{await fetch(`${o}/v1/replay/sessions`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(i),keepalive:!0});}catch(l){u?.(l);}}async function F(o){if(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u")return o;let i=new Blob([o]).stream().pipeThrough(new CompressionStream("gzip")),u=await new Response(i).arrayBuffer();return new Blob([u],{type:"application/gzip"})}async function Q(){try{let o=await import('rrweb');return o.record??o.default?.record??null}catch{return null}}export{W as startReplay};
|