@runtimescope/sdk 0.10.5 → 0.10.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  `).slice(2).join(`
4
4
  `):void 0,sourceFile:J(h),source:"browser"};if(n){let S=n(_);S&&e(S)}else e(_);u&&!u.shouldPrint(f,b)||s[f](...w)};let d=console.assert?.bind(console);d&&(console.assert=(f,...w)=>{if(!f){let h=new Error().stack,b=`Assertion failed: ${w.map(_=>typeof _=="string"?_:Z(_)).join(" ")}`;e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:b,args:w.map(_=>E(_,3)),stackTrace:h?.split(`
5
5
  `).slice(2).join(`
6
- `),sourceFile:J(h),source:"browser"})}d(f,...w)});let l=console.time?.bind(console),p=console.timeEnd?.bind(console);l&&(console.time=(f="default")=>{o.set(f,performance.now()),l(f)}),p&&(console.timeEnd=(f="default")=>{let w=o.get(f);if(w!==void 0){let h=performance.now()-w;o.delete(f),e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"info",message:`${f}: ${h.toFixed(2)}ms`,args:[{label:f,duration:h}],source:"browser"})}p(f)});let R=console.count?.bind(console),v=console.countReset?.bind(console);R&&(console.count=(f="default")=>{let w=(i.get(f)??0)+1;i.set(f,w),e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"info",message:`${f}: ${w}`,args:[{label:f,count:w}],source:"browser"}),R(f)}),v&&(console.countReset=(f="default")=>{i.delete(f),v(f)});let I=console.table?.bind(console);return I&&(console.table=(f,w)=>{e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"info",message:`[table] ${Array.isArray(f)?`${f.length} rows`:typeof f}`,args:[E(f,3)],source:"browser"}),I(f,w)}),()=>{for(let f of Y)console[f]=s[f];d&&(console.assert=d),l&&(console.time=l),p&&(console.timeEnd=p),R&&(console.count=R),v&&(console.countReset=v),I&&(console.table=I),u?.dispose()}}function Z(e){try{return JSON.stringify(e)}catch{return String(e)}}function te(e,t,n,r){let s=new Set(n.map(l=>l.toLowerCase())),o=r?.captureBody??!1,i=r?.maxBodySize??65536,a=new AbortController,c=XMLHttpRequest.prototype.open,u=XMLHttpRequest.prototype.setRequestHeader,d=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(l,p){return this.__rs_method=l.toUpperCase(),this.__rs_url=typeof p=="string"?p:p.href,this.__rs_headers={},c.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(l,p){return this.__rs_headers&&(this.__rs_headers[l.toLowerCase()]=s.has(l.toLowerCase())?"[REDACTED]":p),u.call(this,l,p)},XMLHttpRequest.prototype.send=function(l){let p=this.__rs_method??"GET",R=this.__rs_url??"",v=`${p}:${R}`,I=!1;for(let y of L.keys())if(y.startsWith(v)){I=!0;break}if(I)return this.__rs_fetchIntercepted=!0,d.call(this,l);let f={...this.__rs_headers??{}},w=performance.now(),h,b=0;if(l){if(typeof l=="string")b=new Blob([l]).size,o&&(h=l.length>i?l.slice(0,i):l);else if(l instanceof Blob)b=l.size,o&&(h=`[Blob ${l.size} bytes]`);else if(l instanceof ArrayBuffer)b=l.byteLength,o&&(h=`[ArrayBuffer ${l.byteLength} bytes]`);else if(l instanceof FormData)o&&(h="[FormData]");else if(l instanceof URLSearchParams){let y=l.toString();b=new Blob([y]).size,o&&(h=y.length>i?y.slice(0,i):y)}}let _=Fe(l),S=y=>{let C={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"network",url:R,method:p,status:0,requestHeaders:f,responseHeaders:{},requestBodySize:b,responseBodySize:0,duration:0,ttfb:0,graphqlOperation:_,requestBody:h,source:"xhr",...y};if(r?.beforeSend){let D=r.beforeSend(C);D&&e(D)}else e(C)};return this.addEventListener("loadend",()=>{let y=performance.now()-w;if(this.status>0){let C=He(this.getAllResponseHeaders(),s),D=parseInt(this.getResponseHeader("content-length")||"0",10),x;if(o&&(this.responseType===""||this.responseType==="text"))try{let W=this.responseText;x=W.length>i?W.slice(0,i):W}catch{}S({status:this.status,responseHeaders:C,responseBodySize:D,responseBody:x,duration:y,ttfb:y})}else{let C="error",D="Network error";this.readyState===0||this.status,this.timeout>0&&y>=this.timeout&&(C="timeout",D=`Request timed out after ${this.timeout}ms`),S({duration:y,errorPhase:C,errorMessage:D})}},{once:!0,signal:a.signal}),d.call(this,l)},()=>{a.abort(),XMLHttpRequest.prototype.open=c,XMLHttpRequest.prototype.setRequestHeader=u,XMLHttpRequest.prototype.send=d}}function He(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 o=r.slice(0,s).trim().toLowerCase(),i=r.slice(s+1).trim();n[o]=t.has(o)?"[REDACTED]":i}return n}function Fe(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||Pe(n)||"anonymous";return{type:r,name:s}}}catch{}}function Pe(e){return e.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function re(e,t,n,r){let s=[],o=new Map;for(let[i,a]of Object.entries(n)){let c=$e(a);if(c==="zustand"){let u=a;j(e,t,r?.beforeSend,{storeId:i,library:c,phase:"init",state:E(u.getState(),4)});let d=u.subscribe((l,p)=>{let R=ne(p,l);j(e,t,r?.beforeSend,{storeId:i,library:c,phase:"update",state:E(l,4),previousState:E(p,4),diff:R?E(R,3):void 0})});s.push(d)}else if(c==="redux"){let u=a;j(e,t,r?.beforeSend,{storeId:i,library:c,phase:"init",state:E(u.getState(),4)});let d,l=u.dispatch.bind(u);o.set(i,l),u.dispatch=v=>(v&&typeof v=="object"&&"type"in v&&(d={type:String(v.type),payload:v.payload}),l(v));let p=u.getState(),R=u.subscribe(()=>{let v=u.getState(),I=ne(p,v);j(e,t,r?.beforeSend,{storeId:i,library:c,phase:"update",state:E(v,4),previousState:E(p,4),diff:I?E(I,3):void 0,action:d?E(d,3):void 0}),p=v,d=void 0});s.push(R)}}return()=>{for(let i of s)i();for(let[i,a]of o){let c=n[i];c&&(c.dispatch=a)}}}function $e(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 ne(e,t){if(!e||!t||typeof e!="object"||typeof t!="object")return null;let n={},r=e,s=t,o=new Set([...Object.keys(r),...Object.keys(s)]);for(let i of o)r[i]!==s[i]&&(n[i]={from:r[i],to:s[i]});return Object.keys(n).length>0?n:null}function j(e,t,n,r){let s={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"state",...r};if(n){let o=n(s);o&&e(o)}else e(s)}var Be={LCP:[2500,4e3],FCP:[1800,3e3],CLS:[.1,.25],TTFB:[800,1800],FID:[100,300],INP:[200,500]};function je(e,t){let[n,r]=Be[e]??[1/0,1/0];return t<=n?"good":t<=r?"needs-improvement":"poor"}var H=null;function se(e,t,n){if(H)for(let a of H)try{a.disconnect()}catch{}let r=[];H=r;let s=(a,c,u)=>{let d={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"performance",metricName:a,value:Math.round(c*100)/100,rating:je(a,c),element:u};if(n?.beforeSend){let l=n.beforeSend(d);l&&e(l)}else e(d)};O(r,"largest-contentful-paint",a=>{let c=a[a.length-1];if(!c)return;let u=c.element;s("LCP",c.startTime,u?.tagName?.toLowerCase())}),O(r,"paint",a=>{for(let c of a)c.name==="first-contentful-paint"&&s("FCP",c.startTime)});let o=0;O(r,"layout-shift",a=>{for(let c of a){let u=c;!u.hadRecentInput&&u.value&&(o+=u.value,s("CLS",o))}}),O(r,"first-input",a=>{let c=a[0];if(!c)return;let u=c;u.processingStart&&s("FID",u.processingStart-c.startTime)}),O(r,"navigation",a=>{let c=a[0];c&&s("TTFB",c.responseStart-c.requestStart)});let i=0;return O(r,"event",a=>{for(let c of a)c.duration>i&&(i=c.duration,s("INP",i))},{durationThreshold:16}),()=>{for(let a of r)try{a.disconnect()}catch{}H===r&&(H=null)}}function O(e,t,n,r){try{let s=new PerformanceObserver(o=>{n(o.getEntries())});s.observe({type:t,buffered:!0,...r}),e.push(s)}catch{}}var qe=0,Ue=1,ae=1e4,oe=100,ze=6e4,ie=500;function ce(e,t,n){let r=new Map,s=n?.snapshotIntervalMs??5e3,o=null,i=Xe();if(!i)return()=>{};let a=i.onCommitFiberRoot;return i._runtimescope_original=a,i.onCommitFiberRoot=(c,u)=>{if(a)try{a(c,u)}catch{}u.current&&G(u.current,r)},o=setInterval(()=>{Qe(r,e,t,n?.beforeSend)},s),()=>{o&&(clearInterval(o),o=null),i&&(i._runtimescope_original?i.onCommitFiberRoot=i._runtimescope_original:delete i.onCommitFiberRoot,delete i._runtimescope_original)}}function Xe(){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 G(e,t){We(e,t),e.child&&G(e.child,t),e.sibling&&G(e.sibling,t)}function We(e,t){if(e.tag!==qe&&e.tag!==Ue)return;let n=Ge(e);if(!n)return;let r=Date.now(),s=e.alternate===null,o=e.actualDuration??0,i=Ve(e,s),a=t.get(n);a||(a={renderCount:0,totalDuration:0,lastRenderTime:0,lastRenderPhase:"mount",lastRenderCause:"unknown",renderTimestamps:[]},t.set(n,a)),a.renderCount++,a.totalDuration+=o,a.lastRenderTime=r,a.lastRenderPhase=s?"mount":"update",a.lastRenderCause=i??"unknown",a.renderTimestamps.push(r),a.renderTimestamps.length>oe&&(a.renderTimestamps=a.renderTimestamps.slice(-oe))}function Ge(e){if(e.type&&typeof e.type!="string")return e.type.displayName||e.type.name||void 0}function Ve(e,t){return t?"props":e.alternate?e.memoizedProps!==e.alternate.memoizedProps?"props":e.memoizedState!==e.alternate.memoizedState?"state":"parent":"unknown"}function Ke(e){if(e.length<2)return 0;let t=Date.now(),n=t-ae,r=e.filter(o=>o>=n);if(r.length<2)return 0;let s=t-r[0];return s===0?0:r.length/(s/1e3)}function Qe(e,t,n,r){if(e.size===0)return;let s=[],o=[],i=0;for(let[u,d]of e){let l=Ke(d.renderTimestamps),p=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:p}),p&&o.push(u),i+=d.renderCount}s.sort((u,d)=>d.renderCount-u.renderCount);let a={eventId:g(),sessionId:n,timestamp:Date.now(),eventType:"render",profiles:s,snapshotWindowMs:ae,totalRenders:i,suspiciousComponents:o};if(r){let u=r(a);u&&t(u)}else t(a);let c=Date.now();for(let[u,d]of e)c-d.lastRenderTime>ze?e.delete(u):(d.renderCount=0,d.totalDuration=0);if(e.size>ie){let u=[...e.entries()].sort((l,p)=>l[1].lastRenderTime-p[1].lastRenderTime),d=e.size-ie;for(let l=0;l<d;l++)e.delete(u[l][0])}}function ue(e,t,n){let r=o=>{let i,a,c;if(o instanceof ErrorEvent)i=o.message||"Uncaught error",a=o.error?.stack,c=o.filename?`${o.filename}:${o.lineno}:${o.colno}`:void 0;else{let d=o.target;if(d&&d!==window){let l=d.tagName?.toLowerCase()??"unknown",p=d.src??d.src??d.href??"unknown";i=`Failed to load resource: <${l}> ${p}`}else return}let u={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:`[Uncaught] ${i}`,args:[E(i,3)],stackTrace:a,sourceFile:c};if(n){let d=n(u);d&&e(d)}else e(u)},s=o=>{let i=o.reason,a,c;if(i instanceof Error)a=i.message,c=i.stack;else if(typeof i=="string")a=i;else try{a=JSON.stringify(i)}catch{a=String(i)}let u={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:`[Unhandled Rejection] ${a}`,args:[E(i,3)],stackTrace:c,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 de(e,t){let n=window.location.href;function r(c,u){let d=n;d!==c&&(n=c,e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"navigation",from:d,to:c,trigger:u}))}let s=history.pushState.bind(history),o=history.replaceState.bind(history);history.pushState=function(...c){s(...c),r(window.location.href,"pushState")},history.replaceState=function(...c){o(...c),r(window.location.href,"replaceState")};let i=()=>r(window.location.href,"popstate");window.addEventListener("popstate",i);let a=()=>r(window.location.href,"hashchange");return window.addEventListener("hashchange",a),()=>{history.pushState=s,history.replaceState=o,window.removeEventListener("popstate",i),window.removeEventListener("hashchange",a)}}function le(e,t){let n=r=>{let s=r.target;if(!(s instanceof Element)||s.closest("[data-runtimescope]"))return;let o=Ye(s),i=Je(s),a={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"ui",action:"click",target:o,...i&&{text:i}};e(a)};return document.addEventListener("click",n,!0),()=>{document.removeEventListener("click",n,!0)}}function Ye(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 o=e.className;if(typeof o=="string"&&o.trim()){let a=o.split(/\s+/).find(c=>c.length>2&&!c.startsWith("_")&&!c.includes("__"));if(a)return`${t}.${a}`}let i=e.parentElement;if(i){let a=i.children,c=Array.from(a).filter(u=>u.tagName===e.tagName);if(c.length>1){let u=c.indexOf(e)+1;return`${t}:nth-child(${u})`}}return t}function Je(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}function q(e){let t=e.startsWith("runtimescopes://");if(!e.startsWith("runtimescope://")&&!t)throw new Error("Invalid RuntimeScope DSN: must start with runtimescope:// or runtimescopes://");let n=new URL(e.replace(/^runtimescopes?:\/\//,"http://")),r=n.username;if(!r||!r.startsWith("proj_"))throw new Error("Invalid RuntimeScope DSN: missing projectId (expected proj_xxx@host)");let s=n.password?decodeURIComponent(n.password):void 0,o=n.hostname,i=n.port?parseInt(n.port):6768,a=i-1,c=n.pathname.replace(/^\//,"")||void 0,u=t?"wss":"ws",d=t?"https":"http";return{projectId:r,authToken:s,wsEndpoint:`${u}://${o}:${a}`,httpEndpoint:`${d}://${o}:${i}`,appName:c,tls:t}}function pe(e){let t=e.tls?"runtimescopes":"runtimescope",n=e.host??"localhost",r=e.port??6768,s=e.appName?`/${e.appName}`:"",o=e.authToken?`:${encodeURIComponent(e.authToken)}`:"";return`${t}://${e.projectId}${o}@${n}:${r}${s}`}var U="0.10.5",Ze=console.debug.bind(console),et=console.warn.bind(console),z=!1;function M(...e){z&&Ze(...e)}var fe=new Set;function tt(e,...t){fe.has(e)||(fe.add(e),et(e,...t))}var X=Symbol.for("__runtimescope_originals__");function me(){let e=globalThis;return e[X]||(e[X]={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[X]}var T=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;let n=!1;if(t.dsn)try{let p=q(t.dsn);t={...t,serverUrl:p.wsEndpoint,projectId:p.projectId,...p.authToken?{authToken:p.authToken}:{},...p.appName&&!t.appName?{appName:p.appName}:{}},n=!0}catch(p){M("[RuntimeScope] Invalid DSN:",p.message)}if(!(!!(t.serverUrl||t.endpoint)||n)&&typeof window<"u"){let p=window.location?.hostname;if(p&&p!=="localhost"&&p!=="127.0.0.1"&&!p.startsWith("192.168.")&&!p.startsWith("10.")){M("[RuntimeScope] No endpoint configured and not on localhost \u2014 SDK disabled for production");return}}if(t.verbose===!0)z=!0;else if(typeof localStorage<"u")try{localStorage.getItem("RUNTIMESCOPE_DEBUG")==="1"&&(z=!0)}catch{}V(z);let s=`${t.appName??""}|${t.serverUrl??t.endpoint??""}|${t.dsn??""}|${t.projectId??""}`;if(this._state==="started"){if(this._initSignature===s)return;tt(`[RuntimeScope] init() called twice with different config \u2014 disconnecting and re-initializing.
6
+ `),sourceFile:J(h),source:"browser"})}d(f,...w)});let l=console.time?.bind(console),p=console.timeEnd?.bind(console);l&&(console.time=(f="default")=>{o.set(f,performance.now()),l(f)}),p&&(console.timeEnd=(f="default")=>{let w=o.get(f);if(w!==void 0){let h=performance.now()-w;o.delete(f),e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"info",message:`${f}: ${h.toFixed(2)}ms`,args:[{label:f,duration:h}],source:"browser"})}p(f)});let R=console.count?.bind(console),v=console.countReset?.bind(console);R&&(console.count=(f="default")=>{let w=(i.get(f)??0)+1;i.set(f,w),e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"info",message:`${f}: ${w}`,args:[{label:f,count:w}],source:"browser"}),R(f)}),v&&(console.countReset=(f="default")=>{i.delete(f),v(f)});let I=console.table?.bind(console);return I&&(console.table=(f,w)=>{e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"info",message:`[table] ${Array.isArray(f)?`${f.length} rows`:typeof f}`,args:[E(f,3)],source:"browser"}),I(f,w)}),()=>{for(let f of Y)console[f]=s[f];d&&(console.assert=d),l&&(console.time=l),p&&(console.timeEnd=p),R&&(console.count=R),v&&(console.countReset=v),I&&(console.table=I),u?.dispose()}}function Z(e){try{return JSON.stringify(e)}catch{return String(e)}}function te(e,t,n,r){let s=new Set(n.map(l=>l.toLowerCase())),o=r?.captureBody??!1,i=r?.maxBodySize??65536,a=new AbortController,c=XMLHttpRequest.prototype.open,u=XMLHttpRequest.prototype.setRequestHeader,d=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(l,p){return this.__rs_method=l.toUpperCase(),this.__rs_url=typeof p=="string"?p:p.href,this.__rs_headers={},c.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(l,p){return this.__rs_headers&&(this.__rs_headers[l.toLowerCase()]=s.has(l.toLowerCase())?"[REDACTED]":p),u.call(this,l,p)},XMLHttpRequest.prototype.send=function(l){let p=this.__rs_method??"GET",R=this.__rs_url??"",v=`${p}:${R}`,I=!1;for(let y of L.keys())if(y.startsWith(v)){I=!0;break}if(I)return this.__rs_fetchIntercepted=!0,d.call(this,l);let f={...this.__rs_headers??{}},w=performance.now(),h,b=0;if(l){if(typeof l=="string")b=new Blob([l]).size,o&&(h=l.length>i?l.slice(0,i):l);else if(l instanceof Blob)b=l.size,o&&(h=`[Blob ${l.size} bytes]`);else if(l instanceof ArrayBuffer)b=l.byteLength,o&&(h=`[ArrayBuffer ${l.byteLength} bytes]`);else if(l instanceof FormData)o&&(h="[FormData]");else if(l instanceof URLSearchParams){let y=l.toString();b=new Blob([y]).size,o&&(h=y.length>i?y.slice(0,i):y)}}let _=Fe(l),S=y=>{let C={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"network",url:R,method:p,status:0,requestHeaders:f,responseHeaders:{},requestBodySize:b,responseBodySize:0,duration:0,ttfb:0,graphqlOperation:_,requestBody:h,source:"xhr",...y};if(r?.beforeSend){let D=r.beforeSend(C);D&&e(D)}else e(C)};return this.addEventListener("loadend",()=>{let y=performance.now()-w;if(this.status>0){let C=He(this.getAllResponseHeaders(),s),D=parseInt(this.getResponseHeader("content-length")||"0",10),x;if(o&&(this.responseType===""||this.responseType==="text"))try{let W=this.responseText;x=W.length>i?W.slice(0,i):W}catch{}S({status:this.status,responseHeaders:C,responseBodySize:D,responseBody:x,duration:y,ttfb:y})}else{let C="error",D="Network error";this.readyState===0||this.status,this.timeout>0&&y>=this.timeout&&(C="timeout",D=`Request timed out after ${this.timeout}ms`),S({duration:y,errorPhase:C,errorMessage:D})}},{once:!0,signal:a.signal}),d.call(this,l)},()=>{a.abort(),XMLHttpRequest.prototype.open=c,XMLHttpRequest.prototype.setRequestHeader=u,XMLHttpRequest.prototype.send=d}}function He(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 o=r.slice(0,s).trim().toLowerCase(),i=r.slice(s+1).trim();n[o]=t.has(o)?"[REDACTED]":i}return n}function Fe(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||Pe(n)||"anonymous";return{type:r,name:s}}}catch{}}function Pe(e){return e.match(/^(?:query|mutation|subscription)\s+(\w+)/)?.[1]}function re(e,t,n,r){let s=[],o=new Map;for(let[i,a]of Object.entries(n)){let c=$e(a);if(c==="zustand"){let u=a;j(e,t,r?.beforeSend,{storeId:i,library:c,phase:"init",state:E(u.getState(),4)});let d=u.subscribe((l,p)=>{let R=ne(p,l);j(e,t,r?.beforeSend,{storeId:i,library:c,phase:"update",state:E(l,4),previousState:E(p,4),diff:R?E(R,3):void 0})});s.push(d)}else if(c==="redux"){let u=a;j(e,t,r?.beforeSend,{storeId:i,library:c,phase:"init",state:E(u.getState(),4)});let d,l=u.dispatch.bind(u);o.set(i,l),u.dispatch=v=>(v&&typeof v=="object"&&"type"in v&&(d={type:String(v.type),payload:v.payload}),l(v));let p=u.getState(),R=u.subscribe(()=>{let v=u.getState(),I=ne(p,v);j(e,t,r?.beforeSend,{storeId:i,library:c,phase:"update",state:E(v,4),previousState:E(p,4),diff:I?E(I,3):void 0,action:d?E(d,3):void 0}),p=v,d=void 0});s.push(R)}}return()=>{for(let i of s)i();for(let[i,a]of o){let c=n[i];c&&(c.dispatch=a)}}}function $e(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 ne(e,t){if(!e||!t||typeof e!="object"||typeof t!="object")return null;let n={},r=e,s=t,o=new Set([...Object.keys(r),...Object.keys(s)]);for(let i of o)r[i]!==s[i]&&(n[i]={from:r[i],to:s[i]});return Object.keys(n).length>0?n:null}function j(e,t,n,r){let s={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"state",...r};if(n){let o=n(s);o&&e(o)}else e(s)}var Be={LCP:[2500,4e3],FCP:[1800,3e3],CLS:[.1,.25],TTFB:[800,1800],FID:[100,300],INP:[200,500]};function je(e,t){let[n,r]=Be[e]??[1/0,1/0];return t<=n?"good":t<=r?"needs-improvement":"poor"}var H=null;function se(e,t,n){if(H)for(let a of H)try{a.disconnect()}catch{}let r=[];H=r;let s=(a,c,u)=>{let d={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"performance",metricName:a,value:Math.round(c*100)/100,rating:je(a,c),element:u};if(n?.beforeSend){let l=n.beforeSend(d);l&&e(l)}else e(d)};O(r,"largest-contentful-paint",a=>{let c=a[a.length-1];if(!c)return;let u=c.element;s("LCP",c.startTime,u?.tagName?.toLowerCase())}),O(r,"paint",a=>{for(let c of a)c.name==="first-contentful-paint"&&s("FCP",c.startTime)});let o=0;O(r,"layout-shift",a=>{for(let c of a){let u=c;!u.hadRecentInput&&u.value&&(o+=u.value,s("CLS",o))}}),O(r,"first-input",a=>{let c=a[0];if(!c)return;let u=c;u.processingStart&&s("FID",u.processingStart-c.startTime)}),O(r,"navigation",a=>{let c=a[0];c&&s("TTFB",c.responseStart-c.requestStart)});let i=0;return O(r,"event",a=>{for(let c of a)c.duration>i&&(i=c.duration,s("INP",i))},{durationThreshold:16}),()=>{for(let a of r)try{a.disconnect()}catch{}H===r&&(H=null)}}function O(e,t,n,r){try{let s=new PerformanceObserver(o=>{n(o.getEntries())});s.observe({type:t,buffered:!0,...r}),e.push(s)}catch{}}var qe=0,Ue=1,ae=1e4,oe=100,ze=6e4,ie=500;function ce(e,t,n){let r=new Map,s=n?.snapshotIntervalMs??5e3,o=null,i=Xe();if(!i)return()=>{};let a=i.onCommitFiberRoot;return i._runtimescope_original=a,i.onCommitFiberRoot=(c,u)=>{if(a)try{a(c,u)}catch{}u.current&&G(u.current,r)},o=setInterval(()=>{Qe(r,e,t,n?.beforeSend)},s),()=>{o&&(clearInterval(o),o=null),i&&(i._runtimescope_original?i.onCommitFiberRoot=i._runtimescope_original:delete i.onCommitFiberRoot,delete i._runtimescope_original)}}function Xe(){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 G(e,t){We(e,t),e.child&&G(e.child,t),e.sibling&&G(e.sibling,t)}function We(e,t){if(e.tag!==qe&&e.tag!==Ue)return;let n=Ge(e);if(!n)return;let r=Date.now(),s=e.alternate===null,o=e.actualDuration??0,i=Ve(e,s),a=t.get(n);a||(a={renderCount:0,totalDuration:0,lastRenderTime:0,lastRenderPhase:"mount",lastRenderCause:"unknown",renderTimestamps:[]},t.set(n,a)),a.renderCount++,a.totalDuration+=o,a.lastRenderTime=r,a.lastRenderPhase=s?"mount":"update",a.lastRenderCause=i??"unknown",a.renderTimestamps.push(r),a.renderTimestamps.length>oe&&(a.renderTimestamps=a.renderTimestamps.slice(-oe))}function Ge(e){if(e.type&&typeof e.type!="string")return e.type.displayName||e.type.name||void 0}function Ve(e,t){return t?"props":e.alternate?e.memoizedProps!==e.alternate.memoizedProps?"props":e.memoizedState!==e.alternate.memoizedState?"state":"parent":"unknown"}function Ke(e){if(e.length<2)return 0;let t=Date.now(),n=t-ae,r=e.filter(o=>o>=n);if(r.length<2)return 0;let s=t-r[0];return s===0?0:r.length/(s/1e3)}function Qe(e,t,n,r){if(e.size===0)return;let s=[],o=[],i=0;for(let[u,d]of e){let l=Ke(d.renderTimestamps),p=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:p}),p&&o.push(u),i+=d.renderCount}s.sort((u,d)=>d.renderCount-u.renderCount);let a={eventId:g(),sessionId:n,timestamp:Date.now(),eventType:"render",profiles:s,snapshotWindowMs:ae,totalRenders:i,suspiciousComponents:o};if(r){let u=r(a);u&&t(u)}else t(a);let c=Date.now();for(let[u,d]of e)c-d.lastRenderTime>ze?e.delete(u):(d.renderCount=0,d.totalDuration=0);if(e.size>ie){let u=[...e.entries()].sort((l,p)=>l[1].lastRenderTime-p[1].lastRenderTime),d=e.size-ie;for(let l=0;l<d;l++)e.delete(u[l][0])}}function ue(e,t,n){let r=o=>{let i,a,c;if(o instanceof ErrorEvent)i=o.message||"Uncaught error",a=o.error?.stack,c=o.filename?`${o.filename}:${o.lineno}:${o.colno}`:void 0;else{let d=o.target;if(d&&d!==window){let l=d.tagName?.toLowerCase()??"unknown",p=d.src??d.src??d.href??"unknown";i=`Failed to load resource: <${l}> ${p}`}else return}let u={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:`[Uncaught] ${i}`,args:[E(i,3)],stackTrace:a,sourceFile:c};if(n){let d=n(u);d&&e(d)}else e(u)},s=o=>{let i=o.reason,a,c;if(i instanceof Error)a=i.message,c=i.stack;else if(typeof i=="string")a=i;else try{a=JSON.stringify(i)}catch{a=String(i)}let u={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"console",level:"error",message:`[Unhandled Rejection] ${a}`,args:[E(i,3)],stackTrace:c,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 de(e,t){let n=window.location.href;function r(c,u){let d=n;d!==c&&(n=c,e({eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"navigation",from:d,to:c,trigger:u}))}let s=history.pushState.bind(history),o=history.replaceState.bind(history);history.pushState=function(...c){s(...c),r(window.location.href,"pushState")},history.replaceState=function(...c){o(...c),r(window.location.href,"replaceState")};let i=()=>r(window.location.href,"popstate");window.addEventListener("popstate",i);let a=()=>r(window.location.href,"hashchange");return window.addEventListener("hashchange",a),()=>{history.pushState=s,history.replaceState=o,window.removeEventListener("popstate",i),window.removeEventListener("hashchange",a)}}function le(e,t){let n=r=>{let s=r.target;if(!(s instanceof Element)||s.closest("[data-runtimescope]"))return;let o=Ye(s),i=Je(s),a={eventId:g(),sessionId:t,timestamp:Date.now(),eventType:"ui",action:"click",target:o,...i&&{text:i}};e(a)};return document.addEventListener("click",n,!0),()=>{document.removeEventListener("click",n,!0)}}function Ye(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 o=e.className;if(typeof o=="string"&&o.trim()){let a=o.split(/\s+/).find(c=>c.length>2&&!c.startsWith("_")&&!c.includes("__"));if(a)return`${t}.${a}`}let i=e.parentElement;if(i){let a=i.children,c=Array.from(a).filter(u=>u.tagName===e.tagName);if(c.length>1){let u=c.indexOf(e)+1;return`${t}:nth-child(${u})`}}return t}function Je(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}function q(e){let t=e.startsWith("runtimescopes://");if(!e.startsWith("runtimescope://")&&!t)throw new Error("Invalid RuntimeScope DSN: must start with runtimescope:// or runtimescopes://");let n=new URL(e.replace(/^runtimescopes?:\/\//,"http://")),r=n.username;if(!r||!r.startsWith("proj_"))throw new Error("Invalid RuntimeScope DSN: missing projectId (expected proj_xxx@host)");let s=n.password?decodeURIComponent(n.password):void 0,o=n.hostname,i=n.port?parseInt(n.port):6768,a=i-1,c=n.pathname.replace(/^\//,"")||void 0,u=t?"wss":"ws",d=t?"https":"http";return{projectId:r,authToken:s,wsEndpoint:`${u}://${o}:${a}`,httpEndpoint:`${d}://${o}:${i}`,appName:c,tls:t}}function pe(e){let t=e.tls?"runtimescopes":"runtimescope",n=e.host??"localhost",r=e.port??6768,s=e.appName?`/${e.appName}`:"",o=e.authToken?`:${encodeURIComponent(e.authToken)}`:"";return`${t}://${e.projectId}${o}@${n}:${r}${s}`}var U="0.10.7",Ze=console.debug.bind(console),et=console.warn.bind(console),z=!1;function M(...e){z&&Ze(...e)}var fe=new Set;function tt(e,...t){fe.has(e)||(fe.add(e),et(e,...t))}var X=Symbol.for("__runtimescope_originals__");function me(){let e=globalThis;return e[X]||(e[X]={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[X]}var T=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;let n=!1;if(t.dsn)try{let p=q(t.dsn);t={...t,serverUrl:p.wsEndpoint,projectId:p.projectId,...p.authToken?{authToken:p.authToken}:{},...p.appName&&!t.appName?{appName:p.appName}:{}},n=!0}catch(p){M("[RuntimeScope] Invalid DSN:",p.message)}if(!(!!(t.serverUrl||t.endpoint)||n)&&typeof window<"u"){let p=window.location?.hostname;if(p&&p!=="localhost"&&p!=="127.0.0.1"&&!p.startsWith("192.168.")&&!p.startsWith("10.")){M("[RuntimeScope] No endpoint configured and not on localhost \u2014 SDK disabled for production");return}}if(t.verbose===!0)z=!0;else if(typeof localStorage<"u")try{localStorage.getItem("RUNTIMESCOPE_DEBUG")==="1"&&(z=!0)}catch{}V(z);let s=`${t.appName??""}|${t.serverUrl??t.endpoint??""}|${t.dsn??""}|${t.projectId??""}`;if(this._state==="started"){if(this._initSignature===s)return;tt(`[RuntimeScope] init() called twice with different config \u2014 disconnecting and re-initializing.
7
7
  previous: ${this._initSignature}
