@aj-2000-test/goodlogs-sdk 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +3 -5
- package/dist/index.d.ts +3 -5
- package/dist/index.js +6 -6
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';var
|
|
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>",
|
|
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(),
|
|
1
|
+
'use strict';var w=(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')});function B(o){let e=o.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function j(o,e){return o==="eu"&&(!e||e==="production")?"https://api.goodlogs.dev":o==="eu"?`https://api-${e}.goodlogs.dev`:!e||e==="production"?`https://api-${o}.goodlogs.dev`:`https://api-${o}-${e}.goodlogs.dev`}function y(o,e,t){if(e)return e;let n=B(o);return j(n,t)}var G=5e3,F=50,v="0.5.4",S="gl_anon_id",k="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 M(){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 U(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=U(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(S);if(o)return o;let e=b();return localStorage.setItem(S,e),e}return b()}function W(){if(typeof sessionStorage<"u"){let o=sessionStorage.getItem(k);if(o)return o;let e=b();return sessionStorage.setItem(k,e),e}return b()}function J(){let o="";for(let e=0;e<32;e++)o+=(Math.random()*16|0).toString(16);return o}function z(){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.beforeSend=null;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,e.environment).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.beforeSend=e.beforeSend??null,this.anonymousId=V(),this.sessionId=W(),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.attachAutoBreadcrumbs()),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 ${r}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${r} chars`)));let
|
|
6
|
-
`);await this.postEnvelopeWithRetry(f,l);}}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),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),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 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(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(l=>setTimeout(l,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 o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=t.slice(o.accepted??0);d.length>0&&n(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));r===0&&n(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,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,o=s(r.domainLookupEnd)-s(r.domainLookupStart);o>0&&this.captureVital("dns",o);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 l=s(r.domComplete)-s(r.responseEnd);l>0&&this.captureVital("dom_processing",l);let u=s(r.loadEventEnd)-s(r.fetchStart);u>0&&this.captureVital("page_load",u);}}).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=l=>l&&Number.isFinite(l)&&l>0?l: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 o=n(t?.responseEnd)-n(t?.responseStart);o>0&&this.captureVital("download",o);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 o;if(typeof r=="string")o=r;else try{o=JSON.stringify(r);}catch{o=String(r);}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));}attachAutoBreadcrumbs(){if(typeof console<"u"){let e=this,t=["error","warn","info","log"];for(let n of t){let r=console[n];r&&(console[n]=function(...s){try{e.addBreadcrumb({category:"console",message:s.map(o=>typeof o=="string"?o:JSON.stringify(o)).join(" ").slice(0,500),level:n==="error"?"error":n==="warn"?"warning":"info"});}catch{}return r.apply(console,s)});}}if(typeof globalThis<"u"&&typeof globalThis.history<"u"){let e=this,t=globalThis,n=t.history.pushState;t.history.pushState=function(...r){try{e.addBreadcrumb({category:"navigation",message:`\u2192 ${String(r[2]??"")}`,level:"info"});}catch{}return n.apply(t.history,r)},t.addEventListener("popstate",()=>{try{e.addBreadcrumb({category:"navigation",message:`\u2190 ${t.location.pathname}`,level:"info"});}catch{}});}}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,o){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 l=o??{};if(l.method?a=String(l.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(n.endpoint))return t(s,l);let u=n.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:n.navTransaction??void 0});try{let c=`00-${u.trace_id}-${u.span_id}-01`,f={...l},g=f.headers??{};return f.headers={...g,traceparent:c},t(s,f).then(h=>{let p=h;return typeof p.status=="number"&&u.setAttribute("http.status_code",p.status),u.setStatus(p.ok===!1?"error":"ok"),u.finish(),h}).catch(h=>{throw u.setStatus("error"),u.setAttribute("error.message",h instanceof Error?h.message:String(h)),u.finish(),h})}catch(c){throw u.setStatus("error"),u.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,o=r.setRequestHeader,d=r.send,a=this;r.open=function(u,c,...f){return this.__gl_method=typeof u=="string"?u.toUpperCase():"GET",this.__gl_url=typeof c=="string"?c:String(c??""),this.__gl_headers_set=false,s.apply(this,[u,c,...f])},r.setRequestHeader=function(u,c){return this.__gl_headers_set=true,o.apply(this,[u,c])},r.send=function(u){let c=this.__gl_url||"",f=this.__gl_method||"GET";if(c.startsWith(a.endpoint))return d.apply(this,[u]);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`;o.apply(this,["traceparent",m]);}catch{}let h=(m,E,B)=>{m&&g.setAttribute("http.status_code",m),B&&g.setAttribute("error.message",B),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,[u])},r[n]=true,r.__gl_orig_open=s,r.__gl_orig_set_header=o,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()??"",o=(n.textContent??"").trim().slice(0,50),d=n.getAttribute?.("href")??void 0,a=(n.className??"").toString().slice(0,80),l=globalThis,u=l.innerWidth,c=l.innerHeight,f=l.scrollY,g=typeof document<"u"?document.documentElement?.scrollHeight:void 0;this.track(r||"$click",{$element_tag:s,$element_id:n.id||void 0,$element_text:o||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:u,$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 C=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"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(r,{method:e,headers:s,body:n?JSON.stringify(n):void 0,signal:o.signal});if(!a.ok){let l=await a.json().catch(()=>({})),u=l?.error?.message??`API error ${a.status}`;throw new T(a.status,u,l?.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(i,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:i.source,event:i.event,level:i.level??"info",metadata:{...i.metadata,sdk_version:H}}),keepalive:true}).catch(()=>{});}function I(i){if(!i)return null;let e=i.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(i,e){if(!i)return;let t=i[e]??i[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function ee(i){return function(t,n,r){let s=(t.method??"GET").toUpperCase(),o=t.originalUrl??t.url??"",d=I(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}}),l=false,u=()=>{if(l)return;l=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",u),n.on("close",u),t.goodlogs={span:a},r();}}function te(i){return function(t,n,r){t.addHook("onRequest",(s,o,d)=>{let a=(s.method??"GET").toUpperCase(),l=s.url??"",u=I(N(s.headers,"traceparent")),c=i.startTransaction({op:"http.server",name:`${a} ${l}`,trace_id:u?.trace_id,attributes:{"http.method":a,"http.url":l}});s.__goodlogsSpan=c,d();}),t.addHook("onResponse",(s,o,d)=>{let a=s.__goodlogsSpan;if(a){let l=s.routerPath??s.routeOptions?.url;l&&a.setAttribute("http.route",l);let u=o.statusCode??o.raw?.statusCode??200;a.setAttribute("http.status_code",u),a.setStatus(u>=500?"error":"ok"),a.finish();}d();}),r();}}function ne(i){return {intercept(e,t){let n=e.switchToHttp(),r=n.getRequest(),s=n.getResponse(),o=(r.method??"GET").toUpperCase(),d=r.originalUrl??r.url??"",a=I(N(r.headers,"traceparent")),l=i.startTransaction({op:"http.server",name:`${o} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":o,"http.url":d}}),u=false,c=(g,h)=>{if(u)return;u=true;let p=r.route?.path;p&&l.setAttribute("http.route",p);let m=g??s.statusCode??200;l.setAttribute("http.status_code",m),l.setStatus(h||m>=500?"error":"ok"),l.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=>{l.setAttribute("error.message",h instanceof Error?h.message:String(h)),c(500,true);},complete:()=>c()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function re(i){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{i.captureException(r instanceof Error?r:new Error(String(r)),{tags:{source:"uncaughtException"},level:"fatal"}),i.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)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[n]=true);}var q=globalThis.URL;function _(i){return !!q&&i instanceof q}var j=Symbol.for("goodlogs.node-http.patched");function se(...i){let e=i[0],t=i[1],n="GET",r="";if(typeof e=="string")r=e,t&&typeof t=="object"&&!_(t)&&(n=String(t.method??n).toUpperCase());else if(_(e))r=e.toString(),t&&typeof t=="object"&&!_(t)&&(n=String(t.method??n).toUpperCase());else if(e&&typeof e=="object"){let o=e;n=String(o.method??n).toUpperCase();let d=(o.protocol??"http:").replace(":",""),a=o.hostname??o.host??"localhost",l=o.port?`:${o.port}`:"";r=`${d}://${a}${l}${o.path??"/"}`;}return {method:n,url:r,isOurs:o=>!!o&&r.startsWith(o)}}function oe(i,e,t){let n=i[0]&&typeof i[0]=="object"&&!_(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!_(i[1])?i[1]:void 0;n&&(n.headers||(n.headers={}),!(e in n.headers)&&!(e.toLowerCase()in n.headers)&&(n.headers[e]=t));}function ie(i,e){let t=e?.endpoint??i.endpoint??"",n=r=>{let s=r;if(s[j])return;s[j]=true;let o=r.request.bind(r);r.request=function(...a){let{method:l,url:u,isOurs:c}=se(...a);if(!u||c(t))return o(...a);let f=i.startTransaction({op:"http.client",name:`${l} ${u}`,attributes:{"http.method":l,"http.url":u}});oe(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=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 r=S("http");n(r);}catch{}try{let r=S("https");n(r);}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(S,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(S,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(k,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(k,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(k,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:{...M(),...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);if(this.beforeSend){try{n=this.beforeSend(n);}catch{n=null;}if(!n)return}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??J(),r=z(),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));}attachAutoBreadcrumbs(){if(typeof console<"u"){let e=this,t=["error","warn","info","log"];for(let n of t){let r=console[n];r&&(console[n]=function(...s){try{e.addBreadcrumb({category:"console",message:s.map(i=>typeof i=="string"?i:JSON.stringify(i)).join(" ").slice(0,500),level:n==="error"?"error":n==="warn"?"warning":"info"});}catch{}return r.apply(console,s)});}}if(typeof globalThis<"u"&&typeof globalThis.history<"u"){let e=this,t=globalThis,n=t.history.pushState;t.history.pushState=function(...r){try{e.addBreadcrumb({category:"navigation",message:`\u2192 ${String(r[2]??"")}`,level:"info"});}catch{}return n.apply(t.history,r)},t.addEventListener("popstate",()=>{try{e.addBreadcrumb({category:"navigation",message:`\u2190 ${t.location.pathname}`,level:"info"});}catch{}});}}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,_,N)=>{m&&g.setAttribute("http.status_code",m),N&&g.setAttribute("error.message",N),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,[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",{$element_tag:s,$element_id:n.id||void 0,$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 I=R;var C=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 x(this),this.slos=new L(this),this.ai=new P(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})}},x=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})}},L=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}`)}},P=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 O="0.1.0";function Z(o,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":O};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:O}}),keepalive:true}).catch(()=>{});}function $(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 A(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=$(A(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=$(A(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=$(A(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 H=globalThis.URL;function E(o){return !!H&&o instanceof H}var q=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"&&!E(t)&&(n=String(t.method??n).toUpperCase());else if(E(e))r=e.toString(),t&&typeof t=="object"&&!E(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"&&!E(o[0])?o[0]:o[1]&&typeof o[1]=="object"&&!E(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[q])return;s[q]=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,_)=>{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=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 w=="function"){try{let r=w("http");n(r);}catch{}try{let r=w("https");n(r);}catch{}}}
|
|
7
|
+
exports.GoodLogs=I;exports.GoodLogsApiError=T;exports.GoodLogsClient=C;exports.goodlogsExpress=ee;exports.goodlogsFastify=te;exports.goodlogsNestInterceptor=ne;exports.instrumentNodeHttp=oe;exports.instrumentNodeProcess=re;exports.parseTraceparent=$;exports.resolveEndpoint=y;exports.resolveRegion=B;exports.sendTelemetry=Z;
|
package/dist/index.d.cts
CHANGED
|
@@ -318,12 +318,10 @@ interface TelemetryOptions {
|
|
|
318
318
|
*/
|
|
319
319
|
declare function sendTelemetry(event: TelemetryEvent, options?: TelemetryOptions): void;
|
|
320
320
|
|
|
321
|
-
/** Region-to-API URL mapping. Single EU region — all keys route here. */
|
|
322
|
-
declare const REGION_URLS: Record<string, string>;
|
|
323
321
|
/** Extract region from API key prefix: gl_sk_us_xxx → "us", gl_pk_eu_xxx → "eu" */
|
|
324
322
|
declare function resolveRegion(apiKey: string): string;
|
|
325
|
-
/** Resolve API endpoint from key. User-provided endpoint always wins. */
|
|
326
|
-
declare function resolveEndpoint(apiKey: string, userEndpoint?: string): string;
|
|
323
|
+
/** Resolve API endpoint from key + environment. User-provided endpoint always wins. */
|
|
324
|
+
declare function resolveEndpoint(apiKey: string, userEndpoint?: string, environment?: string): string;
|
|
327
325
|
|
|
328
326
|
/**
|
|
329
327
|
* Node.js framework adapters for GoodLogs tracing.
|
|
@@ -475,4 +473,4 @@ declare function instrumentNodeHttp(gl: GoodLogs, opts?: {
|
|
|
475
473
|
endpoint?: string;
|
|
476
474
|
}): void;
|
|
477
475
|
|
|
478
|
-
export { type AiChatRequest, type AiChatResponse, type AiToolCall, type AlertRule, type CreateAlertRule, type CreateSlo, GoodLogs, GoodLogsApiError, GoodLogsClient, type GoodLogsClientOptions, type GqlAutocompleteResult, type GqlBatchResult, type GqlResult, type LogRecord, type MuteAlertRequest, type Nl2GqlResult, type NotifyChannel, type ProjectInfo,
|
|
476
|
+
export { type AiChatRequest, type AiChatResponse, type AiToolCall, type AlertRule, type CreateAlertRule, type CreateSlo, GoodLogs, GoodLogsApiError, GoodLogsClient, type GoodLogsClientOptions, type GqlAutocompleteResult, type GqlBatchResult, type GqlResult, type LogRecord, type MuteAlertRequest, type Nl2GqlResult, type NotifyChannel, type ProjectInfo, type SchemaField, type SchemaResponse, type SloDefinition, type TelemetryEvent, type TelemetryOptions, type UpdateAlertRule, type UpdateSlo, goodlogsExpress, goodlogsFastify, goodlogsNestInterceptor, instrumentNodeHttp, instrumentNodeProcess, parseTraceparent, resolveEndpoint, resolveRegion, sendTelemetry };
|
package/dist/index.d.ts
CHANGED
|
@@ -318,12 +318,10 @@ interface TelemetryOptions {
|
|
|
318
318
|
*/
|
|
319
319
|
declare function sendTelemetry(event: TelemetryEvent, options?: TelemetryOptions): void;
|
|
320
320
|
|
|
321
|
-
/** Region-to-API URL mapping. Single EU region — all keys route here. */
|
|
322
|
-
declare const REGION_URLS: Record<string, string>;
|
|
323
321
|
/** Extract region from API key prefix: gl_sk_us_xxx → "us", gl_pk_eu_xxx → "eu" */
|
|
324
322
|
declare function resolveRegion(apiKey: string): string;
|
|
325
|
-
/** Resolve API endpoint from key. User-provided endpoint always wins. */
|
|
326
|
-
declare function resolveEndpoint(apiKey: string, userEndpoint?: string): string;
|
|
323
|
+
/** Resolve API endpoint from key + environment. User-provided endpoint always wins. */
|
|
324
|
+
declare function resolveEndpoint(apiKey: string, userEndpoint?: string, environment?: string): string;
|
|
327
325
|
|
|
328
326
|
/**
|
|
329
327
|
* Node.js framework adapters for GoodLogs tracing.
|
|
@@ -475,4 +473,4 @@ declare function instrumentNodeHttp(gl: GoodLogs, opts?: {
|
|
|
475
473
|
endpoint?: string;
|
|
476
474
|
}): void;
|
|
477
475
|
|
|
478
|
-
export { type AiChatRequest, type AiChatResponse, type AiToolCall, type AlertRule, type CreateAlertRule, type CreateSlo, GoodLogs, GoodLogsApiError, GoodLogsClient, type GoodLogsClientOptions, type GqlAutocompleteResult, type GqlBatchResult, type GqlResult, type LogRecord, type MuteAlertRequest, type Nl2GqlResult, type NotifyChannel, type ProjectInfo,
|
|
476
|
+
export { type AiChatRequest, type AiChatResponse, type AiToolCall, type AlertRule, type CreateAlertRule, type CreateSlo, GoodLogs, GoodLogsApiError, GoodLogsClient, type GoodLogsClientOptions, type GqlAutocompleteResult, type GqlBatchResult, type GqlResult, type LogRecord, type MuteAlertRequest, type Nl2GqlResult, type NotifyChannel, type ProjectInfo, type SchemaField, type SchemaResponse, type SloDefinition, type TelemetryEvent, type TelemetryOptions, type UpdateAlertRule, type UpdateSlo, goodlogsExpress, goodlogsFastify, goodlogsNestInterceptor, instrumentNodeHttp, instrumentNodeProcess, parseTraceparent, resolveEndpoint, resolveRegion, sendTelemetry };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
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>",
|
|
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(),
|
|
1
|
+
var w=(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')});function B(o){let e=o.split("_");return e.length>=4&&e[0]==="gl"?e[2]:"eu"}function j(o,e){return o==="eu"&&(!e||e==="production")?"https://api.goodlogs.dev":o==="eu"?`https://api-${e}.goodlogs.dev`:!e||e==="production"?`https://api-${o}.goodlogs.dev`:`https://api-${o}-${e}.goodlogs.dev`}function y(o,e,t){if(e)return e;let n=B(o);return j(n,t)}var G=5e3,F=50,v="0.5.4",S="gl_anon_id",k="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 M(){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 U(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=U(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(S);if(o)return o;let e=b();return localStorage.setItem(S,e),e}return b()}function W(){if(typeof sessionStorage<"u"){let o=sessionStorage.getItem(k);if(o)return o;let e=b();return sessionStorage.setItem(k,e),e}return b()}function J(){let o="";for(let e=0;e<32;e++)o+=(Math.random()*16|0).toString(16);return o}function z(){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.beforeSend=null;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,e.environment).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.beforeSend=e.beforeSend??null,this.anonymousId=V(),this.sessionId=W(),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.attachAutoBreadcrumbs()),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 ${r}]`,this.onError(new Error(`Log message truncated from ${t.length} to ${r} chars`)));let
|
|
6
|
-
`);await this.postEnvelopeWithRetry(f,l);}}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),o=Math.random()*500;return await new Promise(d=>setTimeout(d,s+o)),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 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(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(l=>setTimeout(l,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 o=await s.json().catch(()=>null);if(o&&o.rejected&&o.rejected>0){let d=t.slice(o.accepted??0);d.length>0&&n(d);}}catch(s){let o=s instanceof Error?s:new Error(String(s));r===0&&n(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,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,o=s(r.domainLookupEnd)-s(r.domainLookupStart);o>0&&this.captureVital("dns",o);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 l=s(r.domComplete)-s(r.responseEnd);l>0&&this.captureVital("dom_processing",l);let u=s(r.loadEventEnd)-s(r.fetchStart);u>0&&this.captureVital("page_load",u);}}).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=l=>l&&Number.isFinite(l)&&l>0?l: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 o=n(t?.responseEnd)-n(t?.responseStart);o>0&&this.captureVital("download",o);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 o;if(typeof r=="string")o=r;else try{o=JSON.stringify(r);}catch{o=String(r);}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));}attachAutoBreadcrumbs(){if(typeof console<"u"){let e=this,t=["error","warn","info","log"];for(let n of t){let r=console[n];r&&(console[n]=function(...s){try{e.addBreadcrumb({category:"console",message:s.map(o=>typeof o=="string"?o:JSON.stringify(o)).join(" ").slice(0,500),level:n==="error"?"error":n==="warn"?"warning":"info"});}catch{}return r.apply(console,s)});}}if(typeof globalThis<"u"&&typeof globalThis.history<"u"){let e=this,t=globalThis,n=t.history.pushState;t.history.pushState=function(...r){try{e.addBreadcrumb({category:"navigation",message:`\u2192 ${String(r[2]??"")}`,level:"info"});}catch{}return n.apply(t.history,r)},t.addEventListener("popstate",()=>{try{e.addBreadcrumb({category:"navigation",message:`\u2190 ${t.location.pathname}`,level:"info"});}catch{}});}}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,o){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 l=o??{};if(l.method?a=String(l.method).toUpperCase():typeof s=="object"&&(a=s.method?.toUpperCase()??a),d.startsWith(n.endpoint))return t(s,l);let u=n.startSpan({op:"http.client",name:`${a} ${d}`,attributes:{"http.method":a,"http.url":d},parent:n.navTransaction??void 0});try{let c=`00-${u.trace_id}-${u.span_id}-01`,f={...l},g=f.headers??{};return f.headers={...g,traceparent:c},t(s,f).then(h=>{let p=h;return typeof p.status=="number"&&u.setAttribute("http.status_code",p.status),u.setStatus(p.ok===!1?"error":"ok"),u.finish(),h}).catch(h=>{throw u.setStatus("error"),u.setAttribute("error.message",h instanceof Error?h.message:String(h)),u.finish(),h})}catch(c){throw u.setStatus("error"),u.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,o=r.setRequestHeader,d=r.send,a=this;r.open=function(u,c,...f){return this.__gl_method=typeof u=="string"?u.toUpperCase():"GET",this.__gl_url=typeof c=="string"?c:String(c??""),this.__gl_headers_set=false,s.apply(this,[u,c,...f])},r.setRequestHeader=function(u,c){return this.__gl_headers_set=true,o.apply(this,[u,c])},r.send=function(u){let c=this.__gl_url||"",f=this.__gl_method||"GET";if(c.startsWith(a.endpoint))return d.apply(this,[u]);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`;o.apply(this,["traceparent",m]);}catch{}let h=(m,E,B)=>{m&&g.setAttribute("http.status_code",m),B&&g.setAttribute("error.message",B),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,[u])},r[n]=true,r.__gl_orig_open=s,r.__gl_orig_set_header=o,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()??"",o=(n.textContent??"").trim().slice(0,50),d=n.getAttribute?.("href")??void 0,a=(n.className??"").toString().slice(0,80),l=globalThis,u=l.innerWidth,c=l.innerHeight,f=l.scrollY,g=typeof document<"u"?document.documentElement?.scrollHeight:void 0;this.track(r||"$click",{$element_tag:s,$element_id:n.id||void 0,$element_text:o||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:u,$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 C=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"},o=new AbortController,d=setTimeout(()=>o.abort(),this.timeout);try{let a=await fetch(r,{method:e,headers:s,body:n?JSON.stringify(n):void 0,signal:o.signal});if(!a.ok){let l=await a.json().catch(()=>({})),u=l?.error?.message??`API error ${a.status}`;throw new T(a.status,u,l?.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(i,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:i.source,event:i.event,level:i.level??"info",metadata:{...i.metadata,sdk_version:H}}),keepalive:true}).catch(()=>{});}function I(i){if(!i)return null;let e=i.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(i,e){if(!i)return;let t=i[e]??i[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function ee(i){return function(t,n,r){let s=(t.method??"GET").toUpperCase(),o=t.originalUrl??t.url??"",d=I(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}}),l=false,u=()=>{if(l)return;l=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",u),n.on("close",u),t.goodlogs={span:a},r();}}function te(i){return function(t,n,r){t.addHook("onRequest",(s,o,d)=>{let a=(s.method??"GET").toUpperCase(),l=s.url??"",u=I(N(s.headers,"traceparent")),c=i.startTransaction({op:"http.server",name:`${a} ${l}`,trace_id:u?.trace_id,attributes:{"http.method":a,"http.url":l}});s.__goodlogsSpan=c,d();}),t.addHook("onResponse",(s,o,d)=>{let a=s.__goodlogsSpan;if(a){let l=s.routerPath??s.routeOptions?.url;l&&a.setAttribute("http.route",l);let u=o.statusCode??o.raw?.statusCode??200;a.setAttribute("http.status_code",u),a.setStatus(u>=500?"error":"ok"),a.finish();}d();}),r();}}function ne(i){return {intercept(e,t){let n=e.switchToHttp(),r=n.getRequest(),s=n.getResponse(),o=(r.method??"GET").toUpperCase(),d=r.originalUrl??r.url??"",a=I(N(r.headers,"traceparent")),l=i.startTransaction({op:"http.server",name:`${o} ${d}`,trace_id:a?.trace_id,attributes:{"http.method":o,"http.url":d}}),u=false,c=(g,h)=>{if(u)return;u=true;let p=r.route?.path;p&&l.setAttribute("http.route",p);let m=g??s.statusCode??200;l.setAttribute("http.status_code",m),l.setStatus(h||m>=500?"error":"ok"),l.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=>{l.setAttribute("error.message",h instanceof Error?h.message:String(h)),c(500,true);},complete:()=>c()});return {unsubscribe:()=>g.unsubscribe?.()}}return f}}}function re(i){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{i.captureException(r instanceof Error?r:new Error(String(r)),{tags:{source:"uncaughtException"},level:"fatal"}),i.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)}})());i.captureException(s,{tags:{source:"unhandledRejection"}});}catch{}}),t[n]=true);}var q=globalThis.URL;function _(i){return !!q&&i instanceof q}var j=Symbol.for("goodlogs.node-http.patched");function se(...i){let e=i[0],t=i[1],n="GET",r="";if(typeof e=="string")r=e,t&&typeof t=="object"&&!_(t)&&(n=String(t.method??n).toUpperCase());else if(_(e))r=e.toString(),t&&typeof t=="object"&&!_(t)&&(n=String(t.method??n).toUpperCase());else if(e&&typeof e=="object"){let o=e;n=String(o.method??n).toUpperCase();let d=(o.protocol??"http:").replace(":",""),a=o.hostname??o.host??"localhost",l=o.port?`:${o.port}`:"";r=`${d}://${a}${l}${o.path??"/"}`;}return {method:n,url:r,isOurs:o=>!!o&&r.startsWith(o)}}function oe(i,e,t){let n=i[0]&&typeof i[0]=="object"&&!_(i[0])?i[0]:i[1]&&typeof i[1]=="object"&&!_(i[1])?i[1]:void 0;n&&(n.headers||(n.headers={}),!(e in n.headers)&&!(e.toLowerCase()in n.headers)&&(n.headers[e]=t));}function ie(i,e){let t=e?.endpoint??i.endpoint??"",n=r=>{let s=r;if(s[j])return;s[j]=true;let o=r.request.bind(r);r.request=function(...a){let{method:l,url:u,isOurs:c}=se(...a);if(!u||c(t))return o(...a);let f=i.startTransaction({op:"http.client",name:`${l} ${u}`,attributes:{"http.method":l,"http.url":u}});oe(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=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 r=S("http");n(r);}catch{}try{let r=S("https");n(r);}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(S,e);}getDistinctId(){return this.anonymousId}reset(){this.anonymousId=b(),this.sessionId=b(),typeof localStorage<"u"&&localStorage.setItem(S,this.anonymousId),typeof sessionStorage<"u"&&sessionStorage.setItem(k,this.sessionId);}getSessionId(){return this.sessionId}newSession(){this.sessionId=b(),typeof sessionStorage<"u"&&sessionStorage.setItem(k,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(k,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:{...M(),...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);if(this.beforeSend){try{n=this.beforeSend(n);}catch{n=null;}if(!n)return}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??J(),r=z(),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));}attachAutoBreadcrumbs(){if(typeof console<"u"){let e=this,t=["error","warn","info","log"];for(let n of t){let r=console[n];r&&(console[n]=function(...s){try{e.addBreadcrumb({category:"console",message:s.map(i=>typeof i=="string"?i:JSON.stringify(i)).join(" ").slice(0,500),level:n==="error"?"error":n==="warn"?"warning":"info"});}catch{}return r.apply(console,s)});}}if(typeof globalThis<"u"&&typeof globalThis.history<"u"){let e=this,t=globalThis,n=t.history.pushState;t.history.pushState=function(...r){try{e.addBreadcrumb({category:"navigation",message:`\u2192 ${String(r[2]??"")}`,level:"info"});}catch{}return n.apply(t.history,r)},t.addEventListener("popstate",()=>{try{e.addBreadcrumb({category:"navigation",message:`\u2190 ${t.location.pathname}`,level:"info"});}catch{}});}}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,_,N)=>{m&&g.setAttribute("http.status_code",m),N&&g.setAttribute("error.message",N),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,[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",{$element_tag:s,$element_id:n.id||void 0,$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 I=R;var C=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 x(this),this.slos=new L(this),this.ai=new P(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})}},x=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})}},L=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}`)}},P=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 O="0.1.0";function Z(o,e){let t=y(e?.apiKey??"",e?.endpoint).replace(/\/+$/,""),n={"Content-Type":"application/json","X-GoodLogs-SDK":O};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:O}}),keepalive:true}).catch(()=>{});}function $(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 A(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=$(A(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=$(A(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=$(A(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 H=globalThis.URL;function E(o){return !!H&&o instanceof H}var q=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"&&!E(t)&&(n=String(t.method??n).toUpperCase());else if(E(e))r=e.toString(),t&&typeof t=="object"&&!E(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"&&!E(o[0])?o[0]:o[1]&&typeof o[1]=="object"&&!E(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[q])return;s[q]=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,_)=>{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=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 w=="function"){try{let r=w("http");n(r);}catch{}try{let r=w("https");n(r);}catch{}}}
|
|
7
|
+
export{I as GoodLogs,T as GoodLogsApiError,C as GoodLogsClient,ee as goodlogsExpress,te as goodlogsFastify,ne as goodlogsNestInterceptor,oe as instrumentNodeHttp,re as instrumentNodeProcess,$ as parseTraceparent,y as resolveEndpoint,B as resolveRegion,Z as sendTelemetry};
|