@runtimescope/sdk 0.9.0 → 0.9.2

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 CHANGED
@@ -1,5 +1,8 @@
1
- "use strict";var M=Object.defineProperty;var ie=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var ue=(e,t,n)=>t in e?M(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var de=(e,t)=>{for(var n in t)M(e,n,{get:t[n],enumerable:!0})},le=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ae(t))!ce.call(e,s)&&s!==n&&M(e,s,{get:()=>t[s],enumerable:!(r=ie(t,s))||r.enumerable});return e};var pe=e=>le(M({},"__esModule",{value:!0}),e);var p=(e,t,n)=>ue(e,typeof t!="symbol"?t+"":t,n);var Xe={};de(Xe,{RuntimeScope:()=>E,default:()=>Ue});module.exports=pe(Xe);var k=console.debug.bind(console),R=class R{constructor(t){p(this,"ws",null);p(this,"batch",[]);p(this,"offlineQueue",[]);p(this,"flushTimer",null);p(this,"reconnectTimer",null);p(this,"reconnectDelay",500);p(this,"reconnectAttempt",0);p(this,"connected",!1);p(this,"stopped",!1);p(this,"config");p(this,"commandHandler",null);p(this,"hasEverConnected",!1);p(this,"connectionWarningTimer",null);p(this,"visibilityHandler",null);p(this,"onlineHandler",null);this.config=t}connect(){this.stopped=!1,this.doConnect(),this.connectionWarningTimer=setTimeout(()=>{!this.hasEverConnected&&!this.stopped&&console.warn(`[RuntimeScope] SDK has not connected to ${this.config.serverUrl} after 10s. Is the collector running? Start it with: npx @runtimescope/collector`)},R.CONNECTION_WARNING_DELAY),typeof document<"u"&&(this.visibilityHandler=()=>{document.visibilityState==="visible"&&!this.connected&&!this.stopped&&(k("[RuntimeScope] Tab visible \u2014 attempting immediate reconnect"),this.resetReconnectState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.doConnect())},document.addEventListener("visibilitychange",this.visibilityHandler)),typeof window<"u"&&(this.onlineHandler=()=>{!this.connected&&!this.stopped&&(k("[RuntimeScope] Network online \u2014 attempting immediate reconnect"),this.resetReconnectState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.doConnect())},window.addEventListener("online",this.onlineHandler))}doConnect(){if(!this.stopped){try{this.ws=new WebSocket(this.config.serverUrl)}catch{this.scheduleReconnect();return}this.ws.onmessage=t=>{try{let n=JSON.parse(String(t.data));n.type==="command"&&n.payload&&this.commandHandler&&this.commandHandler(n.payload),n.type==="__server_restart"&&(k("[RuntimeScope] Server restart notice received \u2014 will reconnect immediately"),this.resetReconnectState()),n.type==="error"&&n.payload?.code==="AUTH_FAILED"&&(k("[RuntimeScope] Authentication failed \u2014 stopping reconnection"),this.stopped=!0)}catch{}},this.ws.onopen=()=>{if(this.connected=!0,this.hasEverConnected=!0,this.resetReconnectState(),k(`[RuntimeScope] Connected to ${this.config.serverUrl}`),this.sendRaw({type:"handshake",payload:{appName:this.config.appName,sdkVersion:this.config.sdkVersion,sessionId:this.config.sessionId,...this.config.authToken?{authToken:this.config.authToken}:{},...this.config.projectId?{projectId:this.config.projectId}:{}},timestamp:Date.now(),sessionId:this.config.sessionId}),this.offlineQueue.length>0){let t=this.offlineQueue.splice(0);for(let n of t)this.batch.push(n);this.flush()}this.flushTimer=setInterval(()=>this.flush(),this.config.flushIntervalMs)},this.ws.onclose=()=>{this.connected=!1,this.clearFlushTimer(),this.stopped||(k("[RuntimeScope] Disconnected, will reconnect..."),this.scheduleReconnect())},this.ws.onerror=()=>{k(`[RuntimeScope] WebSocket error connecting to ${this.config.serverUrl}`)}}}send(t){this.connected?(this.batch.push(t),this.batch.length>=this.config.batchSize&&this.flush()):this.offlineQueue.length<R.MAX_OFFLINE_QUEUE&&this.offlineQueue.push(t)}flush(){if(this.batch.length===0||!this.connected||!this.ws)return;let t=this.batch.splice(0);this.sendRaw({type:"event",payload:{events:t},timestamp:Date.now(),sessionId:this.config.sessionId})}sendRaw(t){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(t))}catch{}}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;this.reconnectAttempt++;let t;if(this.reconnectAttempt<=R.FAST_RETRY_COUNT)t=R.FAST_RETRY_DELAY;else{let n=this.reconnectDelay*.25*(Math.random()*2-1);t=Math.min(this.reconnectDelay+n,R.MAX_RECONNECT_DELAY),this.reconnectDelay=Math.min(this.reconnectDelay*2,R.MAX_RECONNECT_DELAY)}this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},t)}resetReconnectState(){this.reconnectDelay=500,this.reconnectAttempt=0}clearFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}onCommand(t){this.commandHandler=t}sendCommandResponse(t,n,r){this.sendRaw({type:"command_response",requestId:t,command:n,payload:r,timestamp:Date.now(),sessionId:this.config.sessionId})}disconnect(){this.stopped=!0,this.clearFlushTimer(),this.connectionWarningTimer&&(clearTimeout(this.connectionWarningTimer),this.connectionWarningTimer=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.onlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.flush(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.close(),this.ws=null),this.connected=!1,this.batch=[],this.offlineQueue=[]}};p(R,"MAX_OFFLINE_QUEUE",1e3),p(R,"MAX_RECONNECT_DELAY",3e4),p(R,"CONNECTION_WARNING_DELAY",1e4),p(R,"FAST_RETRY_COUNT",3),p(R,"FAST_RETRY_DELAY",500);var F=R;function m(){let e=new Uint8Array(8);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function $(){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var fe=1e3,me=1e4,he=5e3,C=new Map,x=null,P=0;function ve(){P++,!x&&(x=setInterval(()=>{let e=Date.now()-me;for(let[t,n]of C)n<e&&C.delete(t)},he))}function ge(){P--,P<=0&&x&&(clearInterval(x),x=null,P=0)}function W(e,t,n,r){let s=window.fetch,c=new Set(n.map(a=>a.toLowerCase())),o=r?.captureBody??!1,i=r?.maxBodySize??65536;return ve(),window.fetch=async function(a,u){let d=performance.now(),l=typeof a=="string"?a:a instanceof URL?a.href:a.url,f=(u?.method??"GET").toUpperCase(),b=ye(u?.headers,c),g=Re(u?.body),T=Se(u?.body),D;o&&u?.body&&(D=Ee(u.body,i));let j=`${f}:${l}:${d}`;if(C.size>=fe){let h=C.keys().next().value;h!==void 0&&C.delete(h)}C.set(j,Date.now());try{let h=await s.call(window,a,u),_=performance.now()-d,L=parseInt(h.headers.get("content-length")||"0",10),I=we(h.headers,c),v;if(o)try{let O=await h.clone().text();v=O.length>i?O.slice(0,i):O}catch{}let w={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"network",url:l,method:f,status:h.status,requestHeaders:b,responseHeaders:I,requestBodySize:g,responseBodySize:L,duration:_,ttfb:_,graphqlOperation:T,requestBody:D,responseBody:v,source:"fetch"};if(r?.beforeSend){let S=r.beforeSend(w);S&&e(S)}else e(w);return h}catch(h){let _=performance.now()-d,L="error",I="";h instanceof DOMException&&h.name==="AbortError"?(L="abort",I="Request aborted"):h instanceof Error&&(I=h.message);let v={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"network",url:l,method:f,status:0,requestHeaders:b,responseHeaders:{},requestBodySize:g,responseBodySize:0,duration:_,ttfb:0,graphqlOperation:T,requestBody:D,errorPhase:L,errorMessage:I,source:"fetch"};if(r?.beforeSend){let w=r.beforeSend(v);w&&e(w)}else e(v);throw h}},()=>{window.fetch=s,ge()}}function ye(e,t){let n={};if(!e)return n;if(e instanceof Headers)e.forEach((r,s)=>{n[s]=t.has(s.toLowerCase())?"[REDACTED]":r});else if(Array.isArray(e))for(let[r,s]of e)n[r]=t.has(r.toLowerCase())?"[REDACTED]":s;else for(let[r,s]of Object.entries(e))n[r]=t.has(r.toLowerCase())?"[REDACTED]":s;return n}function we(e,t){let n={};return e.forEach((r,s)=>{n[s]=t.has(s.toLowerCase())?"[REDACTED]":r}),n}function Re(e){return e?typeof e=="string"?new Blob([e]).size:e instanceof Blob?e.size:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:e instanceof FormData?0:e instanceof URLSearchParams?new Blob([e.toString()]).size:0:0}function Ee(e,t){if(e){if(typeof e=="string")return e.length>t?e.slice(0,t):e;if(e instanceof URLSearchParams){let n=e.toString();return n.length>t?n.slice(0,t):n}if(e instanceof FormData)return"[FormData]";if(e instanceof Blob)return`[Blob ${e.size} bytes]`;if(e instanceof ArrayBuffer)return`[ArrayBuffer ${e.byteLength} bytes]`;if(ArrayBuffer.isView(e))return`[TypedArray ${e.byteLength} bytes]`}}function Se(e){if(!(!e||typeof e!="string"))try{let t=JSON.parse(e);if(typeof t.query=="string"){let n=t.query.trim(),r="query";n.startsWith("mutation")?r="mutation":n.startsWith("subscription")&&(r="subscription");let s=t.operationName||be(n)||"anonymous";return{type:r,name:s}}}catch{}}function be(e){return e.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function y(e,t=5){let n=new WeakSet;function r(s,c){if(c>t)return"[max depth]";if(s==null)return s;if(typeof s=="function")return`[Function: ${s.name||"anonymous"}]`;if(typeof s=="symbol"||typeof s=="bigint")return s.toString();if(typeof s!="object")return s;if(s instanceof Error)return{name:s.name,message:s.message,stack:s.stack};if(s instanceof Date)return s.toISOString();if(s instanceof RegExp)return s.toString();if(n.has(s))return"[Circular]";if(n.add(s),Array.isArray(s))return s.map(u=>r(u,c+1));let o={},i;try{i=Object.keys(s)}catch{return"[Object]"}let a=50;for(let u=0;u<Math.min(i.length,a);u++)try{o[i[u]]=r(s[i[u]],c+1)}catch{o[i[u]]="[Error accessing property]"}return i.length>a&&(o["..."]=`${i.length-a} more keys`),o}return r(e,0)}var V=["log","warn","error","info","debug","trace"];function G(e,t,n){let r={};for(let s of V)r[s]=console[s].bind(console),console[s]=(...c)=>{let o=c.map(a=>typeof a=="string"?a:_e(a)).join(" "),i={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"console",level:s,message:o,args:c.map(a=>y(a,3)),stackTrace:s==="error"||s==="trace"?new Error().stack?.split(`
1
+ "use strict";var M=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var le=(t,e,o)=>e in t?M(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var pe=(t,e)=>{for(var o in e)M(t,o,{get:e[o],enumerable:!0})},fe=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ue(e))!de.call(t,r)&&r!==o&&M(t,r,{get:()=>e[r],enumerable:!(n=ce(e,r))||n.enumerable});return t};var me=t=>fe(M({},"__esModule",{value:!0}),t);var f=(t,e,o)=>le(t,typeof e!="symbol"?e+"":e,o);var Xe={};pe(Xe,{RuntimeScope:()=>b,default:()=>Ue});module.exports=me(Xe);var O=console.debug.bind(console),S=class S{constructor(e){f(this,"ws",null);f(this,"batch",[]);f(this,"offlineQueue",[]);f(this,"flushTimer",null);f(this,"reconnectTimer",null);f(this,"reconnectDelay",500);f(this,"reconnectAttempt",0);f(this,"connected",!1);f(this,"stopped",!1);f(this,"config");f(this,"commandHandler",null);f(this,"hasEverConnected",!1);f(this,"connectionWarningTimer",null);f(this,"visibilityHandler",null);f(this,"onlineHandler",null);this.config=e}connect(){this.stopped=!1,this.doConnect(),this.connectionWarningTimer=setTimeout(()=>{!this.hasEverConnected&&!this.stopped&&console.warn(`[RuntimeScope] SDK has not connected to ${this.config.serverUrl} after 10s. Is the collector running? Start it with: npx @runtimescope/collector`)},S.CONNECTION_WARNING_DELAY),typeof document<"u"&&(this.visibilityHandler=()=>{document.visibilityState==="visible"&&!this.connected&&!this.stopped&&(O("[RuntimeScope] Tab visible \u2014 attempting immediate reconnect"),this.resetReconnectState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.doConnect())},document.addEventListener("visibilitychange",this.visibilityHandler)),typeof window<"u"&&(this.onlineHandler=()=>{!this.connected&&!this.stopped&&(O("[RuntimeScope] Network online \u2014 attempting immediate reconnect"),this.resetReconnectState(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.doConnect())},window.addEventListener("online",this.onlineHandler))}doConnect(){if(!this.stopped){try{this.ws=new WebSocket(this.config.serverUrl)}catch{this.scheduleReconnect();return}this.ws.onmessage=e=>{try{let o=JSON.parse(String(e.data));o.type==="command"&&o.payload&&this.commandHandler&&this.commandHandler(o.payload),o.type==="__server_restart"&&(O("[RuntimeScope] Server restart notice received \u2014 will reconnect immediately"),this.resetReconnectState()),o.type==="error"&&o.payload?.code==="AUTH_FAILED"&&(O("[RuntimeScope] Authentication failed \u2014 stopping reconnection"),this.stopped=!0)}catch{}},this.ws.onopen=()=>{if(this.connected=!0,this.hasEverConnected=!0,this.resetReconnectState(),O(`[RuntimeScope] Connected to ${this.config.serverUrl}`),this.sendRaw({type:"handshake",payload:{appName:this.config.appName,sdkVersion:this.config.sdkVersion,sessionId:this.config.sessionId,...this.config.authToken?{authToken:this.config.authToken}:{},...this.config.projectId?{projectId:this.config.projectId}:{}},timestamp:Date.now(),sessionId:this.config.sessionId}),this.offlineQueue.length>0){let e=this.offlineQueue.splice(0);for(let o of e)this.batch.push(o);this.flush()}this.flushTimer=setInterval(()=>this.flush(),this.config.flushIntervalMs)},this.ws.onclose=()=>{this.connected=!1,this.clearFlushTimer(),this.stopped||(O("[RuntimeScope] Disconnected, will reconnect..."),this.scheduleReconnect())},this.ws.onerror=()=>{O(`[RuntimeScope] WebSocket error connecting to ${this.config.serverUrl}`)}}}send(e){this.connected?(this.batch.push(e),this.batch.length>=this.config.batchSize&&this.flush()):this.offlineQueue.length<S.MAX_OFFLINE_QUEUE&&this.offlineQueue.push(e)}flush(){if(this.batch.length===0||!this.connected||!this.ws)return;let e=this.batch.splice(0);this.sendRaw({type:"event",payload:{events:e},timestamp:Date.now(),sessionId:this.config.sessionId})}sendRaw(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(e))}catch{}}scheduleReconnect(){if(this.stopped||this.reconnectTimer)return;this.reconnectAttempt++;let e;if(this.reconnectAttempt<=S.FAST_RETRY_COUNT)e=S.FAST_RETRY_DELAY;else{let o=this.reconnectDelay*.25*(Math.random()*2-1);e=Math.min(this.reconnectDelay+o,S.MAX_RECONNECT_DELAY),this.reconnectDelay=Math.min(this.reconnectDelay*2,S.MAX_RECONNECT_DELAY)}this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},e)}resetReconnectState(){this.reconnectDelay=500,this.reconnectAttempt=0}clearFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}onCommand(e){this.commandHandler=e}sendCommandResponse(e,o,n){this.sendRaw({type:"command_response",requestId:e,command:o,payload:n,timestamp:Date.now(),sessionId:this.config.sessionId})}disconnect(){this.stopped=!0,this.clearFlushTimer(),this.connectionWarningTimer&&(clearTimeout(this.connectionWarningTimer),this.connectionWarningTimer=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.onlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.flush(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.close(),this.ws=null),this.connected=!1,this.batch=[],this.offlineQueue=[]}};f(S,"MAX_OFFLINE_QUEUE",1e3),f(S,"MAX_RECONNECT_DELAY",3e4),f(S,"CONNECTION_WARNING_DELAY",1e4),f(S,"FAST_RETRY_COUNT",3),f(S,"FAST_RETRY_DELAY",500);var P=S;function m(){let t=new Uint8Array(8);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function X(){let t=new Uint8Array(16);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}var he=1e3,ge=1e4,ve=5e3,L=new Map,H=null,B=0;function we(){B++,!H&&(H=setInterval(()=>{let t=Date.now()-ge;for(let[e,o]of L)o<t&&L.delete(e)},ve))}function ye(){B--,B<=0&&H&&(clearInterval(H),H=null,B=0)}function W(t,e,o,n){let r=window.fetch,u=new Set(o.map(a=>a.toLowerCase())),i=n?.captureBody??!1,s=n?.maxBodySize??65536;return we(),window.fetch=async function(a,c){let l=performance.now(),p=typeof a=="string"?a:a instanceof URL?a.href:a.url,d=(c?.method??"GET").toUpperCase(),h=Re(c?.headers,u),g=Se(c?.body),_=_e(c?.body),R;i&&c?.body&&(R=be(c.body,s));let T=`${d}:${p}:${l}`;if(L.size>=he){let v=L.keys().next().value;v!==void 0&&L.delete(v)}L.set(T,Date.now());try{let v=await r.call(window,a,c),k=performance.now()-l,D=parseInt(v.headers.get("content-length")||"0",10),C=Ee(v.headers,u),w;if(i)try{let N=await v.clone().text();w=N.length>s?N.slice(0,s):N}catch{}let E={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"network",url:p,method:d,status:v.status,requestHeaders:h,responseHeaders:C,requestBodySize:g,responseBodySize:D,duration:k,ttfb:k,graphqlOperation:_,requestBody:R,responseBody:w,source:"fetch"};if(n?.beforeSend){let I=n.beforeSend(E);I&&t(I)}else t(E);return v}catch(v){let k=performance.now()-l,D="error",C="";v instanceof DOMException&&v.name==="AbortError"?(D="abort",C="Request aborted"):v instanceof Error&&(C=v.message);let w={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"network",url:p,method:d,status:0,requestHeaders:h,responseHeaders:{},requestBodySize:g,responseBodySize:0,duration:k,ttfb:0,graphqlOperation:_,requestBody:R,errorPhase:D,errorMessage:C,source:"fetch"};if(n?.beforeSend){let E=n.beforeSend(w);E&&t(E)}else t(w);throw v}},()=>{window.fetch=r,ye()}}function Re(t,e){let o={};if(!t)return o;if(t instanceof Headers)t.forEach((n,r)=>{o[r]=e.has(r.toLowerCase())?"[REDACTED]":n});else if(Array.isArray(t))for(let[n,r]of t)o[n]=e.has(n.toLowerCase())?"[REDACTED]":r;else for(let[n,r]of Object.entries(t))o[n]=e.has(n.toLowerCase())?"[REDACTED]":r;return o}function Ee(t,e){let o={};return t.forEach((n,r)=>{o[r]=e.has(r.toLowerCase())?"[REDACTED]":n}),o}function Se(t){return t?typeof t=="string"?new Blob([t]).size:t instanceof Blob?t.size:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:t instanceof FormData?0:t instanceof URLSearchParams?new Blob([t.toString()]).size:0:0}function be(t,e){if(t){if(typeof t=="string")return t.length>e?t.slice(0,e):t;if(t instanceof URLSearchParams){let o=t.toString();return o.length>e?o.slice(0,e):o}if(t instanceof FormData)return"[FormData]";if(t instanceof Blob)return`[Blob ${t.size} bytes]`;if(t instanceof ArrayBuffer)return`[ArrayBuffer ${t.byteLength} bytes]`;if(ArrayBuffer.isView(t))return`[TypedArray ${t.byteLength} bytes]`}}function _e(t){if(!(!t||typeof t!="string"))try{let e=JSON.parse(t);if(typeof e.query=="string"){let o=e.query.trim(),n="query";o.startsWith("mutation")?n="mutation":o.startsWith("subscription")&&(n="subscription");let r=e.operationName||Te(o)||"anonymous";return{type:n,name:r}}}catch{}}function Te(t){return t.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function y(t,e=5){let o=new WeakSet;function n(r,u){if(u>e)return"[max depth]";if(r==null)return r;if(typeof r=="function")return`[Function: ${r.name||"anonymous"}]`;if(typeof r=="symbol"||typeof r=="bigint")return r.toString();if(typeof r!="object")return r;if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return r.toString();if(o.has(r))return"[Circular]";if(o.add(r),Array.isArray(r))return r.map(c=>n(c,u+1));let i={},s;try{s=Object.keys(r)}catch{return"[Object]"}let a=50;for(let c=0;c<Math.min(s.length,a);c++)try{i[s[c]]=n(r[s[c]],u+1)}catch{i[s[c]]="[Error accessing property]"}return s.length>a&&(i["..."]=`${s.length-a} more keys`),i}return n(t,0)}var V=["log","warn","error","info","debug","trace"];function G(t){if(!t)return;let e=t.split(`
2
+ `).slice(3);for(let o of e){let n=o.match(/(?:at\s+)?(?:.*?\()?(.+?):(\d+):(\d+)\)?/);if(n&&!n[1].includes("interceptor")&&!n[1].includes("runtimescope"))return`${n[1]}:${n[2]}`}}function K(t,e,o){let n={},r=new Map,u=new Map;for(let d of V)n[d]=console[d].bind(console),console[d]=(...h)=>{let g=new Error().stack,_=h.map(T=>typeof T=="string"?T:Q(T)).join(" "),R={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:d,message:_,args:h.map(T=>y(T,3)),stackTrace:d==="error"||d==="trace"?g?.split(`
2
3
  `).slice(2).join(`
3
- `):void 0,sourceFile:void 0};if(n){let a=n(i);a&&e(a)}else e(i);r[s](...c)};return()=>{for(let s of V)console[s]=r[s]}}function _e(e){try{return JSON.stringify(e)}catch{return String(e)}}function Q(e,t,n,r){let s=new Set(n.map(l=>l.toLowerCase())),c=r?.captureBody??!1,o=r?.maxBodySize??65536,i=new AbortController,a=XMLHttpRequest.prototype.open,u=XMLHttpRequest.prototype.setRequestHeader,d=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(l,f){return this.__rs_method=l.toUpperCase(),this.__rs_url=typeof f=="string"?f:f.href,this.__rs_headers={},a.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(l,f){return this.__rs_headers&&(this.__rs_headers[l.toLowerCase()]=s.has(l.toLowerCase())?"[REDACTED]":f),u.call(this,l,f)},XMLHttpRequest.prototype.send=function(l){let f=this.__rs_method??"GET",b=this.__rs_url??"",g=`${f}:${b}`,T=!1;for(let v of C.keys())if(v.startsWith(g)){T=!0;break}if(T)return this.__rs_fetchIntercepted=!0,d.call(this,l);let D={...this.__rs_headers??{}},j=performance.now(),h,_=0;if(l){if(typeof l=="string")_=new Blob([l]).size,c&&(h=l.length>o?l.slice(0,o):l);else if(l instanceof Blob)_=l.size,c&&(h=`[Blob ${l.size} bytes]`);else if(l instanceof ArrayBuffer)_=l.byteLength,c&&(h=`[ArrayBuffer ${l.byteLength} bytes]`);else if(l instanceof FormData)c&&(h="[FormData]");else if(l instanceof URLSearchParams){let v=l.toString();_=new Blob([v]).size,c&&(h=v.length>o?v.slice(0,o):v)}}let L=Ie(l),I=v=>{let w={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"network",url:b,method:f,status:0,requestHeaders:D,responseHeaders:{},requestBodySize:_,responseBodySize:0,duration:0,ttfb:0,graphqlOperation:L,requestBody:h,source:"xhr",...v};if(r?.beforeSend){let S=r.beforeSend(w);S&&e(S)}else e(w)};return this.addEventListener("loadend",()=>{let v=performance.now()-j;if(this.status>0){let w=Te(this.getAllResponseHeaders(),s),S=parseInt(this.getResponseHeader("content-length")||"0",10),O;if(c&&(this.responseType===""||this.responseType==="text"))try{let U=this.responseText;O=U.length>o?U.slice(0,o):U}catch{}I({status:this.status,responseHeaders:w,responseBodySize:S,responseBody:O,duration:v,ttfb:v})}else{let w="error",S="Network error";this.readyState===0||this.status,this.timeout>0&&v>=this.timeout&&(w="timeout",S=`Request timed out after ${this.timeout}ms`),I({duration:v,errorPhase:w,errorMessage:S})}},{once:!0,signal:i.signal}),d.call(this,l)},()=>{i.abort(),XMLHttpRequest.prototype.open=a,XMLHttpRequest.prototype.setRequestHeader=u,XMLHttpRequest.prototype.send=d}}function Te(e,t){let n={};if(!e)return n;for(let r of e.trim().split(/[\r\n]+/)){let s=r.indexOf(":");if(s===-1)continue;let c=r.slice(0,s).trim().toLowerCase(),o=r.slice(s+1).trim();n[c]=t.has(c)?"[REDACTED]":o}return n}function Ie(e){if(!(!e||typeof e!="string"))try{let t=JSON.parse(e);if(typeof t.query=="string"){let n=t.query.trim(),r="query";n.startsWith("mutation")?r="mutation":n.startsWith("subscription")&&(r="subscription");let s=t.operationName||Ce(n)||"anonymous";return{type:r,name:s}}}catch{}}function Ce(e){return e.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function Y(e,t,n,r){let s=[],c=new Map;for(let[o,i]of Object.entries(n)){let a=ke(i);if(a==="zustand"){let u=i;B(e,t,r?.beforeSend,{storeId:o,library:a,phase:"init",state:y(u.getState(),4)});let d=u.subscribe((l,f)=>{let b=K(f,l);B(e,t,r?.beforeSend,{storeId:o,library:a,phase:"update",state:y(l,4),previousState:y(f,4),diff:b?y(b,3):void 0})});s.push(d)}else if(a==="redux"){let u=i;B(e,t,r?.beforeSend,{storeId:o,library:a,phase:"init",state:y(u.getState(),4)});let d,l=u.dispatch.bind(u);c.set(o,l),u.dispatch=g=>(g&&typeof g=="object"&&"type"in g&&(d={type:String(g.type),payload:g.payload}),l(g));let f=u.getState(),b=u.subscribe(()=>{let g=u.getState(),T=K(f,g);B(e,t,r?.beforeSend,{storeId:o,library:a,phase:"update",state:y(g,4),previousState:y(f,4),diff:T?y(T,3):void 0,action:d?y(d,3):void 0}),f=g,d=void 0});s.push(b)}}return()=>{for(let o of s)o();for(let[o,i]of c){let a=n[o];a&&(a.dispatch=i)}}}function ke(e){if(!e||typeof e!="object")return"unknown";let t=e;return typeof t.getState=="function"&&typeof t.setState=="function"&&typeof t.subscribe=="function"?"zustand":typeof t.dispatch=="function"&&typeof t.getState=="function"&&typeof t.subscribe=="function"?"redux":"unknown"}function K(e,t){if(!e||!t||typeof e!="object"||typeof t!="object")return null;let n={},r=e,s=t,c=new Set([...Object.keys(r),...Object.keys(s)]);for(let o of c)r[o]!==s[o]&&(n[o]={from:r[o],to:s[o]});return Object.keys(n).length>0?n:null}function B(e,t,n,r){let s={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"state",...r};if(n){let c=n(s);c&&e(c)}else e(s)}var Le={LCP:[2500,4e3],FCP:[1800,3e3],CLS:[.1,.25],TTFB:[800,1800],FID:[100,300],INP:[200,500]};function Oe(e,t){let[n,r]=Le[e]??[1/0,1/0];return t<=n?"good":t<=r?"needs-improvement":"poor"}var H=null;function J(e,t,n){if(H)for(let i of H)try{i.disconnect()}catch{}let r=[];H=r;let s=(i,a,u)=>{let d={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"performance",metricName:i,value:Math.round(a*100)/100,rating:Oe(i,a),element:u};if(n?.beforeSend){let l=n.beforeSend(d);l&&e(l)}else e(d)};N(r,"largest-contentful-paint",i=>{let a=i[i.length-1];if(!a)return;let u=a.element;s("LCP",a.startTime,u?.tagName?.toLowerCase())}),N(r,"paint",i=>{for(let a of i)a.name==="first-contentful-paint"&&s("FCP",a.startTime)});let c=0;N(r,"layout-shift",i=>{for(let a of i){let u=a;!u.hadRecentInput&&u.value&&(c+=u.value,s("CLS",c))}}),N(r,"first-input",i=>{let a=i[0];if(!a)return;let u=a;u.processingStart&&s("FID",u.processingStart-a.startTime)}),N(r,"navigation",i=>{let a=i[0];a&&s("TTFB",a.responseStart-a.requestStart)});let o=0;return N(r,"event",i=>{for(let a of i)a.duration>o&&(o=a.duration,s("INP",o))},{durationThreshold:16}),()=>{for(let i of r)try{i.disconnect()}catch{}H===r&&(H=null)}}function N(e,t,n,r){try{let s=new PerformanceObserver(c=>{n(c.getEntries())});s.observe({type:t,buffered:!0,...r}),e.push(s)}catch{}}var Ne=0,De=1,te=1e4,Z=100,xe=6e4,ee=500;function ne(e,t,n){let r=new Map,s=n?.snapshotIntervalMs??5e3,c=null,o=He();if(!o)return()=>{};let i=o.onCommitFiberRoot;return o._runtimescope_original=i,o.onCommitFiberRoot=(a,u)=>{if(i)try{i(a,u)}catch{}u.current&&X(u.current,r)},c=setInterval(()=>{Be(r,e,t,n?.beforeSend)},s),()=>{c&&(clearInterval(c),c=null),o&&(o._runtimescope_original?o.onCommitFiberRoot=o._runtimescope_original:delete o.onCommitFiberRoot,delete o._runtimescope_original)}}function He(){if(typeof window>"u")return null;let e=window;return e.__REACT_DEVTOOLS_GLOBAL_HOOK__||(e.__REACT_DEVTOOLS_GLOBAL_HOOK__={}),e.__REACT_DEVTOOLS_GLOBAL_HOOK__}function X(e,t){Ae(e,t),e.child&&X(e.child,t),e.sibling&&X(e.sibling,t)}function Ae(e,t){if(e.tag!==Ne&&e.tag!==De)return;let n=Me(e);if(!n)return;let r=Date.now(),s=e.alternate===null,c=e.actualDuration??0,o=Fe(e,s),i=t.get(n);i||(i={renderCount:0,totalDuration:0,lastRenderTime:0,lastRenderPhase:"mount",lastRenderCause:"unknown",renderTimestamps:[]},t.set(n,i)),i.renderCount++,i.totalDuration+=c,i.lastRenderTime=r,i.lastRenderPhase=s?"mount":"update",i.lastRenderCause=o??"unknown",i.renderTimestamps.push(r),i.renderTimestamps.length>Z&&(i.renderTimestamps=i.renderTimestamps.slice(-Z))}function Me(e){if(e.type&&typeof e.type!="string")return e.type.displayName||e.type.name||void 0}function Fe(e,t){return t?"props":e.alternate?e.memoizedProps!==e.alternate.memoizedProps?"props":e.memoizedState!==e.alternate.memoizedState?"state":"parent":"unknown"}function Pe(e){if(e.length<2)return 0;let t=Date.now(),n=t-te,r=e.filter(c=>c>=n);if(r.length<2)return 0;let s=t-r[0];return s===0?0:r.length/(s/1e3)}function Be(e,t,n,r){if(e.size===0)return;let s=[],c=[],o=0;for(let[u,d]of e){let l=Pe(d.renderTimestamps),f=l>4||d.renderCount>20;s.push({componentName:u,renderCount:d.renderCount,totalDuration:Math.round(d.totalDuration*100)/100,avgDuration:d.renderCount>0?Math.round(d.totalDuration/d.renderCount*100)/100:0,lastRenderPhase:d.lastRenderPhase,lastRenderCause:d.lastRenderCause,renderVelocity:Math.round(l*100)/100,suspicious:f}),f&&c.push(u),o+=d.renderCount}s.sort((u,d)=>d.renderCount-u.renderCount);let i={eventId:m(),sessionId:n,timestamp:Date.now(),eventType:"render",profiles:s,snapshotWindowMs:te,totalRenders:o,suspiciousComponents:c};if(r){let u=r(i);u&&t(u)}else t(i);let a=Date.now();for(let[u,d]of e)a-d.lastRenderTime>xe?e.delete(u):(d.renderCount=0,d.totalDuration=0);if(e.size>ee){let u=[...e.entries()].sort((l,f)=>l[1].lastRenderTime-f[1].lastRenderTime),d=e.size-ee;for(let l=0;l<d;l++)e.delete(u[l][0])}}function re(e,t,n){let r=c=>{let o,i,a;if(c instanceof ErrorEvent)o=c.message||"Uncaught error",i=c.error?.stack,a=c.filename?`${c.filename}:${c.lineno}:${c.colno}`:void 0;else{let d=c.target;if(d&&d!==window){let l=d.tagName?.toLowerCase()??"unknown",f=d.src??d.src??d.href??"unknown";o=`Failed to load resource: <${l}> ${f}`}else return}let u={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:`[Uncaught] ${o}`,args:[y(o,3)],stackTrace:i,sourceFile:a};if(n){let d=n(u);d&&e(d)}else e(u)},s=c=>{let o=c.reason,i,a;if(o instanceof Error)i=o.message,a=o.stack;else if(typeof o=="string")i=o;else try{i=JSON.stringify(o)}catch{i=String(o)}let u={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:`[Unhandled Rejection] ${i}`,args:[y(o,3)],stackTrace:a,sourceFile:void 0};if(n){let d=n(u);d&&e(d)}else e(u)};return window.addEventListener("error",r,!0),window.addEventListener("unhandledrejection",s),()=>{window.removeEventListener("error",r,!0),window.removeEventListener("unhandledrejection",s)}}function se(e,t){let n=window.location.href;function r(a,u){let d=n;d!==a&&(n=a,e({eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"navigation",from:d,to:a,trigger:u}))}let s=history.pushState.bind(history),c=history.replaceState.bind(history);history.pushState=function(...a){s(...a),r(window.location.href,"pushState")},history.replaceState=function(...a){c(...a),r(window.location.href,"replaceState")};let o=()=>r(window.location.href,"popstate");window.addEventListener("popstate",o);let i=()=>r(window.location.href,"hashchange");return window.addEventListener("hashchange",i),()=>{history.pushState=s,history.replaceState=c,window.removeEventListener("popstate",o),window.removeEventListener("hashchange",i)}}function oe(e,t){let n=r=>{let s=r.target;if(!(s instanceof Element)||s.closest("[data-runtimescope]"))return;let c=qe(s),o=ze(s),i={eventId:m(),sessionId:t,timestamp:Date.now(),eventType:"ui",action:"click",target:c,...o&&{text:o}};e(i)};return document.addEventListener("click",n,!0),()=>{document.removeEventListener("click",n,!0)}}function qe(e){let t=e.tagName.toLowerCase();if(e.id)return`${t}#${e.id}`;let n=e.getAttribute("data-testid")??e.getAttribute("data-test-id");if(n)return`${t}[data-testid="${n}"]`;let r=e.getAttribute("role"),s=e.getAttribute("aria-label");if(r&&s)return`${t}[role="${r}"][aria-label="${s}"]`;let c=e.className;if(typeof c=="string"&&c.trim()){let i=c.split(/\s+/).find(a=>a.length>2&&!a.startsWith("_")&&!a.includes("__"));if(i)return`${t}.${i}`}let o=e.parentElement;if(o){let i=o.children,a=Array.from(i).filter(u=>u.tagName===e.tagName);if(a.length>1){let u=a.indexOf(e)+1;return`${t}:nth-child(${u})`}}return t}function ze(e){let t=e.getAttribute("aria-label");if(t)return t.slice(0,80);let n=e.innerText??e.textContent;if(!n)return;let r=n.trim().replace(/\s+/g," ");if(r.length!==0)return r.length>80?r.slice(0,77)+"...":r}var q="0.9.0",A=console.debug.bind(console),z=Symbol.for("__runtimescope_originals__");function je(){let e=globalThis;return e[z]||(e[z]={fetch:window.fetch,xhrOpen:XMLHttpRequest.prototype.open,xhrSend:XMLHttpRequest.prototype.send,xhrSetRequestHeader:XMLHttpRequest.prototype.setRequestHeader,consoleMethods:{log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console),debug:console.debug.bind(console),trace:console.trace.bind(console)}}),e[z]}var E=class{static get sessionId(){return this._sessionId}static get isConnected(){return this._state==="started"}static shouldSample(){if(this._sampleRate<1&&Math.random()>this._sampleRate)return!1;if(this._maxEventsPerSecond!==void 0){let t=Date.now();if(t-this._windowStart>=1e3&&(this._windowCount=0,this._windowStart=t),this._windowCount>=this._maxEventsPerSecond)return!1;this._windowCount++}return!0}static connect(t={}){if(t.enabled===!1)return;this._state==="started"&&(A("[RuntimeScope] Already connected \u2014 disconnecting before re-init"),this.disconnect());let n={serverUrl:t.serverUrl??t.endpoint??"ws://localhost:9090",appName:t.appName??"unknown",captureNetwork:t.captureNetwork??!0,captureConsole:t.captureConsole??!0,captureXhr:t.captureXhr??!0,captureBody:t.captureBody??!1,maxBodySize:t.maxBodySize??65536,capturePerformance:t.capturePerformance??!0,captureRenders:t.captureRenders??!0,captureNavigation:t.captureNavigation??!0,captureClicks:t.captureClicks??!0,stores:t.stores??{},beforeSend:t.beforeSend,redactHeaders:t.redactHeaders??["authorization","cookie"],batchSize:t.batchSize??50,flushIntervalMs:t.flushIntervalMs??100};je(),this._sessionId=$(),this._state="started",this.transport=new F({serverUrl:n.serverUrl,appName:n.appName,sessionId:this._sessionId,sdkVersion:q,authToken:t.authToken,projectId:t.projectId,batchSize:n.batchSize,flushIntervalMs:n.flushIntervalMs}),this._sampleRate=t.sampleRate??1,this._maxEventsPerSecond=t.maxEventsPerSecond,this._windowCount=0,this._windowStart=Date.now(),this._user=t.user,this.transport.connect(),A(`[RuntimeScope] SDK v${q} initializing \u2014 app: ${n.appName}, server: ${n.serverUrl}`);let r=o=>{o.eventType!=="session"&&o.eventType!=="custom"&&o.eventType!=="ui"&&!this.shouldSample()||this.transport?.send(o)};r({eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"session",appName:n.appName,connectedAt:Date.now(),sdkVersion:q,buildMeta:t.buildMeta,user:this._user,projectId:t.projectId});let s=this._sessionId;this.transport.onCommand(o=>{this.handleCommand(o,r,s)}),n.captureNetwork&&this.restoreFns.push(W(r,this._sessionId,n.redactHeaders,{captureBody:n.captureBody,maxBodySize:n.maxBodySize,beforeSend:n.beforeSend})),n.captureXhr&&this.restoreFns.push(Q(r,this._sessionId,n.redactHeaders,{captureBody:n.captureBody,maxBodySize:n.maxBodySize,beforeSend:n.beforeSend})),n.captureConsole&&(this.restoreFns.push(G(r,this._sessionId,n.beforeSend)),this.restoreFns.push(re(r,this._sessionId,n.beforeSend))),Object.keys(n.stores).length>0&&this.restoreFns.push(Y(r,this._sessionId,n.stores,{beforeSend:n.beforeSend})),n.capturePerformance&&this.restoreFns.push(J(r,this._sessionId,{beforeSend:n.beforeSend})),n.captureRenders&&this.restoreFns.push(ne(r,this._sessionId,{beforeSend:n.beforeSend})),n.captureNavigation&&this.restoreFns.push(se(r,this._sessionId)),n.captureClicks&&this.restoreFns.push(oe(r,this._sessionId));let c=[n.captureNetwork&&"fetch",n.captureXhr&&"xhr",n.captureConsole&&"console, errors",Object.keys(n.stores).length>0&&"state",n.capturePerformance&&"performance",n.captureRenders&&"renders",n.captureNavigation&&"navigation",n.captureClicks&&"clicks"].filter(Boolean);A(`[RuntimeScope] Interceptors active \u2014 ${c.join(", ")}`),this._sampleRate<1&&A(`[RuntimeScope] Sampling at ${(this._sampleRate*100).toFixed(0)}%`),this._maxEventsPerSecond!==void 0&&A(`[RuntimeScope] Rate limited to ${this._maxEventsPerSecond} events/sec`)}static handleCommand(t,n,r){if(t.command==="capture_dom_snapshot"){let s=t.params?.maxSize??5e5,c=document.documentElement.outerHTML,o=c.length>s;o&&(c=c.slice(0,s));let i={eventId:m(),sessionId:r,timestamp:Date.now(),eventType:"dom_snapshot",html:c,url:window.location.href,viewport:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},elementCount:document.querySelectorAll("*").length,truncated:o};n(i),this.transport?.sendCommandResponse(t.requestId,t.command,i)}else this.transport?.sendCommandResponse(t.requestId,t.command,{error:"Unknown command"})}static init(t={}){return this.connect(t)}static track(t,n){if(!this.transport||!this._sessionId)return;let r={eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"custom",name:t,properties:n};this.transport.send(r)}static setUser(t){this._user=t??void 0,this.transport&&this._sessionId&&this.transport.send({eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"session",appName:"user_update",connectedAt:Date.now(),sdkVersion:q,user:this._user})}static addBreadcrumb(t,n){if(!this.transport||!this._sessionId)return;let r={eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"ui",action:"breadcrumb",target:"manual",text:t,...n&&{data:n}};this.transport.send(r)}static disconnect(){for(let n of this.restoreFns)try{n()}catch{}this.restoreFns=[];let t=globalThis[z];if(t){window.fetch!==t.fetch&&(window.fetch=t.fetch);for(let[n,r]of Object.entries(t.consoleMethods)){let s=console;s[n]!==r&&(s[n]=r)}}this.transport?.disconnect(),this.transport=null,this._sessionId=null,this._state="stopped"}};p(E,"transport",null),p(E,"restoreFns",[]),p(E,"_sessionId",null),p(E,"_state","stopped"),p(E,"_sampleRate",1),p(E,"_maxEventsPerSecond"),p(E,"_windowCount",0),p(E,"_windowStart",0),p(E,"_user");var Ue=E;0&&(module.exports={RuntimeScope});
4
+ `):void 0,sourceFile:G(g),source:"browser"};if(o){let T=o(R);T&&t(T)}else t(R);n[d](...h)};let i=console.assert?.bind(console);i&&(console.assert=(d,...h)=>{if(!d){let g=new Error().stack,_=`Assertion failed: ${h.map(R=>typeof R=="string"?R:Q(R)).join(" ")}`;t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"error",message:_,args:h.map(R=>y(R,3)),stackTrace:g?.split(`
5
+ `).slice(2).join(`
6
+ `),sourceFile:G(g),source:"browser"})}i(d,...h)});let s=console.time?.bind(console),a=console.timeEnd?.bind(console);s&&(console.time=(d="default")=>{r.set(d,performance.now()),s(d)}),a&&(console.timeEnd=(d="default")=>{let h=r.get(d);if(h!==void 0){let g=performance.now()-h;r.delete(d),t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"info",message:`${d}: ${g.toFixed(2)}ms`,args:[{label:d,duration:g}],source:"browser"})}a(d)});let c=console.count?.bind(console),l=console.countReset?.bind(console);c&&(console.count=(d="default")=>{let h=(u.get(d)??0)+1;u.set(d,h),t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"info",message:`${d}: ${h}`,args:[{label:d,count:h}],source:"browser"}),c(d)}),l&&(console.countReset=(d="default")=>{u.delete(d),l(d)});let p=console.table?.bind(console);return p&&(console.table=(d,h)=>{t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"info",message:`[table] ${Array.isArray(d)?`${d.length} rows`:typeof d}`,args:[y(d,3)],source:"browser"}),p(d,h)}),()=>{for(let d of V)console[d]=n[d];i&&(console.assert=i),s&&(console.time=s),a&&(console.timeEnd=a),c&&(console.count=c),l&&(console.countReset=l),p&&(console.table=p)}}function Q(t){try{return JSON.stringify(t)}catch{return String(t)}}function Y(t,e,o,n){let r=new Set(o.map(p=>p.toLowerCase())),u=n?.captureBody??!1,i=n?.maxBodySize??65536,s=new AbortController,a=XMLHttpRequest.prototype.open,c=XMLHttpRequest.prototype.setRequestHeader,l=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(p,d){return this.__rs_method=p.toUpperCase(),this.__rs_url=typeof d=="string"?d:d.href,this.__rs_headers={},a.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(p,d){return this.__rs_headers&&(this.__rs_headers[p.toLowerCase()]=r.has(p.toLowerCase())?"[REDACTED]":d),c.call(this,p,d)},XMLHttpRequest.prototype.send=function(p){let d=this.__rs_method??"GET",h=this.__rs_url??"",g=`${d}:${h}`,_=!1;for(let w of L.keys())if(w.startsWith(g)){_=!0;break}if(_)return this.__rs_fetchIntercepted=!0,l.call(this,p);let R={...this.__rs_headers??{}},T=performance.now(),v,k=0;if(p){if(typeof p=="string")k=new Blob([p]).size,u&&(v=p.length>i?p.slice(0,i):p);else if(p instanceof Blob)k=p.size,u&&(v=`[Blob ${p.size} bytes]`);else if(p instanceof ArrayBuffer)k=p.byteLength,u&&(v=`[ArrayBuffer ${p.byteLength} bytes]`);else if(p instanceof FormData)u&&(v="[FormData]");else if(p instanceof URLSearchParams){let w=p.toString();k=new Blob([w]).size,u&&(v=w.length>i?w.slice(0,i):w)}}let D=ke(p),C=w=>{let E={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"network",url:h,method:d,status:0,requestHeaders:R,responseHeaders:{},requestBodySize:k,responseBodySize:0,duration:0,ttfb:0,graphqlOperation:D,requestBody:v,source:"xhr",...w};if(n?.beforeSend){let I=n.beforeSend(E);I&&t(I)}else t(E)};return this.addEventListener("loadend",()=>{let w=performance.now()-T;if(this.status>0){let E=Ie(this.getAllResponseHeaders(),r),I=parseInt(this.getResponseHeader("content-length")||"0",10),N;if(u&&(this.responseType===""||this.responseType==="text"))try{let $=this.responseText;N=$.length>i?$.slice(0,i):$}catch{}C({status:this.status,responseHeaders:E,responseBodySize:I,responseBody:N,duration:w,ttfb:w})}else{let E="error",I="Network error";this.readyState===0||this.status,this.timeout>0&&w>=this.timeout&&(E="timeout",I=`Request timed out after ${this.timeout}ms`),C({duration:w,errorPhase:E,errorMessage:I})}},{once:!0,signal:s.signal}),l.call(this,p)},()=>{s.abort(),XMLHttpRequest.prototype.open=a,XMLHttpRequest.prototype.setRequestHeader=c,XMLHttpRequest.prototype.send=l}}function Ie(t,e){let o={};if(!t)return o;for(let n of t.trim().split(/[\r\n]+/)){let r=n.indexOf(":");if(r===-1)continue;let u=n.slice(0,r).trim().toLowerCase(),i=n.slice(r+1).trim();o[u]=e.has(u)?"[REDACTED]":i}return o}function ke(t){if(!(!t||typeof t!="string"))try{let e=JSON.parse(t);if(typeof e.query=="string"){let o=e.query.trim(),n="query";o.startsWith("mutation")?n="mutation":o.startsWith("subscription")&&(n="subscription");let r=e.operationName||Ce(o)||"anonymous";return{type:n,name:r}}}catch{}}function Ce(t){return t.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function Z(t,e,o,n){let r=[],u=new Map;for(let[i,s]of Object.entries(o)){let a=Le(s);if(a==="zustand"){let c=s;q(t,e,n?.beforeSend,{storeId:i,library:a,phase:"init",state:y(c.getState(),4)});let l=c.subscribe((p,d)=>{let h=J(d,p);q(t,e,n?.beforeSend,{storeId:i,library:a,phase:"update",state:y(p,4),previousState:y(d,4),diff:h?y(h,3):void 0})});r.push(l)}else if(a==="redux"){let c=s;q(t,e,n?.beforeSend,{storeId:i,library:a,phase:"init",state:y(c.getState(),4)});let l,p=c.dispatch.bind(c);u.set(i,p),c.dispatch=g=>(g&&typeof g=="object"&&"type"in g&&(l={type:String(g.type),payload:g.payload}),p(g));let d=c.getState(),h=c.subscribe(()=>{let g=c.getState(),_=J(d,g);q(t,e,n?.beforeSend,{storeId:i,library:a,phase:"update",state:y(g,4),previousState:y(d,4),diff:_?y(_,3):void 0,action:l?y(l,3):void 0}),d=g,l=void 0});r.push(h)}}return()=>{for(let i of r)i();for(let[i,s]of u){let a=o[i];a&&(a.dispatch=s)}}}function Le(t){if(!t||typeof t!="object")return"unknown";let e=t;return typeof e.getState=="function"&&typeof e.setState=="function"&&typeof e.subscribe=="function"?"zustand":typeof e.dispatch=="function"&&typeof e.getState=="function"&&typeof e.subscribe=="function"?"redux":"unknown"}function J(t,e){if(!t||!e||typeof t!="object"||typeof e!="object")return null;let o={},n=t,r=e,u=new Set([...Object.keys(n),...Object.keys(r)]);for(let i of u)n[i]!==r[i]&&(o[i]={from:n[i],to:r[i]});return Object.keys(o).length>0?o:null}function q(t,e,o,n){let r={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"state",...n};if(o){let u=o(r);u&&t(u)}else t(r)}var Oe={LCP:[2500,4e3],FCP:[1800,3e3],CLS:[.1,.25],TTFB:[800,1800],FID:[100,300],INP:[200,500]};function De(t,e){let[o,n]=Oe[t]??[1/0,1/0];return e<=o?"good":e<=n?"needs-improvement":"poor"}var F=null;function ee(t,e,o){if(F)for(let s of F)try{s.disconnect()}catch{}let n=[];F=n;let r=(s,a,c)=>{let l={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"performance",metricName:s,value:Math.round(a*100)/100,rating:De(s,a),element:c};if(o?.beforeSend){let p=o.beforeSend(l);p&&t(p)}else t(l)};x(n,"largest-contentful-paint",s=>{let a=s[s.length-1];if(!a)return;let c=a.element;r("LCP",a.startTime,c?.tagName?.toLowerCase())}),x(n,"paint",s=>{for(let a of s)a.name==="first-contentful-paint"&&r("FCP",a.startTime)});let u=0;x(n,"layout-shift",s=>{for(let a of s){let c=a;!c.hadRecentInput&&c.value&&(u+=c.value,r("CLS",u))}}),x(n,"first-input",s=>{let a=s[0];if(!a)return;let c=a;c.processingStart&&r("FID",c.processingStart-a.startTime)}),x(n,"navigation",s=>{let a=s[0];a&&r("TTFB",a.responseStart-a.requestStart)});let i=0;return x(n,"event",s=>{for(let a of s)a.duration>i&&(i=a.duration,r("INP",i))},{durationThreshold:16}),()=>{for(let s of n)try{s.disconnect()}catch{}F===n&&(F=null)}}function x(t,e,o,n){try{let r=new PerformanceObserver(u=>{o(u.getEntries())});r.observe({type:e,buffered:!0,...n}),t.push(r)}catch{}}var Ne=0,xe=1,re=1e4,te=100,Ae=6e4,ne=500;function oe(t,e,o){let n=new Map,r=o?.snapshotIntervalMs??5e3,u=null,i=He();if(!i)return()=>{};let s=i.onCommitFiberRoot;return i._runtimescope_original=s,i.onCommitFiberRoot=(a,c)=>{if(s)try{s(a,c)}catch{}c.current&&U(c.current,n)},u=setInterval(()=>{qe(n,t,e,o?.beforeSend)},r),()=>{u&&(clearInterval(u),u=null),i&&(i._runtimescope_original?i.onCommitFiberRoot=i._runtimescope_original:delete i.onCommitFiberRoot,delete i._runtimescope_original)}}function He(){if(typeof window>"u")return null;let t=window;return t.__REACT_DEVTOOLS_GLOBAL_HOOK__||(t.__REACT_DEVTOOLS_GLOBAL_HOOK__={}),t.__REACT_DEVTOOLS_GLOBAL_HOOK__}function U(t,e){Fe(t,e),t.child&&U(t.child,e),t.sibling&&U(t.sibling,e)}function Fe(t,e){if(t.tag!==Ne&&t.tag!==xe)return;let o=Me(t);if(!o)return;let n=Date.now(),r=t.alternate===null,u=t.actualDuration??0,i=Pe(t,r),s=e.get(o);s||(s={renderCount:0,totalDuration:0,lastRenderTime:0,lastRenderPhase:"mount",lastRenderCause:"unknown",renderTimestamps:[]},e.set(o,s)),s.renderCount++,s.totalDuration+=u,s.lastRenderTime=n,s.lastRenderPhase=r?"mount":"update",s.lastRenderCause=i??"unknown",s.renderTimestamps.push(n),s.renderTimestamps.length>te&&(s.renderTimestamps=s.renderTimestamps.slice(-te))}function Me(t){if(t.type&&typeof t.type!="string")return t.type.displayName||t.type.name||void 0}function Pe(t,e){return e?"props":t.alternate?t.memoizedProps!==t.alternate.memoizedProps?"props":t.memoizedState!==t.alternate.memoizedState?"state":"parent":"unknown"}function Be(t){if(t.length<2)return 0;let e=Date.now(),o=e-re,n=t.filter(u=>u>=o);if(n.length<2)return 0;let r=e-n[0];return r===0?0:n.length/(r/1e3)}function qe(t,e,o,n){if(t.size===0)return;let r=[],u=[],i=0;for(let[c,l]of t){let p=Be(l.renderTimestamps),d=p>4||l.renderCount>20;r.push({componentName:c,renderCount:l.renderCount,totalDuration:Math.round(l.totalDuration*100)/100,avgDuration:l.renderCount>0?Math.round(l.totalDuration/l.renderCount*100)/100:0,lastRenderPhase:l.lastRenderPhase,lastRenderCause:l.lastRenderCause,renderVelocity:Math.round(p*100)/100,suspicious:d}),d&&u.push(c),i+=l.renderCount}r.sort((c,l)=>l.renderCount-c.renderCount);let s={eventId:m(),sessionId:o,timestamp:Date.now(),eventType:"render",profiles:r,snapshotWindowMs:re,totalRenders:i,suspiciousComponents:u};if(n){let c=n(s);c&&e(c)}else e(s);let a=Date.now();for(let[c,l]of t)a-l.lastRenderTime>Ae?t.delete(c):(l.renderCount=0,l.totalDuration=0);if(t.size>ne){let c=[...t.entries()].sort((p,d)=>p[1].lastRenderTime-d[1].lastRenderTime),l=t.size-ne;for(let p=0;p<l;p++)t.delete(c[p][0])}}function se(t,e,o){let n=u=>{let i,s,a;if(u instanceof ErrorEvent)i=u.message||"Uncaught error",s=u.error?.stack,a=u.filename?`${u.filename}:${u.lineno}:${u.colno}`:void 0;else{let l=u.target;if(l&&l!==window){let p=l.tagName?.toLowerCase()??"unknown",d=l.src??l.src??l.href??"unknown";i=`Failed to load resource: <${p}> ${d}`}else return}let c={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"error",message:`[Uncaught] ${i}`,args:[y(i,3)],stackTrace:s,sourceFile:a};if(o){let l=o(c);l&&t(l)}else t(c)},r=u=>{let i=u.reason,s,a;if(i instanceof Error)s=i.message,a=i.stack;else if(typeof i=="string")s=i;else try{s=JSON.stringify(i)}catch{s=String(i)}let c={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"console",level:"error",message:`[Unhandled Rejection] ${s}`,args:[y(i,3)],stackTrace:a,sourceFile:void 0};if(o){let l=o(c);l&&t(l)}else t(c)};return window.addEventListener("error",n,!0),window.addEventListener("unhandledrejection",r),()=>{window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",r)}}function ie(t,e){let o=window.location.href;function n(a,c){let l=o;l!==a&&(o=a,t({eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"navigation",from:l,to:a,trigger:c}))}let r=history.pushState.bind(history),u=history.replaceState.bind(history);history.pushState=function(...a){r(...a),n(window.location.href,"pushState")},history.replaceState=function(...a){u(...a),n(window.location.href,"replaceState")};let i=()=>n(window.location.href,"popstate");window.addEventListener("popstate",i);let s=()=>n(window.location.href,"hashchange");return window.addEventListener("hashchange",s),()=>{history.pushState=r,history.replaceState=u,window.removeEventListener("popstate",i),window.removeEventListener("hashchange",s)}}function ae(t,e){let o=n=>{let r=n.target;if(!(r instanceof Element)||r.closest("[data-runtimescope]"))return;let u=ze(r),i=je(r),s={eventId:m(),sessionId:e,timestamp:Date.now(),eventType:"ui",action:"click",target:u,...i&&{text:i}};t(s)};return document.addEventListener("click",o,!0),()=>{document.removeEventListener("click",o,!0)}}function ze(t){let e=t.tagName.toLowerCase();if(t.id)return`${e}#${t.id}`;let o=t.getAttribute("data-testid")??t.getAttribute("data-test-id");if(o)return`${e}[data-testid="${o}"]`;let n=t.getAttribute("role"),r=t.getAttribute("aria-label");if(n&&r)return`${e}[role="${n}"][aria-label="${r}"]`;let u=t.className;if(typeof u=="string"&&u.trim()){let s=u.split(/\s+/).find(a=>a.length>2&&!a.startsWith("_")&&!a.includes("__"));if(s)return`${e}.${s}`}let i=t.parentElement;if(i){let s=i.children,a=Array.from(s).filter(c=>c.tagName===t.tagName);if(a.length>1){let c=a.indexOf(t)+1;return`${e}:nth-child(${c})`}}return e}function je(t){let e=t.getAttribute("aria-label");if(e)return e.slice(0,80);let o=t.innerText??t.textContent;if(!o)return;let n=o.trim().replace(/\s+/g," ");if(n.length!==0)return n.length>80?n.slice(0,77)+"...":n}var z="0.9.2",A=console.debug.bind(console),j=Symbol.for("__runtimescope_originals__");function $e(){let t=globalThis;return t[j]||(t[j]={fetch:window.fetch,xhrOpen:XMLHttpRequest.prototype.open,xhrSend:XMLHttpRequest.prototype.send,xhrSetRequestHeader:XMLHttpRequest.prototype.setRequestHeader,consoleMethods:{log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console),debug:console.debug.bind(console),trace:console.trace.bind(console)}}),t[j]}var b=class{static get sessionId(){return this._sessionId}static get isConnected(){return this._state==="started"}static shouldSample(){if(this._sampleRate<1&&Math.random()>this._sampleRate)return!1;if(this._maxEventsPerSecond!==void 0){let e=Date.now();if(e-this._windowStart>=1e3&&(this._windowCount=0,this._windowStart=e),this._windowCount>=this._maxEventsPerSecond)return!1;this._windowCount++}return!0}static connect(e={}){if(e.enabled===!1)return;if(!!!(e.serverUrl||e.endpoint)&&typeof window<"u"){let s=window.location?.hostname;if(s&&s!=="localhost"&&s!=="127.0.0.1"&&!s.startsWith("192.168.")&&!s.startsWith("10.")){A("[RuntimeScope] No endpoint configured and not on localhost \u2014 SDK disabled for production");return}}this._state==="started"&&(A("[RuntimeScope] Already connected \u2014 disconnecting before re-init"),this.disconnect());let n={serverUrl:e.serverUrl??e.endpoint??"ws://localhost:9090",appName:e.appName??"unknown",captureNetwork:e.captureNetwork??!0,captureConsole:e.captureConsole??!0,captureXhr:e.captureXhr??!0,captureBody:e.captureBody??!1,maxBodySize:e.maxBodySize??65536,capturePerformance:e.capturePerformance??!0,captureRenders:e.captureRenders??!0,captureNavigation:e.captureNavigation??!0,captureClicks:e.captureClicks??!0,stores:e.stores??{},beforeSend:e.beforeSend,redactHeaders:e.redactHeaders??["authorization","cookie"],batchSize:e.batchSize??50,flushIntervalMs:e.flushIntervalMs??100};$e(),this._sessionId=X(),this._state="started",this.transport=new P({serverUrl:n.serverUrl,appName:n.appName,sessionId:this._sessionId,sdkVersion:z,authToken:e.authToken,projectId:e.projectId,batchSize:n.batchSize,flushIntervalMs:n.flushIntervalMs}),this._sampleRate=e.sampleRate??1,this._maxEventsPerSecond=e.maxEventsPerSecond,this._windowCount=0,this._windowStart=Date.now(),this._user=e.user,this.transport.connect(),A(`[RuntimeScope] SDK v${z} initializing \u2014 app: ${n.appName}, server: ${n.serverUrl}`);let r=s=>{s.eventType!=="session"&&s.eventType!=="custom"&&s.eventType!=="ui"&&!this.shouldSample()||this.transport?.send(s)};r({eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"session",appName:n.appName,connectedAt:Date.now(),sdkVersion:z,buildMeta:e.buildMeta,user:this._user,projectId:e.projectId});let u=this._sessionId;this.transport.onCommand(s=>{this.handleCommand(s,r,u)}),n.captureNetwork&&this.restoreFns.push(W(r,this._sessionId,n.redactHeaders,{captureBody:n.captureBody,maxBodySize:n.maxBodySize,beforeSend:n.beforeSend})),n.captureXhr&&this.restoreFns.push(Y(r,this._sessionId,n.redactHeaders,{captureBody:n.captureBody,maxBodySize:n.maxBodySize,beforeSend:n.beforeSend})),n.captureConsole&&this.restoreFns.push(K(r,this._sessionId,n.beforeSend)),e.captureErrors!==!1&&this.restoreFns.push(se(r,this._sessionId,n.beforeSend)),Object.keys(n.stores).length>0&&this.restoreFns.push(Z(r,this._sessionId,n.stores,{beforeSend:n.beforeSend})),n.capturePerformance&&this.restoreFns.push(ee(r,this._sessionId,{beforeSend:n.beforeSend})),n.captureRenders&&this.restoreFns.push(oe(r,this._sessionId,{beforeSend:n.beforeSend})),n.captureNavigation&&this.restoreFns.push(ie(r,this._sessionId)),n.captureClicks&&this.restoreFns.push(ae(r,this._sessionId));let i=[n.captureNetwork&&"fetch",n.captureXhr&&"xhr",n.captureConsole&&"console, errors",Object.keys(n.stores).length>0&&"state",n.capturePerformance&&"performance",n.captureRenders&&"renders",n.captureNavigation&&"navigation",n.captureClicks&&"clicks"].filter(Boolean);A(`[RuntimeScope] Interceptors active \u2014 ${i.join(", ")}`),this._sampleRate<1&&A(`[RuntimeScope] Sampling at ${(this._sampleRate*100).toFixed(0)}%`),this._maxEventsPerSecond!==void 0&&A(`[RuntimeScope] Rate limited to ${this._maxEventsPerSecond} events/sec`)}static handleCommand(e,o,n){if(e.command==="capture_dom_snapshot"){let r=e.params?.maxSize??5e5,u=document.documentElement.outerHTML,i=u.length>r;i&&(u=u.slice(0,r));let s={eventId:m(),sessionId:n,timestamp:Date.now(),eventType:"dom_snapshot",html:u,url:window.location.href,viewport:{width:window.innerWidth,height:window.innerHeight},scrollPosition:{x:window.scrollX,y:window.scrollY},elementCount:document.querySelectorAll("*").length,truncated:i};o(s),this.transport?.sendCommandResponse(e.requestId,e.command,s)}else this.transport?.sendCommandResponse(e.requestId,e.command,{error:"Unknown command"})}static init(e={}){return this.connect(e)}static track(e,o){if(!this.transport||!this._sessionId)return;let n={eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"custom",name:e,properties:o};this.transport.send(n)}static setUser(e){this._user=e??void 0,this.transport&&this._sessionId&&this.transport.send({eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"session",appName:"user_update",connectedAt:Date.now(),sdkVersion:z,user:this._user})}static addBreadcrumb(e,o){if(!this.transport||!this._sessionId)return;let n={eventId:m(),sessionId:this._sessionId,timestamp:Date.now(),eventType:"ui",action:"breadcrumb",target:"manual",text:e,...o&&{data:o}};this.transport.send(n)}static disconnect(){for(let o of this.restoreFns)try{o()}catch{}this.restoreFns=[];let e=globalThis[j];if(e){window.fetch!==e.fetch&&(window.fetch=e.fetch);for(let[o,n]of Object.entries(e.consoleMethods)){let r=console;r[o]!==n&&(r[o]=n)}}this.transport?.disconnect(),this.transport=null,this._sessionId=null,this._state="stopped"}};f(b,"transport",null),f(b,"restoreFns",[]),f(b,"_sessionId",null),f(b,"_state","stopped"),f(b,"_sampleRate",1),f(b,"_maxEventsPerSecond"),f(b,"_windowCount",0),f(b,"_windowStart",0),f(b,"_user");var Ue=b;0&&(module.exports={RuntimeScope});
4
7
  if(typeof RuntimeScope!=="undefined"&&RuntimeScope.RuntimeScope){RuntimeScope=RuntimeScope.RuntimeScope;}
5
8
  //# sourceMappingURL=index.cjs.map