8
8
  next: ${s}
9
9
  If the SDK is loaded by @runtimescope/vite, drop your manual RuntimeScope.init() call \u2014 the plugin handles it.`),this.disconnect()}this._initSignature=s;let o={serverUrl:t.serverUrl??t.endpoint??"ws://localhost:6767",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,dedupeConsole:t.dedupeConsole??!1};me(),this._sessionId=K(),this._state="started",this.transport=new $({serverUrl:o.serverUrl,appName:o.appName,sessionId:this._sessionId,sdkVersion:U,authToken:t.authToken,projectId:t.projectId,batchSize:o.batchSize,flushIntervalMs:o.flushIntervalMs}),this._sampleRate=t.sampleRate??1,this._maxEventsPerSecond=t.maxEventsPerSecond,this._windowCount=0,this._windowStart=Date.now(),this._user=t.user,this.transport.connect(),M(`[RuntimeScope] SDK v${U} initializing \u2014 app: ${o.appName}, server: ${o.serverUrl}`);let i=me().consoleMethods.warn,a=this.transport,c=o.serverUrl;setTimeout(()=>{if(this.transport!==a||a.isConnected?.())return;let R=/localhost|127\.0\.0\.1/.test(c)?"Run `npx runtimescope start` in a terminal.":`Check that ${c} is reachable and the collector is running.`;i(`[RuntimeScope] Couldn't connect to ${c} after 10s. No events are being captured.`,`