🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor analytics script configuration to remove API key handling
Bill Yang77883bb066fb
diff --git a/docs-v2/content/docs/script.mdx b/docs-v2/content/docs/script.mdxindex 8681589af..744c697da 100644--- a/docs-v2/content/docs/script.mdx+++ b/docs-v2/content/docs/script.mdx@@ -28,20 +28,16 @@ Most tracking options are configured through your site settings in the Rybbit da- **Session Replay**: Record user interactions for debugging and UX analysis- **Web Vitals**: Collect Core Web Vitals performance metrics-These settings can be managed from your site's configuration page in the dashboard.+### Script Attributes-### Testing & Debugging Overrides--For testing and debugging purposes, you can override certain settings using `data-*` attributes on the `<script>` tag:+These are the attributes you can pass to the script tag.| Attribute | Type | Default | Description || :---------------- | :--------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments). || `data-mask-patterns` | `string` | `[]` | A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data. Supports the same wildcards as `data-skip-patterns`. || `data-debounce` | `string` | `"500"`| The delay (in milliseconds) before tracking a pageview after URL changes via the History API (`pushState`, `replaceState`). Set to `0` to disable debouncing. |-| `data-api-key` | `string` | `undefined` | API key for tracking from localhost during development. Bypasses origin validation. See [Localhost Tracking](/docs/localhost-tracking) for details. |-**Note:** These attributes are intended for debugging and testing only. Production configuration should be managed through your site settings.### Pattern Matching Detailsdiff --git a/server/public/script-full.js b/server/public/script-full.jsindex c81b89624..bb40b0759 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -77,7 +77,6 @@}const skipPatterns = parseJsonSafely(scriptTag.getAttribute("data-skip-patterns"), []);const maskPatterns = parseJsonSafely(scriptTag.getAttribute("data-mask-patterns"), []);- const apiKey = scriptTag.getAttribute("data-api-key") || void 0;const debounceDuration = scriptTag.getAttribute("data-debounce") ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce"))) : 500;const sessionReplayBatchSize = scriptTag.getAttribute("data-replay-batch-size") ? Math.max(1, parseInt(scriptTag.getAttribute("data-replay-batch-size"))) : 250;const sessionReplayBatchInterval = scriptTag.getAttribute("data-replay-batch-interval") ? Math.max(1e3, parseInt(scriptTag.getAttribute("data-replay-batch-interval"))) : 5e3;@@ -89,7 +88,6 @@sessionReplayBatchInterval,skipPatterns,maskPatterns,- apiKey,// Default all tracking to true initially (will be updated from API)autoTrackPageview: true,autoTrackSpa: true,@@ -174,14 +172,14 @@timestamp: event.timestamp || Date.now()});},- recordCanvas: true,- // Record canvas elements+ recordCanvas: false,+ // Disable canvas recording to reduce datacollectFonts: true,- // Collect font info for better replay- checkoutEveryNms: 3e4,- // Checkout every 30 seconds- checkoutEveryNth: 200,- // Checkout every 200 events+ // Disable font collection to reduce data+ checkoutEveryNms: 6e4,+ // Checkout every 60 seconds (was 30)+ checkoutEveryNth: 500,+ // Checkout every 500 events (was 200)maskAllInputs: true,// Mask all input values for privacymaskInputOptions: {@@ -201,14 +199,27 @@headMetaVerification: true},sampling: {- // Optional: reduce recording frequency to save bandwidth+ // Aggressive sampling to reduce data volumemousemove: false,- // Don't record every mouse move- mouseInteraction: true,- scroll: 150,- // Sample scroll events every 150ms- input: "last"+ // Don't record mouse moves at all+ mouseInteraction: {+ MouseUp: false,+ MouseDown: false,+ Click: true,+ // Only record clicks+ ContextMenu: false,+ DblClick: true,+ Focus: true,+ Blur: true,+ TouchStart: false,+ TouchEnd: false+ },+ scroll: 500,+ // Sample scroll events every 500ms (was 150)+ input: "last",// Only record the final input value+ media: 800+ // Sample media interactions less frequently}});this.isRecording = true;@@ -323,9 +334,6 @@}async sendSessionReplayBatch(batch) {try {- if (this.config.apiKey) {- batch.apiKey = this.config.apiKey;- }await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`, {method: "POST",headers: {@@ -368,9 +376,6 @@if (this.customUserId) {payload.user_id = this.customUserId;}- if (this.config.apiKey) {- payload.api_key = this.config.apiKey;- }return payload;}async sendTrackingData(payload) {diff --git a/server/public/script.js b/server/public/script.jsindex e6a143336..651cba221 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var oe=Object.defineProperty;var ce=(r,e,t)=>e in r?oe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e,t)=>ce(r,typeof e!="symbol"?e+"":e,t);function le(r){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=r.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let c=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+c+"$")}function P(r,e){for(let t of e)try{if(le(t).test(r))return t}catch(i){console.error(`Invalid pattern: ${t}`,i)}return null}function V(r,e){let t=null;return(...i)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...i),e)}}function H(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function C(r,e){if(!r)return e;try{let t=JSON.parse(r);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}async function z(r){let e=r.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let i=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!i)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=C(r.getAttribute("data-skip-patterns"),[]),c=C(r.getAttribute("data-mask-patterns"),[]),a=r.getAttribute("data-api-key")||void 0,s=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,o=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,l=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,d={analyticsHost:t,siteId:i,debounceDuration:s,sessionReplayBatchSize:o,sessionReplayBatchInterval:l,skipPatterns:n,maskPatterns:c,apiKey:a,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1};try{let y=`${t}/site/${i}/tracking-config`,F=await fetch(y,{method:"GET",credentials:"omit"});if(F.ok){let g=await F.json();return{...d,autoTrackPageview:g.trackInitialPageView??d.autoTrackPageview,autoTrackSpa:g.trackSpaNavigation??d.autoTrackSpa,trackQuerystring:g.trackUrlParams??d.trackQuerystring,trackOutbound:g.trackOutbound??d.trackOutbound,enableWebVitals:g.webVitals??d.enableWebVitals,trackErrors:g.trackErrors??d.trackErrors,enableSessionReplay:g.sessionReplay??d.enableSessionReplay}}else return console.warn("Failed to fetch tracking config from API, using defaults"),d}catch(y){return console.warn("Error fetching tracking config:",y),d}}var R=class{constructor(e,t,i){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=i}async initialize(){this.config.enableSessionReplay&&(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let i=document.createElement("script");i.src=`${this.config.analyticsHost}/replay.js`,i.async=!1,i.onload=()=>{e()},i.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(i)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{this.stopRecordingFn=window.rrweb.record({emit:e=>{this.addEvent({type:e.type,data:e.data,timestamp:e.timestamp||Date.now()})},recordCanvas:!0,collectFonts:!0,checkoutEveryNms:3e4,checkoutEveryNth:200,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:!0,scroll:150,input:"last"}}),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var w=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem("rybbit-user-id");e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new R(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{this.config.apiKey&&(e.apiKey=this.config.apiKey),await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(t){throw console.error("Failed to send session replay batch:",t),t}}createBasePayload(){let e=new URL(window.location.href),t=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(t=e.hash.substring(1)),P(t,this.config.skipPatterns))return null;let i=P(t,this.config.maskPatterns);i&&(t=i);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),this.config.apiKey&&(n.api_key=this.config.apiKey),n}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",i={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let c={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(i):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",i="_self"){this.track("outbound","",{url:e,text:t,target:i})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let i={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(i)}trackError(e,t={}){let i=window.location.origin,n=t.filename||"",c=e.stack||"";if(n)try{if(new URL(n).origin!==i)return}catch{}else if(c&&!c.includes(i))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Z=-1,m=r=>{addEventListener("pageshow",e=>{e.persisted&&(Z=e.timeStamp,r(e))},!0)},u=(r,e,t,i)=>{let n,c;return a=>{e.value>=0&&(a||i)&&(c=e.value-(n??0),(c||n===void 0)&&(n=e.value,e.delta=c,e.rating=((s,o)=>s>o[1]?"poor":s>o[0]?"needs-improvement":"good")(e.value,t),r(e)))}},D=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},U=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},v=()=>U()?.activationStart??0,h=(r,e=-1)=>{let t=U(),i="navigate";return Z>=0?i="back-forward-cache":t&&(document.prerendering||v()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},I=new WeakMap;function x(r,e){return I.get(r)||I.set(r,new e),I.get(r)}var L=class{constructor(){p(this,"t");p(this,"i",0);p(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},b=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let i=new PerformanceObserver(n=>{Promise.resolve().then(()=>{e(n.getEntries())})});return i.observe({type:r,buffered:!0,...t}),i}}catch{}},N=r=>{let e=!1;return()=>{e||(r(),e=!0)}},f=-1,$=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,T=r=>{document.visibilityState==="hidden"&&f>-1&&(f=r.type==="visibilitychange"?r.timeStamp:0,de())},K=()=>{addEventListener("visibilitychange",T,!0),addEventListener("prerenderingchange",T,!0)},de=()=>{removeEventListener("visibilitychange",T,!0),removeEventListener("prerenderingchange",T,!0)},ee=()=>{if(f<0){let r=v();f=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>t.name==="hidden"&&t.startTime>r)[0]?.startTime)??$(),K(),m(()=>{setTimeout(()=>{f=$(),K()})})}return{get firstHiddenTime(){return f}}},S=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},J=[1800,3e3],W=(r,e={})=>{S(()=>{let t=ee(),i,n=h("FCP"),c=b("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(c.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-v(),0),n.entries.push(s),i(!0)))});c&&(i=u(r,n,J,e.reportAllChanges),m(a=>{n=h("FCP"),i=u(r,n,J,e.reportAllChanges),D(()=>{n.value=performance.now()-a.timeStamp,i(!0)})}))})},j=[.1,.25],te=(r,e={})=>{W(N(()=>{let t,i=h("CLS",0),n=x(e,L),c=s=>{for(let o of s)n.h(o);n.i>i.value&&(i.value=n.i,i.entries=n.o,t())},a=b("layout-shift",c);a&&(t=u(r,i,j,e.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),m(()=>{n.i=0,i=h("CLS",0),t=u(r,i,j,e.reportAllChanges),D(()=>t())}),setTimeout(t))}))},re=0,B=1/0,k=0,ue=r=>{for(let e of r)e.interactionId&&(B=Math.min(B,e.interactionId),k=Math.max(k,e.interactionId),re=k?(k-B)/7+1:0)},A,q=()=>A?re:performance.interactionCount??0,he=()=>{"interactionCount"in performance||A||(A=b("event",ue,{type:"event",buffered:!0,durationThreshold:0}))},Q=0,M=class{constructor(){p(this,"u",[]);p(this,"l",new Map);p(this,"m");p(this,"v")}p(){Q=q(),this.u.length=0,this.l.clear()}P(){let e=Math.min(this.u.length-1,Math.floor((q()-Q)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),i=this.l.get(e.interactionId);if(i||this.u.length<10||e.duration>t.T){if(i?e.duration>i.T?(i.entries=[e],i.T=e.duration):e.duration===i.T&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],T:e.duration},this.l.set(i.id,i),this.u.push(i)),this.u.sort((n,c)=>c.T-n.T),this.u.length>10){let n=this.u.splice(10);for(let c of n)this.l.delete(c.id)}this.v?.(i)}}},ie=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=N(r),document.addEventListener("visibilitychange",r,{once:!0}),e(()=>{r(),document.removeEventListener("visibilitychange",r)}))},G=[200,500],ne=(r,e={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&S(()=>{he();let t,i=h("INP"),n=x(e,M),c=s=>{ie(()=>{for(let l of s)n.h(l);let o=n.P();o&&o.T!==i.value&&(i.value=o.T,i.entries=o.entries,t())})},a=b("event",c,{durationThreshold:e.durationThreshold??40});t=u(r,i,G,e.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),m(()=>{n.p(),i=h("INP"),t=u(r,i,G,e.reportAllChanges)}))})},O=class{constructor(){p(this,"m")}h(e){this.m?.(e)}},Y=[2500,4e3],se=(r,e={})=>{S(()=>{let t=ee(),i,n=h("LCP"),c=x(e,O),a=o=>{e.reportAllChanges||(o=o.slice(-1));for(let l of o)c.h(l),l.startTime<t.firstHiddenTime&&(n.value=Math.max(l.startTime-v(),0),n.entries=[l],i())},s=b("largest-contentful-paint",a);if(s){i=u(r,n,Y,e.reportAllChanges);let o=N(()=>{a(s.takeRecords()),s.disconnect(),i(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>ie(o),{capture:!0,once:!0});m(l=>{n=h("LCP"),i=u(r,n,Y,e.reportAllChanges),D(()=>{n.value=performance.now()-l.timeStamp,i(!0)})})}})},X=[800,1800],_=r=>{document.prerendering?S(()=>_(r)):document.readyState!=="complete"?addEventListener("load",()=>_(r),!0):setTimeout(r)},ae=(r,e={})=>{let t=h("TTFB"),i=u(r,t,X,e.reportAllChanges);_(()=>{let n=U();n&&(t.value=Math.max(n.responseStart-v(),0),t.entries=[n],i(!0),m(()=>{t=h("TTFB",0),i=u(r,t,X,e.reportAllChanges),i(!0)}))})};var E=class{constructor(e){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=e}initialize(){try{se(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),ne(this.collectMetric.bind(this)),W(this.collectMetric.bind(this)),ae(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(n=>n!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(async function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=await z(r);if(!e)return;let t=new w(e);e.enableWebVitals&&new E(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let i=()=>t.trackPageview(),n=e.debounceDuration>0?V(i,e.debounceDuration):i;function c(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let o=s.getAttribute("data-rybbit-event");if(o){let l={};for(let d of s.attributes)if(d.name.startsWith("data-rybbit-prop-")){let y=d.name.replace("data-rybbit-prop-","");l[y]=d.value}t.trackEvent(o,l)}break}s=s.parentElement}if(e.trackOutbound){let o=a.target.closest("a");o?.href&&H(o.href)&&t.trackOutbound(o.href,o.innerText||o.textContent||"",o.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...o){a.apply(this,o),n(),t.onPageChange()},history.replaceState=function(...o){s.apply(this,o),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),error:(a,s={})=>t.trackError(a,s),trackOutbound:(a,s="",o="_self")=>t.trackOutbound(a,s,o),identify:a=>t.identify(a),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},c(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();+"use strict";(()=>{var ae=Object.defineProperty;var oe=(r,e,t)=>e in r?ae(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var h=(r,e,t)=>oe(r,typeof e!="symbol"?e+"":e,t);function ce(r){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=r.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let c=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+c+"$")}function P(r,e){for(let t of e)try{if(ce(t).test(r))return t}catch(i){console.error(`Invalid pattern: ${t}`,i)}return null}function W(r,e){let t=null;return(...i)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...i),e)}}function V(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function C(r,e){if(!r)return e;try{let t=JSON.parse(r);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}async function H(r){let e=r.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let i=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!i)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=C(r.getAttribute("data-skip-patterns"),[]),c=C(r.getAttribute("data-mask-patterns"),[]),a=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,s=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,o=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,l={analyticsHost:t,siteId:i,debounceDuration:a,sessionReplayBatchSize:s,sessionReplayBatchInterval:o,skipPatterns:n,maskPatterns:c,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1};try{let p=`${t}/site/${i}/tracking-config`,b=await fetch(p,{method:"GET",credentials:"omit"});if(b.ok){let g=await b.json();return{...l,autoTrackPageview:g.trackInitialPageView??l.autoTrackPageview,autoTrackSpa:g.trackSpaNavigation??l.autoTrackSpa,trackQuerystring:g.trackUrlParams??l.trackQuerystring,trackOutbound:g.trackOutbound??l.trackOutbound,enableWebVitals:g.webVitals??l.enableWebVitals,trackErrors:g.trackErrors??l.trackErrors,enableSessionReplay:g.sessionReplay??l.enableSessionReplay}}else return console.warn("Failed to fetch tracking config from API, using defaults"),l}catch(p){return console.warn("Error fetching tracking config:",p),l}}var R=class{constructor(e,t,i){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=i}async initialize(){this.config.enableSessionReplay&&(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let i=document.createElement("script");i.src=`${this.config.analyticsHost}/replay.js`,i.async=!1,i.onload=()=>{e()},i.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(i)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{this.stopRecordingFn=window.rrweb.record({emit:e=>{this.addEvent({type:e.type,data:e.data,timestamp:e.timestamp||Date.now()})},recordCanvas:!1,collectFonts:!0,checkoutEveryNms:6e4,checkoutEveryNth:500,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800}}),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var w=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem("rybbit-user-id");e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new R(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(t){throw console.error("Failed to send session replay batch:",t),t}}createBasePayload(){let e=new URL(window.location.href),t=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(t=e.hash.substring(1)),P(t,this.config.skipPatterns))return null;let i=P(t,this.config.maskPatterns);i&&(t=i);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),n}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",i={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let c={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(i):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",i="_self"){this.track("outbound","",{url:e,text:t,target:i})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let i={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(i)}trackError(e,t={}){let i=window.location.origin,n=t.filename||"",c=e.stack||"";if(n)try{if(new URL(n).origin!==i)return}catch{}else if(c&&!c.includes(i))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var X=-1,m=r=>{addEventListener("pageshow",e=>{e.persisted&&(X=e.timeStamp,r(e))},!0)},d=(r,e,t,i)=>{let n,c;return a=>{e.value>=0&&(a||i)&&(c=e.value-(n??0),(c||n===void 0)&&(n=e.value,e.delta=c,e.rating=((s,o)=>s>o[1]?"poor":s>o[0]?"needs-improvement":"good")(e.value,t),r(e)))}},_=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},U=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},v=()=>U()?.activationStart??0,u=(r,e=-1)=>{let t=U(),i="navigate";return X>=0?i="back-forward-cache":t&&(document.prerendering||v()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},I=new WeakMap;function x(r,e){return I.get(r)||I.set(r,new e),I.get(r)}var L=class{constructor(){h(this,"t");h(this,"i",0);h(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},y=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let i=new PerformanceObserver(n=>{Promise.resolve().then(()=>{e(n.getEntries())})});return i.observe({type:r,buffered:!0,...t}),i}}catch{}},N=r=>{let e=!1;return()=>{e||(r(),e=!0)}},f=-1,z=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,k=r=>{document.visibilityState==="hidden"&&f>-1&&(f=r.type==="visibilitychange"?r.timeStamp:0,le())},$=()=>{addEventListener("visibilitychange",k,!0),addEventListener("prerenderingchange",k,!0)},le=()=>{removeEventListener("visibilitychange",k,!0),removeEventListener("prerenderingchange",k,!0)},Z=()=>{if(f<0){let r=v();f=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>t.name==="hidden"&&t.startTime>r)[0]?.startTime)??z(),$(),m(()=>{setTimeout(()=>{f=z(),$()})})}return{get firstHiddenTime(){return f}}},S=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},J=[1800,3e3],F=(r,e={})=>{S(()=>{let t=Z(),i,n=u("FCP"),c=y("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(c.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-v(),0),n.entries.push(s),i(!0)))});c&&(i=d(r,n,J,e.reportAllChanges),m(a=>{n=u("FCP"),i=d(r,n,J,e.reportAllChanges),_(()=>{n.value=performance.now()-a.timeStamp,i(!0)})}))})},j=[.1,.25],ee=(r,e={})=>{F(N(()=>{let t,i=u("CLS",0),n=x(e,L),c=s=>{for(let o of s)n.h(o);n.i>i.value&&(i.value=n.i,i.entries=n.o,t())},a=y("layout-shift",c);a&&(t=d(r,i,j,e.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),m(()=>{n.i=0,i=u("CLS",0),t=d(r,i,j,e.reportAllChanges),_(()=>t())}),setTimeout(t))}))},te=0,B=1/0,T=0,de=r=>{for(let e of r)e.interactionId&&(B=Math.min(B,e.interactionId),T=Math.max(T,e.interactionId),te=T?(T-B)/7+1:0)},A,K=()=>A?te:performance.interactionCount??0,ue=()=>{"interactionCount"in performance||A||(A=y("event",de,{type:"event",buffered:!0,durationThreshold:0}))},q=0,M=class{constructor(){h(this,"u",[]);h(this,"l",new Map);h(this,"m");h(this,"v")}p(){q=K(),this.u.length=0,this.l.clear()}P(){let e=Math.min(this.u.length-1,Math.floor((K()-q)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),i=this.l.get(e.interactionId);if(i||this.u.length<10||e.duration>t.T){if(i?e.duration>i.T?(i.entries=[e],i.T=e.duration):e.duration===i.T&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],T:e.duration},this.l.set(i.id,i),this.u.push(i)),this.u.sort((n,c)=>c.T-n.T),this.u.length>10){let n=this.u.splice(10);for(let c of n)this.l.delete(c.id)}this.v?.(i)}}},re=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=N(r),document.addEventListener("visibilitychange",r,{once:!0}),e(()=>{r(),document.removeEventListener("visibilitychange",r)}))},Q=[200,500],ie=(r,e={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&S(()=>{ue();let t,i=u("INP"),n=x(e,M),c=s=>{re(()=>{for(let l of s)n.h(l);let o=n.P();o&&o.T!==i.value&&(i.value=o.T,i.entries=o.entries,t())})},a=y("event",c,{durationThreshold:e.durationThreshold??40});t=d(r,i,Q,e.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),m(()=>{n.p(),i=u("INP"),t=d(r,i,Q,e.reportAllChanges)}))})},O=class{constructor(){h(this,"m")}h(e){this.m?.(e)}},G=[2500,4e3],ne=(r,e={})=>{S(()=>{let t=Z(),i,n=u("LCP"),c=x(e,O),a=o=>{e.reportAllChanges||(o=o.slice(-1));for(let l of o)c.h(l),l.startTime<t.firstHiddenTime&&(n.value=Math.max(l.startTime-v(),0),n.entries=[l],i())},s=y("largest-contentful-paint",a);if(s){i=d(r,n,G,e.reportAllChanges);let o=N(()=>{a(s.takeRecords()),s.disconnect(),i(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>re(o),{capture:!0,once:!0});m(l=>{n=u("LCP"),i=d(r,n,G,e.reportAllChanges),_(()=>{n.value=performance.now()-l.timeStamp,i(!0)})})}})},Y=[800,1800],D=r=>{document.prerendering?S(()=>D(r)):document.readyState!=="complete"?addEventListener("load",()=>D(r),!0):setTimeout(r)},se=(r,e={})=>{let t=u("TTFB"),i=d(r,t,Y,e.reportAllChanges);D(()=>{let n=U();n&&(t.value=Math.max(n.responseStart-v(),0),t.entries=[n],i(!0),m(()=>{t=u("TTFB",0),i=d(r,t,Y,e.reportAllChanges),i(!0)}))})};var E=class{constructor(e){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=e}initialize(){try{ne(this.collectMetric.bind(this)),ee(this.collectMetric.bind(this)),ie(this.collectMetric.bind(this)),F(this.collectMetric.bind(this)),se(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(n=>n!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(async function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=await H(r);if(!e)return;let t=new w(e);e.enableWebVitals&&new E(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let i=()=>t.trackPageview(),n=e.debounceDuration>0?W(i,e.debounceDuration):i;function c(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let o=s.getAttribute("data-rybbit-event");if(o){let l={};for(let p of s.attributes)if(p.name.startsWith("data-rybbit-prop-")){let b=p.name.replace("data-rybbit-prop-","");l[b]=p.value}t.trackEvent(o,l)}break}s=s.parentElement}if(e.trackOutbound){let o=a.target.closest("a");o?.href&&V(o.href)&&t.trackOutbound(o.href,o.innerText||o.textContent||"",o.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...o){a.apply(this,o),n(),t.onPageChange()},history.replaceState=function(...o){s.apply(this,o),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),error:(a,s={})=>t.trackError(a,s),trackOutbound:(a,s="",o="_self")=>t.trackOutbound(a,s,o),identify:a=>t.identify(a),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},c(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();diff --git a/server/src/analytics-script/config.test.ts b/server/src/analytics-script/config.test.tsindex 384109507..7a9f788df 100644--- a/server/src/analytics-script/config.test.ts+++ b/server/src/analytics-script/config.test.ts@@ -54,7 +54,6 @@ describe("parseScriptConfig", () => {enableSessionReplay: true, // sessionReplay from APIskipPatterns: [],maskPatterns: [],- apiKey: undefined,sessionReplayBatchInterval: 5000,sessionReplayBatchSize: 250,});@@ -96,7 +95,6 @@ describe("parseScriptConfig", () => {enableSessionReplay: false,skipPatterns: [],maskPatterns: [],- apiKey: undefined,sessionReplayBatchInterval: 5000,sessionReplayBatchSize: 250,});@@ -128,7 +126,6 @@ describe("parseScriptConfig", () => {enableSessionReplay: false,skipPatterns: [],maskPatterns: [],- apiKey: undefined,sessionReplayBatchInterval: 5000,sessionReplayBatchSize: 250,});@@ -216,7 +213,6 @@ describe("parseScriptConfig", () => {mockScriptTag.setAttribute("data-site-id", "123");mockScriptTag.setAttribute("data-skip-patterns", '["/admin/**"]');mockScriptTag.setAttribute("data-mask-patterns", '["/user/**"]');- mockScriptTag.setAttribute("data-api-key", "test-key");// Mock successful API response(global.fetch as any).mockResolvedValueOnce({@@ -237,7 +233,6 @@ describe("parseScriptConfig", () => {// These should be from data attributes (overrides for testing)expect(config?.skipPatterns).toEqual(["/admin/**"]);expect(config?.maskPatterns).toEqual(["/user/**"]);- expect(config?.apiKey).toBe("test-key");// These should be from APIexpect(config?.enableSessionReplay).toBe(true);diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.tsindex 81e29aea4..6f5c2065c 100644--- a/server/src/analytics-script/config.ts+++ b/server/src/analytics-script/config.ts@@ -27,7 +27,6 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S// These can be overridden via data attributes for testing/debuggingconst skipPatterns = parseJsonSafely<string[]>(scriptTag.getAttribute("data-skip-patterns"), []);const maskPatterns = parseJsonSafely<string[]>(scriptTag.getAttribute("data-mask-patterns"), []);- const apiKey = scriptTag.getAttribute("data-api-key") || undefined;const debounceDuration = scriptTag.getAttribute("data-debounce")? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce")!))@@ -50,7 +49,6 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<SsessionReplayBatchInterval,skipPatterns,maskPatterns,- apiKey,// Default all tracking to true initially (will be updated from API)autoTrackPageview: true,autoTrackSpa: true,diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.tsindex 238e9fed0..0eb549afc 100644--- a/server/src/analytics-script/tracking.ts+++ b/server/src/analytics-script/tracking.ts@@ -40,11 +40,6 @@ export class Tracker {private async sendSessionReplayBatch(batch: SessionReplayBatch): Promise<void> {try {- // Include API key if configured- if (this.config.apiKey) {- batch.apiKey = this.config.apiKey;- }-await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`, {method: "POST",headers: {@@ -96,11 +91,6 @@ export class Tracker {payload.user_id = this.customUserId;}- // Include API key if configured- if (this.config.apiKey) {- payload.api_key = this.config.apiKey;- }-return payload;}diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.tsindex efa772fb2..b3c9f103d 100644--- a/server/src/analytics-script/types.ts+++ b/server/src/analytics-script/types.ts@@ -13,7 +13,6 @@ export interface ScriptConfig {sessionReplayBatchInterval: number;skipPatterns: string[];maskPatterns: string[];- apiKey?: string;}export interface BasePayload {@@ -27,7 +26,6 @@ export interface BasePayload {page_title: string;referrer: string;user_id?: string;- api_key?: string;}export interface TrackingPayload extends BasePayload {@@ -85,5 +83,4 @@ export interface SessionReplayBatch {viewportHeight?: number;language?: string;};- apiKey?: string;}