@arvoretech/bug-jar 0.6.0 → 0.7.1

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.js CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var X=Object.create;var v=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var Z=(s,e)=>{for(var t in e)v(s,t,{get:e[t],enumerable:!0})},D=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of G(e))!W.call(s,n)&&n!==t&&v(s,n,{get:()=>e[n],enumerable:!(r=K(e,n))||r.enumerable});return s};var Y=(s,e,t)=>(t=s!=null?X(V(s)):{},D(e||!s||!s.__esModule?v(t,"default",{value:s,enumerable:!0}):t,s)),Q=s=>D(v({},"__esModule",{value:!0}),s);var ge={};Z(ge,{BugJar:()=>g,default:()=>fe,exportAsZip:()=>P,generateSummary:()=>H,init:()=>N});module.exports=Q(ge);function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function $(s,e=1e4){try{let t=new WeakSet,r=JSON.stringify(s,(n,o)=>{if(typeof o=="object"&&o!==null){if(t.has(o))return"[Circular]";t.add(o)}return o instanceof Error?{message:o.message,stack:o.stack,name:o.name}:typeof o=="function"?"[Function]":o instanceof HTMLElement?f(o):o});return r&&r.length>e?r.slice(0,e)+"...[truncated]":r||""}catch{return"[Unserializable]"}}function f(s){if(!s||!(s instanceof Element))return"unknown";let e=s.tagName.toLowerCase(),t=s.id?`#${s.id}`:"",r=s.className&&typeof s.className=="string"?`.${s.className.trim().split(/\s+/).join(".")}`:"",n=s.textContent?.trim().slice(0,30)||"",o=n?` "${n}"`:"";return`${e}${t}${r}${o}`}function d(s,e){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(r=>d(r,e));let t={};for(let[r,n]of Object.entries(s))e.some(a=>r.toLowerCase().includes(a.toLowerCase()))?t[r]="[REDACTED]":typeof n=="object"&&n!==null?t[r]=d(n,e):t[r]=n;return t}var l=class{constructor(e){this.buffer=[];this.maxSize=e}push(e){this.buffer.length>=this.maxSize&&this.buffer.shift(),this.buffer.push(e)}getAll(){return[...this.buffer]}clear(){this.buffer=[]}get length(){return this.buffer.length}};var w=class{constructor(e){this.originalFetch=null;this.originalXhrOpen=null;this.originalXhrSend=null;this.originalXhrSetRequestHeader=null;this.originalSendBeacon=null;this.config=e,this.buffer=new l(e.maxNetworkEntries)}start(){this.interceptFetch(),this.interceptXHR(),this.interceptBeacon()}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXhrOpen&&this.originalXhrSend&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrOpen=null,this.originalXhrSend=null),this.originalXhrSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXhrSetRequestHeader,this.originalXhrSetRequestHeader=null),this.originalSendBeacon&&(Navigator.prototype.sendBeacon=this.originalSendBeacon,this.originalSendBeacon=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}interceptFetch(){this.originalFetch=window.fetch.bind(window);let e=this;window.fetch=async function(t,r){let n=performance.now(),o={id:h(),timestamp:Date.now(),method:(r?.method||"GET").toUpperCase(),url:typeof t=="string"?t:t instanceof URL?t.href:t.url,requestHeaders:e.extractHeaders(r?.headers),requestBody:e.safeParseBody(r?.body),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"fetch",error:null,initiator:e.getInitiator()};try{let a=await e.originalFetch(t,r);o.status=a.status,o.statusText=a.statusText,o.responseHeaders=e.extractResponseHeaders(a.headers),o.duration=performance.now()-n;let c=a.clone();try{let i=await c.text();o.responseSize=i.length,o.responseBody=e.safeParseJson(i)}catch{o.responseBody="[Unable to read response]"}return o.requestBody=d(o.requestBody,e.config.sensitiveFields),o.responseBody=d(o.responseBody,e.config.sensitiveFields),e.buffer.push(o),a}catch(a){throw o.duration=performance.now()-n,o.error=a instanceof Error?a.message:String(a),e.buffer.push(o),a}}}interceptXHR(){this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send,this.originalXhrSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader;let e=this;XMLHttpRequest.prototype.open=function(t,r){return this.__bugjar_method=t,this.__bugjar_url=typeof r=="string"?r:r.href,this.__bugjar_headers={},e.originalXhrOpen.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(t,r){return this.__bugjar_headers&&(this.__bugjar_headers[t]=r),e.originalXhrSetRequestHeader.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){let r=performance.now(),n={id:h(),timestamp:Date.now(),method:(this.__bugjar_method||"GET").toUpperCase(),url:this.__bugjar_url||"",requestHeaders:this.__bugjar_headers||{},requestBody:e.safeParseBody(t),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"xhr",error:null,initiator:e.getInitiator()};return this.addEventListener("load",function(){n.status=this.status,n.statusText=this.statusText,n.responseHeaders=e.parseXhrHeaders(this.getAllResponseHeaders()),n.duration=performance.now()-r,n.responseSize=this.responseText?.length||null,n.responseBody=e.safeParseJson(this.responseText),n.requestBody=d(n.requestBody,e.config.sensitiveFields),n.responseBody=d(n.responseBody,e.config.sensitiveFields),e.buffer.push(n)}),this.addEventListener("error",function(){n.duration=performance.now()-r,n.error="Network error",e.buffer.push(n)}),this.addEventListener("timeout",function(){n.duration=performance.now()-r,n.error="Request timeout",e.buffer.push(n)}),e.originalXhrSend.apply(this,arguments)}}interceptBeacon(){if(!navigator.sendBeacon)return;this.originalSendBeacon=navigator.sendBeacon.bind(navigator);let e=this;Navigator.prototype.sendBeacon=function(t,r){let n={id:h(),timestamp:Date.now(),method:"POST",url:typeof t=="string"?t:t.href,requestHeaders:{},requestBody:e.safeParseBody(r),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"beacon",error:null,initiator:"sendBeacon"};return n.requestBody=d(n.requestBody,e.config.sensitiveFields),e.buffer.push(n),e.originalSendBeacon(t,r)}}extractHeaders(e){let t={};return e&&(e instanceof Headers?e.forEach((r,n)=>{t[n]=r}):Array.isArray(e)?e.forEach(([r,n])=>{t[r]=n}):Object.assign(t,e)),t}extractResponseHeaders(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}parseXhrHeaders(e){let t={};return e&&e.trim().split(/[\r\n]+/).forEach(r=>{let n=r.split(": "),o=n.shift();o&&(t[o]=n.join(": "))}),t}safeParseBody(e){if(!e)return null;if(typeof e=="string")return this.safeParseJson(e);if(e instanceof FormData){let t={};return e.forEach((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),t}return e instanceof URLSearchParams?Object.fromEntries(e.entries()):e instanceof Blob?`[Blob: ${e.size} bytes]`:e instanceof ArrayBuffer?`[ArrayBuffer: ${e.byteLength} bytes]`:String(e)}safeParseJson(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.length>5e3?e.slice(0,5e3)+"...[truncated]":e}}getInitiator(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
2
- `);for(let r of t)if(!r.includes("bug-jar")&&r.includes("at "))return r.trim().slice(0,200);return null}catch{return null}}};var b=class{constructor(e){this.originals={};this.levels=["log","warn","error","info","debug"];this.buffer=new l(e.maxConsoleEntries)}start(){for(let e of this.levels){this.originals[e]=console[e].bind(console);let t=this;console[e]=(...r)=>{t.capture(e,r),t.originals[e](...r)}}}stop(){for(let e of this.levels)this.originals[e]&&(console[e]=this.originals[e]);this.originals={}}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}capture(e,t){let r={timestamp:Date.now(),level:e,args:t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?n:JSON.parse($(n))),stack:e==="error"||e==="warn"?this.getStack():null};this.buffer.push(r)}getStack(){try{return new Error().stack?.split(`
1
+ "use strict";var W=Object.create;var v=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var G=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var Z=(s,e)=>{for(var t in e)v(s,t,{get:e[t],enumerable:!0})},M=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of V(e))!Y.call(s,n)&&n!==t&&v(s,n,{get:()=>e[n],enumerable:!(r=K(e,n))||r.enumerable});return s};var Q=(s,e,t)=>(t=s!=null?W(G(s)):{},M(e||!s||!s.__esModule?v(t,"default",{value:s,enumerable:!0}):t,s)),ee=s=>M(v({},"__esModule",{value:!0}),s);var me={};Z(me,{BugJar:()=>g,default:()=>ge,exportAsZip:()=>H,generateSummary:()=>P,init:()=>X});module.exports=ee(me);function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function I(s,e=1e4){try{let t=new WeakSet,r=JSON.stringify(s,(n,o)=>{if(typeof o=="object"&&o!==null){if(t.has(o))return"[Circular]";t.add(o)}return o instanceof Error?{message:o.message,stack:o.stack,name:o.name}:typeof o=="function"?"[Function]":o instanceof HTMLElement?f(o):o});return r&&r.length>e?r.slice(0,e)+"...[truncated]":r||""}catch{return"[Unserializable]"}}function f(s){if(!s||!(s instanceof Element))return"unknown";let e=s.tagName.toLowerCase(),t=s.id?`#${s.id}`:"",r=s.className&&typeof s.className=="string"?`.${s.className.trim().split(/\s+/).join(".")}`:"",n=s.textContent?.trim().slice(0,30)||"",o=n?` "${n}"`:"";return`${e}${t}${r}${o}`}function d(s,e){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(r=>d(r,e));let t={};for(let[r,n]of Object.entries(s))e.some(a=>r.toLowerCase().includes(a.toLowerCase()))?t[r]="[REDACTED]":typeof n=="object"&&n!==null?t[r]=d(n,e):t[r]=n;return t}var u=class{constructor(e){this.buffer=[];this.maxSize=e}push(e){this.buffer.length>=this.maxSize&&this.buffer.shift(),this.buffer.push(e)}getAll(){return[...this.buffer]}clear(){this.buffer=[]}get length(){return this.buffer.length}};var w=class{constructor(e){this.originalFetch=null;this.originalXhrOpen=null;this.originalXhrSend=null;this.originalXhrSetRequestHeader=null;this.originalSendBeacon=null;this.config=e,this.buffer=new u(e.maxNetworkEntries)}start(){this.interceptFetch(),this.interceptXHR(),this.interceptBeacon()}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXhrOpen&&this.originalXhrSend&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrOpen=null,this.originalXhrSend=null),this.originalXhrSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXhrSetRequestHeader,this.originalXhrSetRequestHeader=null),this.originalSendBeacon&&(Navigator.prototype.sendBeacon=this.originalSendBeacon,this.originalSendBeacon=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addIgnoreUrl(e){this.config.ignoreUrls||(this.config.ignoreUrls=[]),this.config.ignoreUrls.includes(e)||this.config.ignoreUrls.push(e)}getRawFetch(){return this.originalFetch??window.fetch.bind(window)}shouldIgnore(e){let t=this.config.ignoreUrls;return!t||t.length===0?!1:t.some(r=>e.includes(r))}resolveUrl(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}interceptFetch(){this.originalFetch=window.fetch.bind(window);let e=this;window.fetch=async function(t,r){if(e.shouldIgnore(e.resolveUrl(t)))return e.originalFetch(t,r);let n=performance.now(),o={id:h(),timestamp:Date.now(),method:(r?.method||"GET").toUpperCase(),url:typeof t=="string"?t:t instanceof URL?t.href:t.url,requestHeaders:e.extractHeaders(r?.headers),requestBody:e.safeParseBody(r?.body),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"fetch",error:null,initiator:e.getInitiator()};try{let a=await e.originalFetch(t,r);o.status=a.status,o.statusText=a.statusText,o.responseHeaders=e.extractResponseHeaders(a.headers),o.duration=performance.now()-n;let c=a.clone();try{let i=await c.text();o.responseSize=i.length,o.responseBody=e.safeParseJson(i)}catch{o.responseBody="[Unable to read response]"}return o.requestBody=d(o.requestBody,e.config.sensitiveFields),o.responseBody=d(o.responseBody,e.config.sensitiveFields),e.buffer.push(o),a}catch(a){throw o.duration=performance.now()-n,o.error=a instanceof Error?a.message:String(a),e.buffer.push(o),a}}}interceptXHR(){this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send,this.originalXhrSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader;let e=this;XMLHttpRequest.prototype.open=function(t,r){return this.__bugjar_method=t,this.__bugjar_url=typeof r=="string"?r:r.href,this.__bugjar_headers={},e.originalXhrOpen.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(t,r){return this.__bugjar_headers&&(this.__bugjar_headers[t]=r),e.originalXhrSetRequestHeader.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){if(e.shouldIgnore(this.__bugjar_url||""))return e.originalXhrSend.apply(this,arguments);let r=performance.now(),n={id:h(),timestamp:Date.now(),method:(this.__bugjar_method||"GET").toUpperCase(),url:this.__bugjar_url||"",requestHeaders:this.__bugjar_headers||{},requestBody:e.safeParseBody(t),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"xhr",error:null,initiator:e.getInitiator()};return this.addEventListener("load",function(){n.status=this.status,n.statusText=this.statusText,n.responseHeaders=e.parseXhrHeaders(this.getAllResponseHeaders()),n.duration=performance.now()-r,n.responseSize=this.responseText?.length||null,n.responseBody=e.safeParseJson(this.responseText),n.requestBody=d(n.requestBody,e.config.sensitiveFields),n.responseBody=d(n.responseBody,e.config.sensitiveFields),e.buffer.push(n)}),this.addEventListener("error",function(){n.duration=performance.now()-r,n.error="Network error",e.buffer.push(n)}),this.addEventListener("timeout",function(){n.duration=performance.now()-r,n.error="Request timeout",e.buffer.push(n)}),e.originalXhrSend.apply(this,arguments)}}interceptBeacon(){if(!navigator.sendBeacon)return;this.originalSendBeacon=navigator.sendBeacon.bind(navigator);let e=this;Navigator.prototype.sendBeacon=function(t,r){let n=typeof t=="string"?t:t.href;if(e.shouldIgnore(n))return e.originalSendBeacon(t,r);let o={id:h(),timestamp:Date.now(),method:"POST",url:n,requestHeaders:{},requestBody:e.safeParseBody(r),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"beacon",error:null,initiator:"sendBeacon"};return o.requestBody=d(o.requestBody,e.config.sensitiveFields),e.buffer.push(o),e.originalSendBeacon(t,r)}}extractHeaders(e){let t={};return e&&(e instanceof Headers?e.forEach((r,n)=>{t[n]=r}):Array.isArray(e)?e.forEach(([r,n])=>{t[r]=n}):Object.assign(t,e)),t}extractResponseHeaders(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}parseXhrHeaders(e){let t={};return e&&e.trim().split(/[\r\n]+/).forEach(r=>{let n=r.split(": "),o=n.shift();o&&(t[o]=n.join(": "))}),t}safeParseBody(e){if(!e)return null;if(typeof e=="string")return this.safeParseJson(e);if(e instanceof FormData){let t={};return e.forEach((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),t}return e instanceof URLSearchParams?Object.fromEntries(e.entries()):e instanceof Blob?`[Blob: ${e.size} bytes]`:e instanceof ArrayBuffer?`[ArrayBuffer: ${e.byteLength} bytes]`:String(e)}safeParseJson(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.length>5e3?e.slice(0,5e3)+"...[truncated]":e}}getInitiator(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
2
+ `);for(let r of t)if(!r.includes("bug-jar")&&r.includes("at "))return r.trim().slice(0,200);return null}catch{return null}}};var b=class{constructor(e){this.originals={};this.levels=["log","warn","error","info","debug"];this.buffer=new u(e.maxConsoleEntries)}start(){for(let e of this.levels){this.originals[e]=console[e].bind(console);let t=this;console[e]=(...r)=>{t.capture(e,r),t.originals[e](...r)}}}stop(){for(let e of this.levels)this.originals[e]&&(console[e]=this.originals[e]);this.originals={}}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}capture(e,t){let r={timestamp:Date.now(),level:e,args:t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?n:JSON.parse(I(n))),stack:e==="error"||e==="warn"?this.getStack():null};this.buffer.push(r)}getStack(){try{return new Error().stack?.split(`
3
3
  `).slice(4).join(`
4
- `)||null}catch{return null}}};var S=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new l(e.maxErrors)}start(){this.errorHandler=e=>{this.buffer.push({timestamp:Date.now(),message:e.message||"Unknown error",stack:e.error?.stack||null,filename:e.filename||null,lineno:e.lineno||null,colno:e.colno||null,type:"uncaught",context:this.getContext(e.error)})},this.rejectionHandler=e=>{let t=e.reason;this.buffer.push({timestamp:Date.now(),message:t instanceof Error?t.message:String(t),stack:t instanceof Error&&t.stack||null,filename:null,lineno:null,colno:null,type:"unhandledrejection",context:t instanceof Error?this.getContext(t):null})},this.resourceErrorHandler=e=>{let t=e.target;!t||!(t instanceof HTMLElement)||(t.tagName==="SCRIPT"||t.tagName==="LINK"||t.tagName==="IMG")&&this.buffer.push({timestamp:Date.now(),message:`Failed to load ${t.tagName.toLowerCase()}: ${t.src||t.href||"unknown"}`,stack:null,filename:t.src||t.href||null,lineno:null,colno:null,type:"resource",context:null})},window.addEventListener("error",this.errorHandler),window.addEventListener("unhandledrejection",this.rejectionHandler),window.addEventListener("error",this.resourceErrorHandler,!0)}stop(){this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null),this.resourceErrorHandler&&(window.removeEventListener("error",this.resourceErrorHandler,!0),this.resourceErrorHandler=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}getContext(e){if(!e)return null;try{let t=e.stack;if(!t)return null;let r=t.match(/at\s+(.+?)\s+\(/);return r?r[1]:null}catch{return null}}};var E=class{constructor(e){this.listeners=[];this.buffer=new l(e.maxUserActions)}start(){this.addListener("click",n=>{let o=n.target;this.buffer.push({timestamp:Date.now(),type:"click",target:f(o),metadata:{x:n.clientX,y:n.clientY,button:n.button}})},!0),this.addListener("input",n=>{let o=n.target,a=o.type==="password"||o.type==="hidden"||o.name?.toLowerCase().includes("password")||o.name?.toLowerCase().includes("token")||o.name?.toLowerCase().includes("secret");this.buffer.push({timestamp:Date.now(),type:"input",target:f(o),value:a?"[REDACTED]":o.value?.slice(0,50)||"",metadata:{inputType:o.type,name:o.name}})},!0),this.addListener("scroll",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"scroll",target:"window",metadata:{scrollX:window.scrollX,scrollY:window.scrollY,scrollHeight:document.documentElement.scrollHeight}})},500)),this.addListener("resize",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"resize",target:"window",metadata:{width:window.innerWidth,height:window.innerHeight}})},500)),this.addListener("visibilitychange",()=>{this.buffer.push({timestamp:Date.now(),type:"visibility",target:"document",value:document.visibilityState})}),this.addListener("copy",n=>{this.buffer.push({timestamp:Date.now(),type:"copy",target:f(n.target)})}),this.addListener("paste",n=>{this.buffer.push({timestamp:Date.now(),type:"paste",target:f(n.target)})});let e=history.pushState.bind(history),t=history.replaceState.bind(history),r=this;history.pushState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"pushState"}}),e(...n)},history.replaceState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"replaceState"}}),t(...n)},this.addListener("popstate",()=>{this.buffer.push({timestamp:Date.now(),type:"navigation",target:window.location.href,metadata:{method:"popstate"}})})}stop(){for(let{event:e,handler:t,options:r}of this.listeners)(e==="visibilitychange"?document:window).removeEventListener(e,t,r);this.listeners=[]}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addListener(e,t,r){(e==="visibilitychange"?document:window).addEventListener(e,t,r),this.listeners.push({event:e,handler:t,options:r})}throttle(e,t){let r=0;return()=>{let n=Date.now();n-r>=t&&(r=n,e())}}};var k=class{collect(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset(),screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio,colorDepth:screen.colorDepth,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,online:navigator.onLine,hardwareConcurrency:navigator.hardwareConcurrency||0,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,connection:this.getConnection(),memory:this.getMemory()}}getConnection(){let e=navigator.connection;return e?{effectiveType:e.effectiveType||"unknown",downlink:e.downlink||0,rtt:e.rtt||0,saveData:e.saveData||!1}:null}getMemory(){let e=performance.memory;return e?{jsHeapSizeLimit:e.jsHeapSizeLimit,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}:null}};var C=class{constructor(){this.lcp=null;this.fid=null;this.cls=null;this.observers=[]}start(){this.observeLCP(),this.observeFID(),this.observeCLS()}stop(){for(let e of this.observers)e.disconnect();this.observers=[]}collect(){let e=performance.getEntriesByType("navigation")[0],t=performance.getEntriesByType("paint"),r=performance.getEntriesByType("resource"),n=t.find(a=>a.name==="first-paint"),o=t.find(a=>a.name==="first-contentful-paint");return{navigationTiming:e?{redirectTime:e.redirectEnd-e.redirectStart,dnsTime:e.domainLookupEnd-e.domainLookupStart,tcpTime:e.connectEnd-e.connectStart,tlsTime:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,downloadTime:e.responseEnd-e.responseStart,domParsing:e.domInteractive-e.responseEnd,domContentLoaded:e.domContentLoadedEventEnd-e.domContentLoadedEventStart,loadEvent:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-e.startTime}:{},resourceCount:r.length,totalTransferSize:r.reduce((a,c)=>a+(c.transferSize||0),0),domContentLoaded:e?e.domContentLoadedEventEnd-e.startTime:null,loadComplete:e?e.loadEventEnd-e.startTime:null,firstPaint:n?n.startTime:null,firstContentfulPaint:o?o.startTime:null,largestContentfulPaint:this.lcp,firstInputDelay:this.fid,cumulativeLayoutShift:this.cls,timeToInteractive:null}}observeLCP(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.lcp=r[r.length-1].startTime)});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}}observeFID(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.fid=r[0].processingStart-r[0].startTime)});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}}observeCLS(){try{let e=0,t=new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.value);this.cls=e});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t)}catch{}}};var x=class{constructor(e){this.config=e}collect(){return{localStorage:this.config.captureLocalStorage?this.collectStorage(localStorage):{},sessionStorage:this.config.captureSessionStorage?this.collectStorage(sessionStorage):{},cookies:this.config.captureCookies?this.collectCookies():[]}}collectStorage(e){let t={};try{for(let r=0;r<e.length;r++){let n=e.key(r);if(!n)continue;if(this.config.sensitiveFields.some(a=>n.toLowerCase().includes(a.toLowerCase())))t[n]="[REDACTED]";else{let a=e.getItem(n)||"";t[n]=a.length>500?a.slice(0,500)+"...[truncated]":a}}}catch{}return t}collectCookies(){try{return document.cookie.split(";").map(e=>e.trim().split("=")[0]).filter(Boolean)}catch{return[]}}};var R=class{async capture(){try{let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return null;let r=window.innerWidth,n=window.innerHeight,o=Math.min(window.devicePixelRatio,2);e.width=r*o,e.height=n*o,t.scale(o,o);let a=this.domToSvg(r,n);return a?new Promise(c=>{let i=new Image;i.onload=()=>{t.drawImage(i,0,0);try{let u=e.toDataURL("image/png",.8);c(u)}catch{c(null)}},i.onerror=()=>c(null),i.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(a)}`,setTimeout(()=>c(null),3e3)}):null}catch{return null}}domToSvg(e,t){try{let r=document.documentElement.cloneNode(!0);r.querySelectorAll("script").forEach(a=>a.remove());let o=new XMLSerializer().serializeToString(r);return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">
4
+ `)||null}catch{return null}}};var S=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new u(e.maxErrors)}start(){this.errorHandler=e=>{this.buffer.push({timestamp:Date.now(),message:e.message||"Unknown error",stack:e.error?.stack||null,filename:e.filename||null,lineno:e.lineno||null,colno:e.colno||null,type:"uncaught",context:this.getContext(e.error)})},this.rejectionHandler=e=>{let t=e.reason;this.buffer.push({timestamp:Date.now(),message:t instanceof Error?t.message:String(t),stack:t instanceof Error&&t.stack||null,filename:null,lineno:null,colno:null,type:"unhandledrejection",context:t instanceof Error?this.getContext(t):null})},this.resourceErrorHandler=e=>{let t=e.target;!t||!(t instanceof HTMLElement)||(t.tagName==="SCRIPT"||t.tagName==="LINK"||t.tagName==="IMG")&&this.buffer.push({timestamp:Date.now(),message:`Failed to load ${t.tagName.toLowerCase()}: ${t.src||t.href||"unknown"}`,stack:null,filename:t.src||t.href||null,lineno:null,colno:null,type:"resource",context:null})},window.addEventListener("error",this.errorHandler),window.addEventListener("unhandledrejection",this.rejectionHandler),window.addEventListener("error",this.resourceErrorHandler,!0)}stop(){this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null),this.resourceErrorHandler&&(window.removeEventListener("error",this.resourceErrorHandler,!0),this.resourceErrorHandler=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}getContext(e){if(!e)return null;try{let t=e.stack;if(!t)return null;let r=t.match(/at\s+(.+?)\s+\(/);return r?r[1]:null}catch{return null}}};var E=class{constructor(e){this.listeners=[];this.buffer=new u(e.maxUserActions)}start(){this.addListener("click",n=>{let o=n.target;this.buffer.push({timestamp:Date.now(),type:"click",target:f(o),metadata:{x:n.clientX,y:n.clientY,button:n.button}})},!0),this.addListener("input",n=>{let o=n.target,a=o.type==="password"||o.type==="hidden"||o.name?.toLowerCase().includes("password")||o.name?.toLowerCase().includes("token")||o.name?.toLowerCase().includes("secret");this.buffer.push({timestamp:Date.now(),type:"input",target:f(o),value:a?"[REDACTED]":o.value?.slice(0,50)||"",metadata:{inputType:o.type,name:o.name}})},!0),this.addListener("scroll",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"scroll",target:"window",metadata:{scrollX:window.scrollX,scrollY:window.scrollY,scrollHeight:document.documentElement.scrollHeight}})},500)),this.addListener("resize",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"resize",target:"window",metadata:{width:window.innerWidth,height:window.innerHeight}})},500)),this.addListener("visibilitychange",()=>{this.buffer.push({timestamp:Date.now(),type:"visibility",target:"document",value:document.visibilityState})}),this.addListener("copy",n=>{this.buffer.push({timestamp:Date.now(),type:"copy",target:f(n.target)})}),this.addListener("paste",n=>{this.buffer.push({timestamp:Date.now(),type:"paste",target:f(n.target)})});let e=history.pushState.bind(history),t=history.replaceState.bind(history),r=this;history.pushState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"pushState"}}),e(...n)},history.replaceState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"replaceState"}}),t(...n)},this.addListener("popstate",()=>{this.buffer.push({timestamp:Date.now(),type:"navigation",target:window.location.href,metadata:{method:"popstate"}})})}stop(){for(let{event:e,handler:t,options:r}of this.listeners)(e==="visibilitychange"?document:window).removeEventListener(e,t,r);this.listeners=[]}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addListener(e,t,r){(e==="visibilitychange"?document:window).addEventListener(e,t,r),this.listeners.push({event:e,handler:t,options:r})}throttle(e,t){let r=0;return()=>{let n=Date.now();n-r>=t&&(r=n,e())}}};var k=class{collect(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset(),screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio,colorDepth:screen.colorDepth,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,online:navigator.onLine,hardwareConcurrency:navigator.hardwareConcurrency||0,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,connection:this.getConnection(),memory:this.getMemory()}}getConnection(){let e=navigator.connection;return e?{effectiveType:e.effectiveType||"unknown",downlink:e.downlink||0,rtt:e.rtt||0,saveData:e.saveData||!1}:null}getMemory(){let e=performance.memory;return e?{jsHeapSizeLimit:e.jsHeapSizeLimit,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}:null}};var U=class{constructor(){this.lcp=null;this.fid=null;this.cls=null;this.observers=[]}start(){this.observeLCP(),this.observeFID(),this.observeCLS()}stop(){for(let e of this.observers)e.disconnect();this.observers=[]}collect(){let e=performance.getEntriesByType("navigation")[0],t=performance.getEntriesByType("paint"),r=performance.getEntriesByType("resource"),n=t.find(a=>a.name==="first-paint"),o=t.find(a=>a.name==="first-contentful-paint");return{navigationTiming:e?{redirectTime:e.redirectEnd-e.redirectStart,dnsTime:e.domainLookupEnd-e.domainLookupStart,tcpTime:e.connectEnd-e.connectStart,tlsTime:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,downloadTime:e.responseEnd-e.responseStart,domParsing:e.domInteractive-e.responseEnd,domContentLoaded:e.domContentLoadedEventEnd-e.domContentLoadedEventStart,loadEvent:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-e.startTime}:{},resourceCount:r.length,totalTransferSize:r.reduce((a,c)=>a+(c.transferSize||0),0),domContentLoaded:e?e.domContentLoadedEventEnd-e.startTime:null,loadComplete:e?e.loadEventEnd-e.startTime:null,firstPaint:n?n.startTime:null,firstContentfulPaint:o?o.startTime:null,largestContentfulPaint:this.lcp,firstInputDelay:this.fid,cumulativeLayoutShift:this.cls,timeToInteractive:null}}observeLCP(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.lcp=r[r.length-1].startTime)});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}}observeFID(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.fid=r[0].processingStart-r[0].startTime)});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}}observeCLS(){try{let e=0,t=new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.value);this.cls=e});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t)}catch{}}};var C=class{constructor(e){this.config=e}collect(){return{localStorage:this.config.captureLocalStorage?this.collectStorage(localStorage):{},sessionStorage:this.config.captureSessionStorage?this.collectStorage(sessionStorage):{},cookies:this.config.captureCookies?this.collectCookies():[]}}collectStorage(e){let t={};try{for(let r=0;r<e.length;r++){let n=e.key(r);if(!n)continue;if(this.config.sensitiveFields.some(a=>n.toLowerCase().includes(a.toLowerCase())))t[n]="[REDACTED]";else{let a=e.getItem(n)||"";t[n]=a.length>500?a.slice(0,500)+"...[truncated]":a}}}catch{}return t}collectCookies(){try{return document.cookie.split(";").map(e=>e.trim().split("=")[0]).filter(Boolean)}catch{return[]}}};var R=class{async capture(){try{let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return null;let r=window.innerWidth,n=window.innerHeight,o=Math.min(window.devicePixelRatio,2);e.width=r*o,e.height=n*o,t.scale(o,o);let a=this.domToSvg(r,n);return a?new Promise(c=>{let i=new Image;i.onload=()=>{t.drawImage(i,0,0);try{let l=e.toDataURL("image/png",.8);c(l)}catch{c(null)}},i.onerror=()=>c(null),i.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(a)}`,setTimeout(()=>c(null),3e3)}):null}catch{return null}}domToSvg(e,t){try{let r=document.documentElement.cloneNode(!0);r.querySelectorAll("script").forEach(a=>a.remove());let o=new XMLSerializer().serializeToString(r);return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">
5
5
  <foreignObject width="100%" height="100%">
6
6
  ${o}
7
7
  </foreignObject>
8
- </svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(n=>n.remove()),e.querySelectorAll('input[type="password"], input[name*="token"], input[name*="secret"]').forEach(n=>n.value="[REDACTED]"),e.outerHTML.slice(0,5e5)}catch{return null}}};var U=class{collect(){let e={},t=!1,r=window.posthog;if(r?.getFeatureFlag)try{let c=r.getAllFlags?.()||r.getFeatureFlags?.()||{};e.posthog=c,t=!0}catch{}let n=window.ldclient;if(n?.allFlags)try{e.launchdarkly=n.allFlags(),t=!0}catch{}let o=window.statsig;if(o?.getExperiment||o?.checkGate)try{e.statsig={detected:!0},t=!0}catch{}let a=window.unleash;if(a?.getAllToggles)try{e.unleash=a.getAllToggles(),t=!0}catch{}return t?e:null}};var T=class{constructor(){this.mediaRecorder=null;this.chunks=[];this.stream=null;this.recording=!1;this.onChunk=null}get isRecording(){return this.recording}setChunkHandler(e){this.onChunk=e}async start(){if(!this.recording)try{this.stream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!1,preferCurrentTab:!0}),this.chunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:this.getSupportedMimeType(),videoBitsPerSecond:1e6}),this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&(this.chunks.push(e.data),this.onChunk&&e.data.arrayBuffer().then(t=>this.onChunk?.(new Uint8Array(t),!1)))},this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks()},this.stream.getVideoTracks()[0].onended=()=>{this.stop()},this.mediaRecorder.start(1e3),this.recording=!0}catch{this.recording=!1,this.stream=null,this.mediaRecorder=null}}stop(){return new Promise(e=>{if(!this.mediaRecorder||!this.recording){e(null);return}this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks();let t=new Blob(this.chunks,{type:this.getSupportedMimeType()});this.chunks=[],e(t)},this.mediaRecorder.stop()})}stopTracks(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}getSupportedMimeType(){let e=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"];for(let t of e)if(MediaRecorder.isTypeSupported(t))return t;return"video/webm"}};var B=class{constructor(){this.container=null}mount(){this.container||(this.container=document.createElement("div"),this.container.id="bug-jar-session-border",this.container.setAttribute("aria-hidden","true"),this.container.innerHTML=`
8
+ </svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(n=>n.remove()),e.querySelectorAll('input[type="password"], input[name*="token"], input[name*="secret"]').forEach(n=>n.value="[REDACTED]"),e.outerHTML.slice(0,5e5)}catch{return null}}};var x=class{collect(){let e={},t=!1,r=window.posthog;if(r?.getFeatureFlag)try{let c=r.getAllFlags?.()||r.getFeatureFlags?.()||{};e.posthog=c,t=!0}catch{}let n=window.ldclient;if(n?.allFlags)try{e.launchdarkly=n.allFlags(),t=!0}catch{}let o=window.statsig;if(o?.getExperiment||o?.checkGate)try{e.statsig={detected:!0},t=!0}catch{}let a=window.unleash;if(a?.getAllToggles)try{e.unleash=a.getAllToggles(),t=!0}catch{}return t?e:null}};var T=class{constructor(){this.mediaRecorder=null;this.chunks=[];this.stream=null;this.recording=!1;this.onChunk=null}get isRecording(){return this.recording}setChunkHandler(e){this.onChunk=e}async start(){if(!this.recording)try{this.stream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!1,preferCurrentTab:!0}),this.chunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:this.getSupportedMimeType(),videoBitsPerSecond:1e6}),this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&(this.chunks.push(e.data),this.onChunk&&e.data.arrayBuffer().then(t=>this.onChunk?.(new Uint8Array(t),!1)).catch(()=>{}))},this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks()},this.stream.getVideoTracks()[0].onended=()=>{this.stop()},this.mediaRecorder.start(1e3),this.recording=!0}catch{this.recording=!1,this.stream=null,this.mediaRecorder=null}}stop(){return new Promise(e=>{if(!this.mediaRecorder||!this.recording){e(null);return}this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks();let t=new Blob(this.chunks,{type:this.getSupportedMimeType()});this.chunks=[],e(t)},this.mediaRecorder.stop()})}stopTracks(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}getSupportedMimeType(){let e=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"];for(let t of e)if(MediaRecorder.isTypeSupported(t))return t;return"video/webm"}};var A=class{constructor(){this.container=null}mount(){this.container||(this.container=document.createElement("div"),this.container.id="bug-jar-session-border",this.container.setAttribute("aria-hidden","true"),this.container.innerHTML=`
9
9
  <div class="bug-jar-session-border-glow"></div>
10
10
  <div class="bug-jar-session-pill">
11
11
  <span class="bug-jar-session-pill-dot"></span>
@@ -80,7 +80,7 @@
80
80
  .bug-jar-session-border-glow { animation: none; }
81
81
  .bug-jar-session-pill-dot { animation: none; }
82
82
  }
83
- `,document.head.appendChild(e)}};function I(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function F(s,e){let t=`${s.replace(/\/$/,"")}/${encodeURIComponent(e)}`,r=await fetch(t,{method:"GET",credentials:"include"});if(!r.ok)throw new Error(`Failed to load debug session (${r.status})`);return await r.json()}function j(s){let e=s.replace(/\/$/,"");return async t=>{let r=`${e}/${encodeURIComponent(t.token)}/chunk-url`,n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({pageId:t.pageId,stream:t.stream,seq:t.seq})});if(!n.ok)throw new Error(`Failed to get chunk URL (${n.status})`);return await n.json()}}async function q(s,e,t,r){let o=`${s.replace(/\/$/,"")}/${encodeURIComponent(e)}/meta`;await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",keepalive:!0,body:JSON.stringify({pageId:t,meta:r})})}async function ee(){let s=await import("libsodium-wrappers"),e=s.default??s;return await e.ready,e}function te(s){let e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}var ne=[66,74,83,49],A=class{constructor(){this.sodium=null;this.state=null;this.headerEnvelope=null}async init(e){let t=await ee();this.sodium=t;let r=te(e),n=t.crypto_secretstream_xchacha20poly1305_keygen(),o=t.crypto_box_seal(n,r),{state:a,header:c}=t.crypto_secretstream_xchacha20poly1305_init_push(n);this.state=a;let i=new Uint8Array(ne),u=new Uint8Array([1]),p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,o.length,!0);let m=re([i,u,p,o,c]);return this.headerEnvelope=m,m}get header(){if(!this.headerEnvelope)throw new Error("StreamEncryptor not initialized");return this.headerEnvelope}encryptChunk(e,t=!1){if(!this.sodium||!this.state)throw new Error("StreamEncryptor not initialized");let r=t?this.sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL:this.sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;return this.sodium.crypto_secretstream_xchacha20poly1305_push(this.state,e,null,r)}};function re(s){let e=s.reduce((n,o)=>n+o.length,0),t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var y=class{constructor(e,t,r,n,o){this.token=e;this.pageId=t;this.stream=r;this.publicKey=n;this.fetchChunkUrl=o;this.encryptor=new A;this.seq=0;this.initialized=!1;this.queue=Promise.resolve()}async ensureInit(){if(this.initialized)return;this.initialized=!0;let e=await this.encryptor.init(this.publicKey);await this.putChunk(e)}pushChunk(e,t=!1){this.queue=this.queue.then(async()=>{await this.ensureInit();let r=this.encryptor.encryptChunk(e,t);await this.putChunk(r)})}async flush(){await this.queue}async putChunk(e){let{uploadUrl:t}=await this.fetchChunkUrl({token:this.token,pageId:this.pageId,stream:this.stream,seq:this.seq});this.seq+=1,await fetch(t,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:e})}};var L="bug-jar-session";function M(){if(typeof window>"u")return;let e=window.location.hostname.split(".");return e.length<2?void 0:`.${e.slice(-2).join(".")}`}function _(){if(typeof document>"u")return null;let s=document.cookie.split("; ").find(t=>t.startsWith(`${L}=`));if(!s)return null;let e=s.slice(L.length+1);return e?decodeURIComponent(e):null}function O(s,e){if(typeof document>"u")return;let t=M(),r=new Date(e).toUTCString(),n=window.location.protocol==="https:"?"; Secure":"",o=t?`; Domain=${t}`:"";document.cookie=`${L}=${encodeURIComponent(s)}; Path=/; Expires=${r}; SameSite=Lax${o}${n}`}function z(){if(typeof document>"u")return;let s=M(),e=s?`; Domain=${s}`:"";document.cookie=`${L}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${e}`}function H(s){let e=[];e.push(`Bug Report: ${s.id}`),e.push(`URL: ${s.url}`),e.push(`Time: ${new Date(s.timestamp).toISOString()}`),e.push(`User Description: "${s.userDescription}"`),e.push(""),e.push("## Environment"),e.push(`Browser: ${se(s.environment.userAgent)}`),e.push(`Viewport: ${s.environment.viewportWidth}x${s.environment.viewportHeight}`),e.push(`Connection: ${s.environment.connection?.effectiveType||"unknown"}`),e.push(`Online: ${s.environment.online}`),e.push(""),e.push("## Network Activity");let t=s.network.length,r=s.network.filter(i=>i.error||i.status&&i.status>=400),n=s.network.filter(i=>i.duration&&i.duration>3e3);if(e.push(`Total requests: ${t}`),r.length>0){e.push(`Failed requests (${r.length}):`);for(let i of r)e.push(` - ${i.method} ${i.url} \u2192 ${i.error||`HTTP ${i.status}`}`)}if(n.length>0){e.push(`Slow requests >3s (${n.length}):`);for(let i of n)e.push(` - ${i.method} ${i.url} (${Math.round(i.duration)}ms)`)}if(e.push(""),e.push("## Errors"),s.errors.length===0)e.push("No errors captured.");else{e.push(`Total errors: ${s.errors.length}`);for(let i of s.errors)e.push(` - [${i.type}] ${i.message}`),i.filename&&e.push(` at ${i.filename}:${i.lineno}:${i.colno}`)}e.push(""),e.push("## Console");let o={log:0,warn:0,error:0,info:0,debug:0};for(let i of s.console)o[i.level]++;e.push(`Logs: ${o.log}, Warnings: ${o.warn}, Errors: ${o.error}, Info: ${o.info}, Debug: ${o.debug}`);let a=s.console.filter(i=>i.level==="error");if(a.length>0){e.push("Console errors:");for(let i of a)e.push(` - ${i.args.map(u=>typeof u=="string"?u:JSON.stringify(u)).join(" ")}`)}e.push(""),e.push("## User Actions"),e.push(`Total actions: ${s.userActions.length}`);let c={};for(let i of s.userActions)c[i.type]=(c[i.type]||0)+1;for(let[i,u]of Object.entries(c))e.push(` - ${i}: ${u}`);if(s.userActions.length>0){let i=s.userActions[0].timestamp,p=((s.userActions[s.userActions.length-1].timestamp-i)/1e3).toFixed(1);e.push(`Session duration: ${p}s`)}if(e.push(""),s.performance){e.push("## Performance");let i=s.performance;i.largestContentfulPaint&&e.push(`LCP: ${Math.round(i.largestContentfulPaint)}ms`),i.firstInputDelay&&e.push(`FID: ${Math.round(i.firstInputDelay)}ms`),i.cumulativeLayoutShift!==null&&e.push(`CLS: ${i.cumulativeLayoutShift?.toFixed(3)}`),i.loadComplete&&e.push(`Page Load: ${Math.round(i.loadComplete)}ms`),e.push(`Resources: ${i.resourceCount} (${oe(i.totalTransferSize)})`)}return e.join(`
84
- `)}function se(s){return s.includes("Chrome/")?`Chrome ${s.match(/Chrome\/(\d+)/)?.[1]||""}`:s.includes("Firefox/")?`Firefox ${s.match(/Firefox\/(\d+)/)?.[1]||""}`:s.includes("Safari/")&&!s.includes("Chrome")?`Safari ${s.match(/Version\/(\d+)/)?.[1]||""}`:s.slice(0,50)}function oe(s){return s<1024?`${s}B`:s<1024*1024?`${(s/1024).toFixed(1)}KB`:`${(s/(1024*1024)).toFixed(1)}MB`}async function P(s,e){let t=[],r=JSON.stringify(s,null,2);t.push({name:"report.json",content:new TextEncoder().encode(r)});let n=H(s);if(t.push({name:"summary.md",content:new TextEncoder().encode(n)}),s.screenshot){let o=ie(s.screenshot);o&&t.push({name:"screenshot.png",content:o})}if(e){let o=new Uint8Array(await e.arrayBuffer());t.push({name:"recording.webm",content:o})}return ae(t)}function ie(s){try{let e=s.split(",")[1];if(!e)return null;let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}catch{return null}}function ae(s){let e=[],t=[],r=0;for(let i of s){let u=new TextEncoder().encode(i.name),p=de(i.content),m=ce(u,i.content.length,p);e.push(m),e.push(u),e.push(i.content);let J=ue(u,i.content.length,p,r);t.push(J),t.push(u),r+=m.length+u.length+i.content.length}let n=r,o=0;for(let i of t)o+=i.length;let a=le(s.length,o,n),c=[...e,...t,a].map(i=>i.buffer);return new Blob(c,{type:"application/zip"})}function ce(s,e,t){let r=new Uint8Array(30),n=new DataView(r.buffer);return n.setUint32(0,67324752,!0),n.setUint16(4,20,!0),n.setUint16(6,0,!0),n.setUint16(8,0,!0),n.setUint16(10,0,!0),n.setUint16(12,0,!0),n.setUint32(14,t,!0),n.setUint32(18,e,!0),n.setUint32(22,e,!0),n.setUint16(26,s.length,!0),n.setUint16(28,0,!0),r}function ue(s,e,t,r){let n=new Uint8Array(46),o=new DataView(n.buffer);return o.setUint32(0,33639248,!0),o.setUint16(4,20,!0),o.setUint16(6,20,!0),o.setUint16(8,0,!0),o.setUint16(10,0,!0),o.setUint16(12,0,!0),o.setUint16(14,0,!0),o.setUint32(16,t,!0),o.setUint32(20,e,!0),o.setUint32(24,e,!0),o.setUint16(28,s.length,!0),o.setUint16(30,0,!0),o.setUint16(32,0,!0),o.setUint16(34,0,!0),o.setUint16(36,0,!0),o.setUint32(38,0,!0),o.setUint32(42,r,!0),n}function le(s,e,t){let r=new Uint8Array(22),n=new DataView(r.buffer);return n.setUint32(0,101010256,!0),n.setUint16(4,0,!0),n.setUint16(6,0,!0),n.setUint16(8,s,!0),n.setUint16(10,s,!0),n.setUint32(12,e,!0),n.setUint32(16,t,!0),n.setUint16(20,0,!0),r}function de(s){let e=4294967295;for(let t=0;t<s.length;t++){e^=s[t];for(let r=0;r<8;r++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}var pe="0.6.0",he={maxNetworkEntries:100,maxConsoleEntries:200,maxUserActions:150,maxErrors:50,captureScreenshot:!0,captureHtmlSnapshot:!0,captureCookies:!0,captureLocalStorage:!0,captureSessionStorage:!0,capturePerformance:!0,captureWebVitals:!0,captureMemory:!0,captureConnectivity:!0,sensitiveFields:["password","token","secret","authorization","cookie","session","credit_card","cvv","ssn","cpf"],endpoint:void 0,onCapture:void 0,debugToken:void 0,debugSessionEndpoint:void 0},g=class{constructor(e={}){this.sessionBorder=null;this.debugSession=null;this.dataUploader=null;this.videoUploader=null;this.pageId=h();this.dataInterval=null;this.finalized=!1;this.started=!1;this.config={...he,...e},this.network=new w(this.config),this.console=new b(this.config),this.errors=new S(this.config),this.userActions=new E(this.config),this.environment=new k,this.performance=new C,this.storage=new x(this.config),this.screenshot=new R,this.featureFlags=new U,this.screenRecorder=new T}start(){if(this.started)return;this.started=!0,this.network.start(),this.console.start(),this.errors.start(),this.userActions.start(),this.config.captureWebVitals&&this.performance.start();let e=this.config.debugToken??I()??_();e&&this.startDebugSession(e)}stop(){this.started&&(this.started=!1,this.network.stop(),this.console.stop(),this.errors.stop(),this.userActions.stop(),this.performance.stop(),this.sessionBorder?.unmount())}async startRecording(){await this.screenRecorder.start()}get isRecording(){return this.screenRecorder.isRecording}async capture(e=""){let t={id:h(),timestamp:Date.now(),url:window.location.href,title:document.title,userDescription:e,environment:this.environment.collect(),network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),performance:this.config.capturePerformance?this.performance.collect():null,storage:this.storage.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null,htmlSnapshot:this.config.captureHtmlSnapshot?this.screenshot.captureHtml():null,featureFlags:this.featureFlags.collect(),metadata:{},version:pe};return this.config.onCapture&&this.config.onCapture(t),t}async captureAndExport(e=""){let t=await this.screenRecorder.stop(),r=await this.capture(e);if(this.config.endpoint)if(t){let n=new FormData;n.append("report",JSON.stringify(r)),n.append("video",t,"recording.webm"),await fetch(this.config.endpoint,{method:"POST",body:n})}else await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});else{let n=await P(r,t),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=`bug-report-${r.id}.zip`,a.click(),URL.revokeObjectURL(o)}return r}getReport(){return this.capture()}async startDebugSession(e){if(!this.config.debugSessionEndpoint)return;let t=this.config.debugSessionEndpoint,r=()=>{this.sessionBorder=new B,this.sessionBorder.mount()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",r):r();try{this.debugSession=await F(t,e),O(this.debugSession.token,this.debugSession.expiresAt);let n=j(t);this.dataUploader=new y(this.debugSession.token,this.pageId,"data",this.debugSession.publicKey,n),this.videoUploader=new y(this.debugSession.token,this.pageId,"video",this.debugSession.publicKey,n),q(t,this.debugSession.token,this.pageId,{url:window.location.href,title:document.title,startedAt:Date.now(),environment:this.environment.collect()}),this.screenRecorder.setChunkHandler(o=>{this.videoUploader?.pushChunk(o)}),await this.screenRecorder.start(),this.startDataStreaming(),this.registerFlushHandlers()}catch{this.sessionBorder?.unmount()}}startDataStreaming(){let e=t=>{if(!this.dataUploader)return;let r={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),storage:this.storage.collect(),featureFlags:this.featureFlags.collect()},n=new TextEncoder().encode(JSON.stringify(r)+`
85
- `);this.dataUploader.pushChunk(n,t)};this.dataInterval=setInterval(()=>e(!1),5e3)}registerFlushHandlers(){let e=()=>{this.finalizePage()};window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()})}async finalizePage(){if(this.finalized||!this.debugSession)return;this.finalized=!0,this.dataInterval&&(clearInterval(this.dataInterval),this.dataInterval=null);let e={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),storage:this.storage.collect(),featureFlags:this.featureFlags.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null},t=new TextEncoder().encode(JSON.stringify(e)+`
86
- `);this.dataUploader?.pushChunk(t,!0),await this.screenRecorder.stop(),await Promise.allSettled([this.dataUploader?.flush()??Promise.resolve(),this.videoUploader?.flush()??Promise.resolve()])}endDebugSession(){z(),this.sessionBorder?.unmount(),this.finalizePage()}};function N(s={}){let e=new g(s);return e.start(),e}typeof window<"u"&&(window.BugJar={BugJar:g,init:N});var fe=g;0&&(module.exports={BugJar,exportAsZip,generateSummary,init});
83
+ `,document.head.appendChild(e)}};function j(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function _(s,e,t=fetch){let r=`${s.replace(/\/$/,"")}/${encodeURIComponent(e)}`,n=await t(r,{method:"GET",credentials:"include"});if(!n.ok){let o=new Error(`Failed to load debug session (${n.status})`);throw o.status=n.status,o}return await n.json()}function q(s,e=fetch){let t=s.replace(/\/$/,"");return async r=>{let n=`${t}/${encodeURIComponent(r.token)}/chunk-url`,o=await e(n,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({pageId:r.pageId,stream:r.stream,seq:r.seq})});if(!o.ok)throw new Error(`Failed to get chunk URL (${o.status})`);return await o.json()}}async function O(s,e,t,r,n=fetch){let a=`${s.replace(/\/$/,"")}/${encodeURIComponent(e)}/meta`;await n(a,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",keepalive:!0,body:JSON.stringify({pageId:t,meta:r})})}async function te(){let s=await import("libsodium-wrappers"),e=s.default??s;return await e.ready,e}function re(s){let e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}var ne=[66,74,83,49],B=class{constructor(){this.sodium=null;this.state=null;this.headerEnvelope=null}async init(e){let t=await te();this.sodium=t;let r=re(e),n=t.crypto_secretstream_xchacha20poly1305_keygen(),o=t.crypto_box_seal(n,r),{state:a,header:c}=t.crypto_secretstream_xchacha20poly1305_init_push(n);this.state=a;let i=new Uint8Array(ne),l=new Uint8Array([1]),p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,o.length,!0);let m=se([i,l,p,o,c]);return this.headerEnvelope=m,m}get header(){if(!this.headerEnvelope)throw new Error("StreamEncryptor not initialized");return this.headerEnvelope}encryptChunk(e,t=!1){if(!this.sodium||!this.state)throw new Error("StreamEncryptor not initialized");let r=t?this.sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL:this.sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;return this.sodium.crypto_secretstream_xchacha20poly1305_push(this.state,e,null,r)}};function se(s){let e=s.reduce((n,o)=>n+o.length,0),t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var y=class{constructor(e,t,r,n,o,a=fetch){this.token=e;this.pageId=t;this.stream=r;this.publicKey=n;this.fetchChunkUrl=o;this.rawFetch=a;this.encryptor=new B;this.seq=0;this.initialized=!1;this.queue=Promise.resolve()}async ensureInit(){if(this.initialized)return;this.initialized=!0;let e=await this.encryptor.init(this.publicKey);await this.putChunk(e)}pushChunk(e,t=!1){this.queue=this.queue.then(async()=>{await this.ensureInit();let r=this.encryptor.encryptChunk(e,t);await this.putChunk(r)})}async flush(){await this.queue}async putChunk(e){let{uploadUrl:t}=await this.fetchChunkUrl({token:this.token,pageId:this.pageId,stream:this.stream,seq:this.seq});this.seq+=1,await this.rawFetch(t,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:e})}};var L=class{constructor(e,t,r=fetch){this.baseUrl=e;this.token=t;this.rawFetch=r}async run(){let e=performance.now(),t={ranAt:Date.now(),latencyMs:null,jitterMs:null,downloadMbps:null,uploadMbps:null,durationMs:0};try{let r=await this.measureLatency();t.latencyMs=r.min,t.jitterMs=r.jitter}catch{}try{t.downloadMbps=await this.measureDownload()}catch{}try{t.uploadMbps=await this.measureUpload()}catch{}return t.durationMs=Math.round(performance.now()-e),t}url(e){return`${this.baseUrl.replace(/\/$/,"")}/${encodeURIComponent(this.token)}/${e}`}async measureLatency(){let e=[];for(let o=0;o<5;o++){let a=performance.now();await this.rawFetch(this.url(`speedtest/ping?n=${o}`),{cache:"no-store"}),e.push(performance.now()-a)}let t=Math.min(...e),r=e.reduce((o,a)=>o+a,0)/e.length,n=e.reduce((o,a)=>o+Math.abs(a-r),0)/e.length;return{min:Math.round(t),jitter:Math.round(n)}}async measureDownload(){let e=Math.floor(2097152),t=performance.now(),r=Array.from({length:4},(c,i)=>this.rawFetch(this.url(`speedtest/download?bytes=${e}&s=${i}`),{cache:"no-store"}).then(l=>l.arrayBuffer())),n=await Promise.all(r),o=(performance.now()-t)/1e3,a=n.reduce((c,i)=>c+i.byteLength,0);return this.toMbps(a,o)}async measureUpload(){let e=new Uint8Array(4194304);crypto.getRandomValues(e.subarray(0,Math.min(65536,4194304)));let t=performance.now();await this.rawFetch(this.url("speedtest/upload"),{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});let r=(performance.now()-t)/1e3;return this.toMbps(4194304,r)}toMbps(e,t){return t<=0?0:Math.round(e*8/t/1e6*100)/100}};var D="bug-jar-session";function N(){if(typeof window>"u")return;let e=window.location.hostname.split(".");return e.length<2?void 0:`.${e.slice(-2).join(".")}`}function z(){if(typeof document>"u")return null;let s=document.cookie.split("; ").find(t=>t.startsWith(`${D}=`));if(!s)return null;let e=s.slice(D.length+1);return e?decodeURIComponent(e):null}function $(s,e){if(typeof document>"u")return;let t=N(),r=new Date(e).toUTCString(),n=window.location.protocol==="https:"?"; Secure":"",o=t?`; Domain=${t}`:"";document.cookie=`${D}=${encodeURIComponent(s)}; Path=/; Expires=${r}; SameSite=Lax${o}${n}`}function F(){if(typeof document>"u")return;let s=N(),e=s?`; Domain=${s}`:"";document.cookie=`${D}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${e}`}function P(s){let e=[];e.push(`Bug Report: ${s.id}`),e.push(`URL: ${s.url}`),e.push(`Time: ${new Date(s.timestamp).toISOString()}`),e.push(`User Description: "${s.userDescription}"`),e.push(""),e.push("## Environment"),e.push(`Browser: ${oe(s.environment.userAgent)}`),e.push(`Viewport: ${s.environment.viewportWidth}x${s.environment.viewportHeight}`),e.push(`Connection: ${s.environment.connection?.effectiveType||"unknown"}`),e.push(`Online: ${s.environment.online}`),e.push(""),e.push("## Network Activity");let t=s.network.length,r=s.network.filter(i=>i.error||i.status&&i.status>=400),n=s.network.filter(i=>i.duration&&i.duration>3e3);if(e.push(`Total requests: ${t}`),r.length>0){e.push(`Failed requests (${r.length}):`);for(let i of r)e.push(` - ${i.method} ${i.url} \u2192 ${i.error||`HTTP ${i.status}`}`)}if(n.length>0){e.push(`Slow requests >3s (${n.length}):`);for(let i of n)e.push(` - ${i.method} ${i.url} (${Math.round(i.duration)}ms)`)}if(e.push(""),e.push("## Errors"),s.errors.length===0)e.push("No errors captured.");else{e.push(`Total errors: ${s.errors.length}`);for(let i of s.errors)e.push(` - [${i.type}] ${i.message}`),i.filename&&e.push(` at ${i.filename}:${i.lineno}:${i.colno}`)}e.push(""),e.push("## Console");let o={log:0,warn:0,error:0,info:0,debug:0};for(let i of s.console)o[i.level]++;e.push(`Logs: ${o.log}, Warnings: ${o.warn}, Errors: ${o.error}, Info: ${o.info}, Debug: ${o.debug}`);let a=s.console.filter(i=>i.level==="error");if(a.length>0){e.push("Console errors:");for(let i of a)e.push(` - ${i.args.map(l=>typeof l=="string"?l:JSON.stringify(l)).join(" ")}`)}e.push(""),e.push("## User Actions"),e.push(`Total actions: ${s.userActions.length}`);let c={};for(let i of s.userActions)c[i.type]=(c[i.type]||0)+1;for(let[i,l]of Object.entries(c))e.push(` - ${i}: ${l}`);if(s.userActions.length>0){let i=s.userActions[0].timestamp,p=((s.userActions[s.userActions.length-1].timestamp-i)/1e3).toFixed(1);e.push(`Session duration: ${p}s`)}if(e.push(""),s.performance){e.push("## Performance");let i=s.performance;i.largestContentfulPaint&&e.push(`LCP: ${Math.round(i.largestContentfulPaint)}ms`),i.firstInputDelay&&e.push(`FID: ${Math.round(i.firstInputDelay)}ms`),i.cumulativeLayoutShift!==null&&e.push(`CLS: ${i.cumulativeLayoutShift?.toFixed(3)}`),i.loadComplete&&e.push(`Page Load: ${Math.round(i.loadComplete)}ms`),e.push(`Resources: ${i.resourceCount} (${ie(i.totalTransferSize)})`)}return e.join(`
84
+ `)}function oe(s){return s.includes("Chrome/")?`Chrome ${s.match(/Chrome\/(\d+)/)?.[1]||""}`:s.includes("Firefox/")?`Firefox ${s.match(/Firefox\/(\d+)/)?.[1]||""}`:s.includes("Safari/")&&!s.includes("Chrome")?`Safari ${s.match(/Version\/(\d+)/)?.[1]||""}`:s.slice(0,50)}function ie(s){return s<1024?`${s}B`:s<1024*1024?`${(s/1024).toFixed(1)}KB`:`${(s/(1024*1024)).toFixed(1)}MB`}async function H(s,e){let t=[],r=JSON.stringify(s,null,2);t.push({name:"report.json",content:new TextEncoder().encode(r)});let n=P(s);if(t.push({name:"summary.md",content:new TextEncoder().encode(n)}),s.screenshot){let o=ae(s.screenshot);o&&t.push({name:"screenshot.png",content:o})}if(e){let o=new Uint8Array(await e.arrayBuffer());t.push({name:"recording.webm",content:o})}return ce(t)}function ae(s){try{let e=s.split(",")[1];if(!e)return null;let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}catch{return null}}function ce(s){let e=[],t=[],r=0;for(let i of s){let l=new TextEncoder().encode(i.name),p=pe(i.content),m=le(l,i.content.length,p);e.push(m),e.push(l),e.push(i.content);let J=ue(l,i.content.length,p,r);t.push(J),t.push(l),r+=m.length+l.length+i.content.length}let n=r,o=0;for(let i of t)o+=i.length;let a=de(s.length,o,n),c=[...e,...t,a].map(i=>i.buffer);return new Blob(c,{type:"application/zip"})}function le(s,e,t){let r=new Uint8Array(30),n=new DataView(r.buffer);return n.setUint32(0,67324752,!0),n.setUint16(4,20,!0),n.setUint16(6,0,!0),n.setUint16(8,0,!0),n.setUint16(10,0,!0),n.setUint16(12,0,!0),n.setUint32(14,t,!0),n.setUint32(18,e,!0),n.setUint32(22,e,!0),n.setUint16(26,s.length,!0),n.setUint16(28,0,!0),r}function ue(s,e,t,r){let n=new Uint8Array(46),o=new DataView(n.buffer);return o.setUint32(0,33639248,!0),o.setUint16(4,20,!0),o.setUint16(6,20,!0),o.setUint16(8,0,!0),o.setUint16(10,0,!0),o.setUint16(12,0,!0),o.setUint16(14,0,!0),o.setUint32(16,t,!0),o.setUint32(20,e,!0),o.setUint32(24,e,!0),o.setUint16(28,s.length,!0),o.setUint16(30,0,!0),o.setUint16(32,0,!0),o.setUint16(34,0,!0),o.setUint16(36,0,!0),o.setUint32(38,0,!0),o.setUint32(42,r,!0),n}function de(s,e,t){let r=new Uint8Array(22),n=new DataView(r.buffer);return n.setUint32(0,101010256,!0),n.setUint16(4,0,!0),n.setUint16(6,0,!0),n.setUint16(8,s,!0),n.setUint16(10,s,!0),n.setUint32(12,e,!0),n.setUint32(16,t,!0),n.setUint16(20,0,!0),r}function pe(s){let e=4294967295;for(let t=0;t<s.length;t++){e^=s[t];for(let r=0;r<8;r++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}var he="0.7.1",fe={maxNetworkEntries:100,maxConsoleEntries:200,maxUserActions:150,maxErrors:50,captureScreenshot:!0,captureHtmlSnapshot:!0,captureCookies:!0,captureLocalStorage:!0,captureSessionStorage:!0,capturePerformance:!0,captureWebVitals:!0,captureMemory:!0,captureConnectivity:!0,sensitiveFields:["password","token","secret","authorization","cookie","session","credit_card","cvv","ssn","cpf"],endpoint:void 0,onCapture:void 0,debugToken:void 0,debugSessionEndpoint:void 0},g=class{constructor(e={}){this.sessionBorder=null;this.debugSession=null;this.dataUploader=null;this.videoUploader=null;this.pageId=h();this.dataInterval=null;this.lastFlushTs=0;this.finalized=!1;this.started=!1;this.config={...fe,...e},this.network=new w(this.config),this.console=new b(this.config),this.errors=new S(this.config),this.userActions=new E(this.config),this.environment=new k,this.performance=new U,this.storage=new C(this.config),this.screenshot=new R,this.featureFlags=new x,this.screenRecorder=new T}start(){if(this.started)return;this.started=!0,this.network.start(),this.console.start(),this.errors.start(),this.userActions.start(),this.config.captureWebVitals&&this.performance.start();let e=this.config.debugToken??j(),t=e??z();e&&$(e,Date.now()+1440*60*1e3),t&&this.startDebugSession(t)}stop(){this.started&&(this.started=!1,this.network.stop(),this.console.stop(),this.errors.stop(),this.userActions.stop(),this.performance.stop(),this.sessionBorder?.unmount())}async startRecording(){await this.screenRecorder.start()}get isRecording(){return this.screenRecorder.isRecording}async capture(e=""){let t={id:h(),timestamp:Date.now(),url:window.location.href,title:document.title,userDescription:e,environment:this.environment.collect(),network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),performance:this.config.capturePerformance?this.performance.collect():null,storage:this.storage.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null,htmlSnapshot:this.config.captureHtmlSnapshot?this.screenshot.captureHtml():null,featureFlags:this.featureFlags.collect(),metadata:{},version:he};return this.config.onCapture&&this.config.onCapture(t),t}async captureAndExport(e=""){let t=await this.screenRecorder.stop(),r=await this.capture(e);if(this.config.endpoint)if(t){let n=new FormData;n.append("report",JSON.stringify(r)),n.append("video",t,"recording.webm"),await fetch(this.config.endpoint,{method:"POST",body:n})}else await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});else{let n=await H(r,t),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=`bug-report-${r.id}.zip`,a.click(),URL.revokeObjectURL(o)}return r}getReport(){return this.capture()}async startDebugSession(e){if(!this.config.debugSessionEndpoint)return;let t=this.config.debugSessionEndpoint,r=()=>{this.sessionBorder=new A,this.sessionBorder.mount()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",r):r();try{let n=this.network.getRawFetch();this.debugSession=await _(t,e,n),$(this.debugSession.token,this.debugSession.expiresAt);let o=q(t,n);this.dataUploader=new y(this.debugSession.token,this.pageId,"data",this.debugSession.publicKey,o,n),this.videoUploader=new y(this.debugSession.token,this.pageId,"video",this.debugSession.publicKey,o,n),this.runSpeedtest(t,this.debugSession.token,n),this.startDataStreaming(),this.registerFlushHandlers(),this.screenRecorder.setChunkHandler(a=>{this.videoUploader?.pushChunk(a)}),this.screenRecorder.start()}catch(n){this.sessionBorder?.unmount();let o=n?.status;(o===401||o===403||o===404)&&F()}}startDataStreaming(){let e=t=>{if(!this.dataUploader)return;let r=this.lastFlushTs,n=Date.now(),o={pageId:this.pageId,timestamp:n,url:window.location.href,network:this.network.getEntries().filter(c=>c.timestamp>r),console:this.console.getEntries().filter(c=>c.timestamp>r),errors:this.errors.getEntries().filter(c=>c.timestamp>r),userActions:this.userActions.getEntries().filter(c=>c.timestamp>r)};this.lastFlushTs=n;let a=new TextEncoder().encode(JSON.stringify(o)+`
85
+ `);this.dataUploader.pushChunk(a,t)};this.dataInterval=setInterval(()=>e(!1),5e3)}registerFlushHandlers(){let e=()=>{this.finalizePage()};window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()})}async finalizePage(){if(this.finalized||!this.debugSession)return;this.finalized=!0,this.dataInterval&&(clearInterval(this.dataInterval),this.dataInterval=null);let e={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,final:!0,network:this.network.getEntries().filter(r=>r.timestamp>this.lastFlushTs),console:this.console.getEntries().filter(r=>r.timestamp>this.lastFlushTs),errors:this.errors.getEntries().filter(r=>r.timestamp>this.lastFlushTs),userActions:this.userActions.getEntries().filter(r=>r.timestamp>this.lastFlushTs),storage:this.storage.collect(),featureFlags:this.featureFlags.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null},t=new TextEncoder().encode(JSON.stringify(e)+`
86
+ `);this.dataUploader?.pushChunk(t,!0),await this.screenRecorder.stop(),await Promise.allSettled([this.dataUploader?.flush()??Promise.resolve(),this.videoUploader?.flush()??Promise.resolve()])}async runSpeedtest(e,t,r){let n=null;try{n=await new L(e,t,r).run()}catch{}await O(e,t,this.pageId,{url:window.location.href,title:document.title,startedAt:Date.now(),environment:this.environment.collect(),speedtest:n},r)}endDebugSession(){F(),this.sessionBorder?.unmount(),this.finalizePage()}};function X(s={}){let e=new g(s);return e.start(),e}typeof window<"u"&&(window.BugJar={BugJar:g,init:X});var ge=g;0&&(module.exports={BugJar,exportAsZip,generateSummary,init});
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function P(s,e=1e4){try{let t=new WeakSet,r=JSON.stringify(s,(n,o)=>{if(typeof o=="object"&&o!==null){if(t.has(o))return"[Circular]";t.add(o)}return o instanceof Error?{message:o.message,stack:o.stack,name:o.name}:typeof o=="function"?"[Function]":o instanceof HTMLElement?f(o):o});return r&&r.length>e?r.slice(0,e)+"...[truncated]":r||""}catch{return"[Unserializable]"}}function f(s){if(!s||!(s instanceof Element))return"unknown";let e=s.tagName.toLowerCase(),t=s.id?`#${s.id}`:"",r=s.className&&typeof s.className=="string"?`.${s.className.trim().split(/\s+/).join(".")}`:"",n=s.textContent?.trim().slice(0,30)||"",o=n?` "${n}"`:"";return`${e}${t}${r}${o}`}function d(s,e){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(r=>d(r,e));let t={};for(let[r,n]of Object.entries(s))e.some(a=>r.toLowerCase().includes(a.toLowerCase()))?t[r]="[REDACTED]":typeof n=="object"&&n!==null?t[r]=d(n,e):t[r]=n;return t}var l=class{constructor(e){this.buffer=[];this.maxSize=e}push(e){this.buffer.length>=this.maxSize&&this.buffer.shift(),this.buffer.push(e)}getAll(){return[...this.buffer]}clear(){this.buffer=[]}get length(){return this.buffer.length}};var v=class{constructor(e){this.originalFetch=null;this.originalXhrOpen=null;this.originalXhrSend=null;this.originalXhrSetRequestHeader=null;this.originalSendBeacon=null;this.config=e,this.buffer=new l(e.maxNetworkEntries)}start(){this.interceptFetch(),this.interceptXHR(),this.interceptBeacon()}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXhrOpen&&this.originalXhrSend&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrOpen=null,this.originalXhrSend=null),this.originalXhrSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXhrSetRequestHeader,this.originalXhrSetRequestHeader=null),this.originalSendBeacon&&(Navigator.prototype.sendBeacon=this.originalSendBeacon,this.originalSendBeacon=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}interceptFetch(){this.originalFetch=window.fetch.bind(window);let e=this;window.fetch=async function(t,r){let n=performance.now(),o={id:h(),timestamp:Date.now(),method:(r?.method||"GET").toUpperCase(),url:typeof t=="string"?t:t instanceof URL?t.href:t.url,requestHeaders:e.extractHeaders(r?.headers),requestBody:e.safeParseBody(r?.body),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"fetch",error:null,initiator:e.getInitiator()};try{let a=await e.originalFetch(t,r);o.status=a.status,o.statusText=a.statusText,o.responseHeaders=e.extractResponseHeaders(a.headers),o.duration=performance.now()-n;let c=a.clone();try{let i=await c.text();o.responseSize=i.length,o.responseBody=e.safeParseJson(i)}catch{o.responseBody="[Unable to read response]"}return o.requestBody=d(o.requestBody,e.config.sensitiveFields),o.responseBody=d(o.responseBody,e.config.sensitiveFields),e.buffer.push(o),a}catch(a){throw o.duration=performance.now()-n,o.error=a instanceof Error?a.message:String(a),e.buffer.push(o),a}}}interceptXHR(){this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send,this.originalXhrSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader;let e=this;XMLHttpRequest.prototype.open=function(t,r){return this.__bugjar_method=t,this.__bugjar_url=typeof r=="string"?r:r.href,this.__bugjar_headers={},e.originalXhrOpen.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(t,r){return this.__bugjar_headers&&(this.__bugjar_headers[t]=r),e.originalXhrSetRequestHeader.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){let r=performance.now(),n={id:h(),timestamp:Date.now(),method:(this.__bugjar_method||"GET").toUpperCase(),url:this.__bugjar_url||"",requestHeaders:this.__bugjar_headers||{},requestBody:e.safeParseBody(t),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"xhr",error:null,initiator:e.getInitiator()};return this.addEventListener("load",function(){n.status=this.status,n.statusText=this.statusText,n.responseHeaders=e.parseXhrHeaders(this.getAllResponseHeaders()),n.duration=performance.now()-r,n.responseSize=this.responseText?.length||null,n.responseBody=e.safeParseJson(this.responseText),n.requestBody=d(n.requestBody,e.config.sensitiveFields),n.responseBody=d(n.responseBody,e.config.sensitiveFields),e.buffer.push(n)}),this.addEventListener("error",function(){n.duration=performance.now()-r,n.error="Network error",e.buffer.push(n)}),this.addEventListener("timeout",function(){n.duration=performance.now()-r,n.error="Request timeout",e.buffer.push(n)}),e.originalXhrSend.apply(this,arguments)}}interceptBeacon(){if(!navigator.sendBeacon)return;this.originalSendBeacon=navigator.sendBeacon.bind(navigator);let e=this;Navigator.prototype.sendBeacon=function(t,r){let n={id:h(),timestamp:Date.now(),method:"POST",url:typeof t=="string"?t:t.href,requestHeaders:{},requestBody:e.safeParseBody(r),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"beacon",error:null,initiator:"sendBeacon"};return n.requestBody=d(n.requestBody,e.config.sensitiveFields),e.buffer.push(n),e.originalSendBeacon(t,r)}}extractHeaders(e){let t={};return e&&(e instanceof Headers?e.forEach((r,n)=>{t[n]=r}):Array.isArray(e)?e.forEach(([r,n])=>{t[r]=n}):Object.assign(t,e)),t}extractResponseHeaders(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}parseXhrHeaders(e){let t={};return e&&e.trim().split(/[\r\n]+/).forEach(r=>{let n=r.split(": "),o=n.shift();o&&(t[o]=n.join(": "))}),t}safeParseBody(e){if(!e)return null;if(typeof e=="string")return this.safeParseJson(e);if(e instanceof FormData){let t={};return e.forEach((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),t}return e instanceof URLSearchParams?Object.fromEntries(e.entries()):e instanceof Blob?`[Blob: ${e.size} bytes]`:e instanceof ArrayBuffer?`[ArrayBuffer: ${e.byteLength} bytes]`:String(e)}safeParseJson(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.length>5e3?e.slice(0,5e3)+"...[truncated]":e}}getInitiator(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
2
- `);for(let r of t)if(!r.includes("bug-jar")&&r.includes("at "))return r.trim().slice(0,200);return null}catch{return null}}};var w=class{constructor(e){this.originals={};this.levels=["log","warn","error","info","debug"];this.buffer=new l(e.maxConsoleEntries)}start(){for(let e of this.levels){this.originals[e]=console[e].bind(console);let t=this;console[e]=(...r)=>{t.capture(e,r),t.originals[e](...r)}}}stop(){for(let e of this.levels)this.originals[e]&&(console[e]=this.originals[e]);this.originals={}}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}capture(e,t){let r={timestamp:Date.now(),level:e,args:t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?n:JSON.parse(P(n))),stack:e==="error"||e==="warn"?this.getStack():null};this.buffer.push(r)}getStack(){try{return new Error().stack?.split(`
1
+ function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function F(o,e=1e4){try{let t=new WeakSet,r=JSON.stringify(o,(n,s)=>{if(typeof s=="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s instanceof Error?{message:s.message,stack:s.stack,name:s.name}:typeof s=="function"?"[Function]":s instanceof HTMLElement?f(s):s});return r&&r.length>e?r.slice(0,e)+"...[truncated]":r||""}catch{return"[Unserializable]"}}function f(o){if(!o||!(o instanceof Element))return"unknown";let e=o.tagName.toLowerCase(),t=o.id?`#${o.id}`:"",r=o.className&&typeof o.className=="string"?`.${o.className.trim().split(/\s+/).join(".")}`:"",n=o.textContent?.trim().slice(0,30)||"",s=n?` "${n}"`:"";return`${e}${t}${r}${s}`}function d(o,e){if(!o||typeof o!="object")return o;if(Array.isArray(o))return o.map(r=>d(r,e));let t={};for(let[r,n]of Object.entries(o))e.some(a=>r.toLowerCase().includes(a.toLowerCase()))?t[r]="[REDACTED]":typeof n=="object"&&n!==null?t[r]=d(n,e):t[r]=n;return t}var u=class{constructor(e){this.buffer=[];this.maxSize=e}push(e){this.buffer.length>=this.maxSize&&this.buffer.shift(),this.buffer.push(e)}getAll(){return[...this.buffer]}clear(){this.buffer=[]}get length(){return this.buffer.length}};var v=class{constructor(e){this.originalFetch=null;this.originalXhrOpen=null;this.originalXhrSend=null;this.originalXhrSetRequestHeader=null;this.originalSendBeacon=null;this.config=e,this.buffer=new u(e.maxNetworkEntries)}start(){this.interceptFetch(),this.interceptXHR(),this.interceptBeacon()}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXhrOpen&&this.originalXhrSend&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrOpen=null,this.originalXhrSend=null),this.originalXhrSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXhrSetRequestHeader,this.originalXhrSetRequestHeader=null),this.originalSendBeacon&&(Navigator.prototype.sendBeacon=this.originalSendBeacon,this.originalSendBeacon=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addIgnoreUrl(e){this.config.ignoreUrls||(this.config.ignoreUrls=[]),this.config.ignoreUrls.includes(e)||this.config.ignoreUrls.push(e)}getRawFetch(){return this.originalFetch??window.fetch.bind(window)}shouldIgnore(e){let t=this.config.ignoreUrls;return!t||t.length===0?!1:t.some(r=>e.includes(r))}resolveUrl(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}interceptFetch(){this.originalFetch=window.fetch.bind(window);let e=this;window.fetch=async function(t,r){if(e.shouldIgnore(e.resolveUrl(t)))return e.originalFetch(t,r);let n=performance.now(),s={id:h(),timestamp:Date.now(),method:(r?.method||"GET").toUpperCase(),url:typeof t=="string"?t:t instanceof URL?t.href:t.url,requestHeaders:e.extractHeaders(r?.headers),requestBody:e.safeParseBody(r?.body),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"fetch",error:null,initiator:e.getInitiator()};try{let a=await e.originalFetch(t,r);s.status=a.status,s.statusText=a.statusText,s.responseHeaders=e.extractResponseHeaders(a.headers),s.duration=performance.now()-n;let c=a.clone();try{let i=await c.text();s.responseSize=i.length,s.responseBody=e.safeParseJson(i)}catch{s.responseBody="[Unable to read response]"}return s.requestBody=d(s.requestBody,e.config.sensitiveFields),s.responseBody=d(s.responseBody,e.config.sensitiveFields),e.buffer.push(s),a}catch(a){throw s.duration=performance.now()-n,s.error=a instanceof Error?a.message:String(a),e.buffer.push(s),a}}}interceptXHR(){this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send,this.originalXhrSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader;let e=this;XMLHttpRequest.prototype.open=function(t,r){return this.__bugjar_method=t,this.__bugjar_url=typeof r=="string"?r:r.href,this.__bugjar_headers={},e.originalXhrOpen.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(t,r){return this.__bugjar_headers&&(this.__bugjar_headers[t]=r),e.originalXhrSetRequestHeader.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){if(e.shouldIgnore(this.__bugjar_url||""))return e.originalXhrSend.apply(this,arguments);let r=performance.now(),n={id:h(),timestamp:Date.now(),method:(this.__bugjar_method||"GET").toUpperCase(),url:this.__bugjar_url||"",requestHeaders:this.__bugjar_headers||{},requestBody:e.safeParseBody(t),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"xhr",error:null,initiator:e.getInitiator()};return this.addEventListener("load",function(){n.status=this.status,n.statusText=this.statusText,n.responseHeaders=e.parseXhrHeaders(this.getAllResponseHeaders()),n.duration=performance.now()-r,n.responseSize=this.responseText?.length||null,n.responseBody=e.safeParseJson(this.responseText),n.requestBody=d(n.requestBody,e.config.sensitiveFields),n.responseBody=d(n.responseBody,e.config.sensitiveFields),e.buffer.push(n)}),this.addEventListener("error",function(){n.duration=performance.now()-r,n.error="Network error",e.buffer.push(n)}),this.addEventListener("timeout",function(){n.duration=performance.now()-r,n.error="Request timeout",e.buffer.push(n)}),e.originalXhrSend.apply(this,arguments)}}interceptBeacon(){if(!navigator.sendBeacon)return;this.originalSendBeacon=navigator.sendBeacon.bind(navigator);let e=this;Navigator.prototype.sendBeacon=function(t,r){let n=typeof t=="string"?t:t.href;if(e.shouldIgnore(n))return e.originalSendBeacon(t,r);let s={id:h(),timestamp:Date.now(),method:"POST",url:n,requestHeaders:{},requestBody:e.safeParseBody(r),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"beacon",error:null,initiator:"sendBeacon"};return s.requestBody=d(s.requestBody,e.config.sensitiveFields),e.buffer.push(s),e.originalSendBeacon(t,r)}}extractHeaders(e){let t={};return e&&(e instanceof Headers?e.forEach((r,n)=>{t[n]=r}):Array.isArray(e)?e.forEach(([r,n])=>{t[r]=n}):Object.assign(t,e)),t}extractResponseHeaders(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}parseXhrHeaders(e){let t={};return e&&e.trim().split(/[\r\n]+/).forEach(r=>{let n=r.split(": "),s=n.shift();s&&(t[s]=n.join(": "))}),t}safeParseBody(e){if(!e)return null;if(typeof e=="string")return this.safeParseJson(e);if(e instanceof FormData){let t={};return e.forEach((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),t}return e instanceof URLSearchParams?Object.fromEntries(e.entries()):e instanceof Blob?`[Blob: ${e.size} bytes]`:e instanceof ArrayBuffer?`[ArrayBuffer: ${e.byteLength} bytes]`:String(e)}safeParseJson(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.length>5e3?e.slice(0,5e3)+"...[truncated]":e}}getInitiator(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
2
+ `);for(let r of t)if(!r.includes("bug-jar")&&r.includes("at "))return r.trim().slice(0,200);return null}catch{return null}}};var w=class{constructor(e){this.originals={};this.levels=["log","warn","error","info","debug"];this.buffer=new u(e.maxConsoleEntries)}start(){for(let e of this.levels){this.originals[e]=console[e].bind(console);let t=this;console[e]=(...r)=>{t.capture(e,r),t.originals[e](...r)}}}stop(){for(let e of this.levels)this.originals[e]&&(console[e]=this.originals[e]);this.originals={}}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}capture(e,t){let r={timestamp:Date.now(),level:e,args:t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?n:JSON.parse(F(n))),stack:e==="error"||e==="warn"?this.getStack():null};this.buffer.push(r)}getStack(){try{return new Error().stack?.split(`
3
3
  `).slice(4).join(`
4
- `)||null}catch{return null}}};var b=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new l(e.maxErrors)}start(){this.errorHandler=e=>{this.buffer.push({timestamp:Date.now(),message:e.message||"Unknown error",stack:e.error?.stack||null,filename:e.filename||null,lineno:e.lineno||null,colno:e.colno||null,type:"uncaught",context:this.getContext(e.error)})},this.rejectionHandler=e=>{let t=e.reason;this.buffer.push({timestamp:Date.now(),message:t instanceof Error?t.message:String(t),stack:t instanceof Error&&t.stack||null,filename:null,lineno:null,colno:null,type:"unhandledrejection",context:t instanceof Error?this.getContext(t):null})},this.resourceErrorHandler=e=>{let t=e.target;!t||!(t instanceof HTMLElement)||(t.tagName==="SCRIPT"||t.tagName==="LINK"||t.tagName==="IMG")&&this.buffer.push({timestamp:Date.now(),message:`Failed to load ${t.tagName.toLowerCase()}: ${t.src||t.href||"unknown"}`,stack:null,filename:t.src||t.href||null,lineno:null,colno:null,type:"resource",context:null})},window.addEventListener("error",this.errorHandler),window.addEventListener("unhandledrejection",this.rejectionHandler),window.addEventListener("error",this.resourceErrorHandler,!0)}stop(){this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null),this.resourceErrorHandler&&(window.removeEventListener("error",this.resourceErrorHandler,!0),this.resourceErrorHandler=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}getContext(e){if(!e)return null;try{let t=e.stack;if(!t)return null;let r=t.match(/at\s+(.+?)\s+\(/);return r?r[1]:null}catch{return null}}};var S=class{constructor(e){this.listeners=[];this.buffer=new l(e.maxUserActions)}start(){this.addListener("click",n=>{let o=n.target;this.buffer.push({timestamp:Date.now(),type:"click",target:f(o),metadata:{x:n.clientX,y:n.clientY,button:n.button}})},!0),this.addListener("input",n=>{let o=n.target,a=o.type==="password"||o.type==="hidden"||o.name?.toLowerCase().includes("password")||o.name?.toLowerCase().includes("token")||o.name?.toLowerCase().includes("secret");this.buffer.push({timestamp:Date.now(),type:"input",target:f(o),value:a?"[REDACTED]":o.value?.slice(0,50)||"",metadata:{inputType:o.type,name:o.name}})},!0),this.addListener("scroll",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"scroll",target:"window",metadata:{scrollX:window.scrollX,scrollY:window.scrollY,scrollHeight:document.documentElement.scrollHeight}})},500)),this.addListener("resize",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"resize",target:"window",metadata:{width:window.innerWidth,height:window.innerHeight}})},500)),this.addListener("visibilitychange",()=>{this.buffer.push({timestamp:Date.now(),type:"visibility",target:"document",value:document.visibilityState})}),this.addListener("copy",n=>{this.buffer.push({timestamp:Date.now(),type:"copy",target:f(n.target)})}),this.addListener("paste",n=>{this.buffer.push({timestamp:Date.now(),type:"paste",target:f(n.target)})});let e=history.pushState.bind(history),t=history.replaceState.bind(history),r=this;history.pushState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"pushState"}}),e(...n)},history.replaceState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"replaceState"}}),t(...n)},this.addListener("popstate",()=>{this.buffer.push({timestamp:Date.now(),type:"navigation",target:window.location.href,metadata:{method:"popstate"}})})}stop(){for(let{event:e,handler:t,options:r}of this.listeners)(e==="visibilitychange"?document:window).removeEventListener(e,t,r);this.listeners=[]}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addListener(e,t,r){(e==="visibilitychange"?document:window).addEventListener(e,t,r),this.listeners.push({event:e,handler:t,options:r})}throttle(e,t){let r=0;return()=>{let n=Date.now();n-r>=t&&(r=n,e())}}};var E=class{collect(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset(),screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio,colorDepth:screen.colorDepth,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,online:navigator.onLine,hardwareConcurrency:navigator.hardwareConcurrency||0,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,connection:this.getConnection(),memory:this.getMemory()}}getConnection(){let e=navigator.connection;return e?{effectiveType:e.effectiveType||"unknown",downlink:e.downlink||0,rtt:e.rtt||0,saveData:e.saveData||!1}:null}getMemory(){let e=performance.memory;return e?{jsHeapSizeLimit:e.jsHeapSizeLimit,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}:null}};var k=class{constructor(){this.lcp=null;this.fid=null;this.cls=null;this.observers=[]}start(){this.observeLCP(),this.observeFID(),this.observeCLS()}stop(){for(let e of this.observers)e.disconnect();this.observers=[]}collect(){let e=performance.getEntriesByType("navigation")[0],t=performance.getEntriesByType("paint"),r=performance.getEntriesByType("resource"),n=t.find(a=>a.name==="first-paint"),o=t.find(a=>a.name==="first-contentful-paint");return{navigationTiming:e?{redirectTime:e.redirectEnd-e.redirectStart,dnsTime:e.domainLookupEnd-e.domainLookupStart,tcpTime:e.connectEnd-e.connectStart,tlsTime:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,downloadTime:e.responseEnd-e.responseStart,domParsing:e.domInteractive-e.responseEnd,domContentLoaded:e.domContentLoadedEventEnd-e.domContentLoadedEventStart,loadEvent:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-e.startTime}:{},resourceCount:r.length,totalTransferSize:r.reduce((a,c)=>a+(c.transferSize||0),0),domContentLoaded:e?e.domContentLoadedEventEnd-e.startTime:null,loadComplete:e?e.loadEventEnd-e.startTime:null,firstPaint:n?n.startTime:null,firstContentfulPaint:o?o.startTime:null,largestContentfulPaint:this.lcp,firstInputDelay:this.fid,cumulativeLayoutShift:this.cls,timeToInteractive:null}}observeLCP(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.lcp=r[r.length-1].startTime)});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}}observeFID(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.fid=r[0].processingStart-r[0].startTime)});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}}observeCLS(){try{let e=0,t=new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.value);this.cls=e});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t)}catch{}}};var C=class{constructor(e){this.config=e}collect(){return{localStorage:this.config.captureLocalStorage?this.collectStorage(localStorage):{},sessionStorage:this.config.captureSessionStorage?this.collectStorage(sessionStorage):{},cookies:this.config.captureCookies?this.collectCookies():[]}}collectStorage(e){let t={};try{for(let r=0;r<e.length;r++){let n=e.key(r);if(!n)continue;if(this.config.sensitiveFields.some(a=>n.toLowerCase().includes(a.toLowerCase())))t[n]="[REDACTED]";else{let a=e.getItem(n)||"";t[n]=a.length>500?a.slice(0,500)+"...[truncated]":a}}}catch{}return t}collectCookies(){try{return document.cookie.split(";").map(e=>e.trim().split("=")[0]).filter(Boolean)}catch{return[]}}};var x=class{async capture(){try{let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return null;let r=window.innerWidth,n=window.innerHeight,o=Math.min(window.devicePixelRatio,2);e.width=r*o,e.height=n*o,t.scale(o,o);let a=this.domToSvg(r,n);return a?new Promise(c=>{let i=new Image;i.onload=()=>{t.drawImage(i,0,0);try{let u=e.toDataURL("image/png",.8);c(u)}catch{c(null)}},i.onerror=()=>c(null),i.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(a)}`,setTimeout(()=>c(null),3e3)}):null}catch{return null}}domToSvg(e,t){try{let r=document.documentElement.cloneNode(!0);r.querySelectorAll("script").forEach(a=>a.remove());let o=new XMLSerializer().serializeToString(r);return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">
4
+ `)||null}catch{return null}}};var b=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new u(e.maxErrors)}start(){this.errorHandler=e=>{this.buffer.push({timestamp:Date.now(),message:e.message||"Unknown error",stack:e.error?.stack||null,filename:e.filename||null,lineno:e.lineno||null,colno:e.colno||null,type:"uncaught",context:this.getContext(e.error)})},this.rejectionHandler=e=>{let t=e.reason;this.buffer.push({timestamp:Date.now(),message:t instanceof Error?t.message:String(t),stack:t instanceof Error&&t.stack||null,filename:null,lineno:null,colno:null,type:"unhandledrejection",context:t instanceof Error?this.getContext(t):null})},this.resourceErrorHandler=e=>{let t=e.target;!t||!(t instanceof HTMLElement)||(t.tagName==="SCRIPT"||t.tagName==="LINK"||t.tagName==="IMG")&&this.buffer.push({timestamp:Date.now(),message:`Failed to load ${t.tagName.toLowerCase()}: ${t.src||t.href||"unknown"}`,stack:null,filename:t.src||t.href||null,lineno:null,colno:null,type:"resource",context:null})},window.addEventListener("error",this.errorHandler),window.addEventListener("unhandledrejection",this.rejectionHandler),window.addEventListener("error",this.resourceErrorHandler,!0)}stop(){this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null),this.resourceErrorHandler&&(window.removeEventListener("error",this.resourceErrorHandler,!0),this.resourceErrorHandler=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}getContext(e){if(!e)return null;try{let t=e.stack;if(!t)return null;let r=t.match(/at\s+(.+?)\s+\(/);return r?r[1]:null}catch{return null}}};var S=class{constructor(e){this.listeners=[];this.buffer=new u(e.maxUserActions)}start(){this.addListener("click",n=>{let s=n.target;this.buffer.push({timestamp:Date.now(),type:"click",target:f(s),metadata:{x:n.clientX,y:n.clientY,button:n.button}})},!0),this.addListener("input",n=>{let s=n.target,a=s.type==="password"||s.type==="hidden"||s.name?.toLowerCase().includes("password")||s.name?.toLowerCase().includes("token")||s.name?.toLowerCase().includes("secret");this.buffer.push({timestamp:Date.now(),type:"input",target:f(s),value:a?"[REDACTED]":s.value?.slice(0,50)||"",metadata:{inputType:s.type,name:s.name}})},!0),this.addListener("scroll",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"scroll",target:"window",metadata:{scrollX:window.scrollX,scrollY:window.scrollY,scrollHeight:document.documentElement.scrollHeight}})},500)),this.addListener("resize",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"resize",target:"window",metadata:{width:window.innerWidth,height:window.innerHeight}})},500)),this.addListener("visibilitychange",()=>{this.buffer.push({timestamp:Date.now(),type:"visibility",target:"document",value:document.visibilityState})}),this.addListener("copy",n=>{this.buffer.push({timestamp:Date.now(),type:"copy",target:f(n.target)})}),this.addListener("paste",n=>{this.buffer.push({timestamp:Date.now(),type:"paste",target:f(n.target)})});let e=history.pushState.bind(history),t=history.replaceState.bind(history),r=this;history.pushState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"pushState"}}),e(...n)},history.replaceState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"replaceState"}}),t(...n)},this.addListener("popstate",()=>{this.buffer.push({timestamp:Date.now(),type:"navigation",target:window.location.href,metadata:{method:"popstate"}})})}stop(){for(let{event:e,handler:t,options:r}of this.listeners)(e==="visibilitychange"?document:window).removeEventListener(e,t,r);this.listeners=[]}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addListener(e,t,r){(e==="visibilitychange"?document:window).addEventListener(e,t,r),this.listeners.push({event:e,handler:t,options:r})}throttle(e,t){let r=0;return()=>{let n=Date.now();n-r>=t&&(r=n,e())}}};var E=class{collect(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset(),screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio,colorDepth:screen.colorDepth,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,online:navigator.onLine,hardwareConcurrency:navigator.hardwareConcurrency||0,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,connection:this.getConnection(),memory:this.getMemory()}}getConnection(){let e=navigator.connection;return e?{effectiveType:e.effectiveType||"unknown",downlink:e.downlink||0,rtt:e.rtt||0,saveData:e.saveData||!1}:null}getMemory(){let e=performance.memory;return e?{jsHeapSizeLimit:e.jsHeapSizeLimit,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}:null}};var k=class{constructor(){this.lcp=null;this.fid=null;this.cls=null;this.observers=[]}start(){this.observeLCP(),this.observeFID(),this.observeCLS()}stop(){for(let e of this.observers)e.disconnect();this.observers=[]}collect(){let e=performance.getEntriesByType("navigation")[0],t=performance.getEntriesByType("paint"),r=performance.getEntriesByType("resource"),n=t.find(a=>a.name==="first-paint"),s=t.find(a=>a.name==="first-contentful-paint");return{navigationTiming:e?{redirectTime:e.redirectEnd-e.redirectStart,dnsTime:e.domainLookupEnd-e.domainLookupStart,tcpTime:e.connectEnd-e.connectStart,tlsTime:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,downloadTime:e.responseEnd-e.responseStart,domParsing:e.domInteractive-e.responseEnd,domContentLoaded:e.domContentLoadedEventEnd-e.domContentLoadedEventStart,loadEvent:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-e.startTime}:{},resourceCount:r.length,totalTransferSize:r.reduce((a,c)=>a+(c.transferSize||0),0),domContentLoaded:e?e.domContentLoadedEventEnd-e.startTime:null,loadComplete:e?e.loadEventEnd-e.startTime:null,firstPaint:n?n.startTime:null,firstContentfulPaint:s?s.startTime:null,largestContentfulPaint:this.lcp,firstInputDelay:this.fid,cumulativeLayoutShift:this.cls,timeToInteractive:null}}observeLCP(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.lcp=r[r.length-1].startTime)});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}}observeFID(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.fid=r[0].processingStart-r[0].startTime)});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}}observeCLS(){try{let e=0,t=new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.value);this.cls=e});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t)}catch{}}};var U=class{constructor(e){this.config=e}collect(){return{localStorage:this.config.captureLocalStorage?this.collectStorage(localStorage):{},sessionStorage:this.config.captureSessionStorage?this.collectStorage(sessionStorage):{},cookies:this.config.captureCookies?this.collectCookies():[]}}collectStorage(e){let t={};try{for(let r=0;r<e.length;r++){let n=e.key(r);if(!n)continue;if(this.config.sensitiveFields.some(a=>n.toLowerCase().includes(a.toLowerCase())))t[n]="[REDACTED]";else{let a=e.getItem(n)||"";t[n]=a.length>500?a.slice(0,500)+"...[truncated]":a}}}catch{}return t}collectCookies(){try{return document.cookie.split(";").map(e=>e.trim().split("=")[0]).filter(Boolean)}catch{return[]}}};var C=class{async capture(){try{let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return null;let r=window.innerWidth,n=window.innerHeight,s=Math.min(window.devicePixelRatio,2);e.width=r*s,e.height=n*s,t.scale(s,s);let a=this.domToSvg(r,n);return a?new Promise(c=>{let i=new Image;i.onload=()=>{t.drawImage(i,0,0);try{let l=e.toDataURL("image/png",.8);c(l)}catch{c(null)}},i.onerror=()=>c(null),i.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(a)}`,setTimeout(()=>c(null),3e3)}):null}catch{return null}}domToSvg(e,t){try{let r=document.documentElement.cloneNode(!0);r.querySelectorAll("script").forEach(a=>a.remove());let s=new XMLSerializer().serializeToString(r);return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">
5
5
  <foreignObject width="100%" height="100%">
6
- ${o}
6
+ ${s}
7
7
  </foreignObject>
8
- </svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(n=>n.remove()),e.querySelectorAll('input[type="password"], input[name*="token"], input[name*="secret"]').forEach(n=>n.value="[REDACTED]"),e.outerHTML.slice(0,5e5)}catch{return null}}};var R=class{collect(){let e={},t=!1,r=window.posthog;if(r?.getFeatureFlag)try{let c=r.getAllFlags?.()||r.getFeatureFlags?.()||{};e.posthog=c,t=!0}catch{}let n=window.ldclient;if(n?.allFlags)try{e.launchdarkly=n.allFlags(),t=!0}catch{}let o=window.statsig;if(o?.getExperiment||o?.checkGate)try{e.statsig={detected:!0},t=!0}catch{}let a=window.unleash;if(a?.getAllToggles)try{e.unleash=a.getAllToggles(),t=!0}catch{}return t?e:null}};var U=class{constructor(){this.mediaRecorder=null;this.chunks=[];this.stream=null;this.recording=!1;this.onChunk=null}get isRecording(){return this.recording}setChunkHandler(e){this.onChunk=e}async start(){if(!this.recording)try{this.stream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!1,preferCurrentTab:!0}),this.chunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:this.getSupportedMimeType(),videoBitsPerSecond:1e6}),this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&(this.chunks.push(e.data),this.onChunk&&e.data.arrayBuffer().then(t=>this.onChunk?.(new Uint8Array(t),!1)))},this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks()},this.stream.getVideoTracks()[0].onended=()=>{this.stop()},this.mediaRecorder.start(1e3),this.recording=!0}catch{this.recording=!1,this.stream=null,this.mediaRecorder=null}}stop(){return new Promise(e=>{if(!this.mediaRecorder||!this.recording){e(null);return}this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks();let t=new Blob(this.chunks,{type:this.getSupportedMimeType()});this.chunks=[],e(t)},this.mediaRecorder.stop()})}stopTracks(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}getSupportedMimeType(){let e=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"];for(let t of e)if(MediaRecorder.isTypeSupported(t))return t;return"video/webm"}};var T=class{constructor(){this.container=null}mount(){this.container||(this.container=document.createElement("div"),this.container.id="bug-jar-session-border",this.container.setAttribute("aria-hidden","true"),this.container.innerHTML=`
8
+ </svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(n=>n.remove()),e.querySelectorAll('input[type="password"], input[name*="token"], input[name*="secret"]').forEach(n=>n.value="[REDACTED]"),e.outerHTML.slice(0,5e5)}catch{return null}}};var R=class{collect(){let e={},t=!1,r=window.posthog;if(r?.getFeatureFlag)try{let c=r.getAllFlags?.()||r.getFeatureFlags?.()||{};e.posthog=c,t=!0}catch{}let n=window.ldclient;if(n?.allFlags)try{e.launchdarkly=n.allFlags(),t=!0}catch{}let s=window.statsig;if(s?.getExperiment||s?.checkGate)try{e.statsig={detected:!0},t=!0}catch{}let a=window.unleash;if(a?.getAllToggles)try{e.unleash=a.getAllToggles(),t=!0}catch{}return t?e:null}};var x=class{constructor(){this.mediaRecorder=null;this.chunks=[];this.stream=null;this.recording=!1;this.onChunk=null}get isRecording(){return this.recording}setChunkHandler(e){this.onChunk=e}async start(){if(!this.recording)try{this.stream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!1,preferCurrentTab:!0}),this.chunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:this.getSupportedMimeType(),videoBitsPerSecond:1e6}),this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&(this.chunks.push(e.data),this.onChunk&&e.data.arrayBuffer().then(t=>this.onChunk?.(new Uint8Array(t),!1)).catch(()=>{}))},this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks()},this.stream.getVideoTracks()[0].onended=()=>{this.stop()},this.mediaRecorder.start(1e3),this.recording=!0}catch{this.recording=!1,this.stream=null,this.mediaRecorder=null}}stop(){return new Promise(e=>{if(!this.mediaRecorder||!this.recording){e(null);return}this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks();let t=new Blob(this.chunks,{type:this.getSupportedMimeType()});this.chunks=[],e(t)},this.mediaRecorder.stop()})}stopTracks(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}getSupportedMimeType(){let e=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"];for(let t of e)if(MediaRecorder.isTypeSupported(t))return t;return"video/webm"}};var T=class{constructor(){this.container=null}mount(){this.container||(this.container=document.createElement("div"),this.container.id="bug-jar-session-border",this.container.setAttribute("aria-hidden","true"),this.container.innerHTML=`
9
9
  <div class="bug-jar-session-border-glow"></div>
10
10
  <div class="bug-jar-session-pill">
11
11
  <span class="bug-jar-session-pill-dot"></span>
@@ -80,7 +80,7 @@ function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slic
80
80
  .bug-jar-session-border-glow { animation: none; }
81
81
  .bug-jar-session-pill-dot { animation: none; }
82
82
  }
83
- `,document.head.appendChild(e)}};function D(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function $(s,e){let t=`${s.replace(/\/$/,"")}/${encodeURIComponent(e)}`,r=await fetch(t,{method:"GET",credentials:"include"});if(!r.ok)throw new Error(`Failed to load debug session (${r.status})`);return await r.json()}function I(s){let e=s.replace(/\/$/,"");return async t=>{let r=`${e}/${encodeURIComponent(t.token)}/chunk-url`,n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({pageId:t.pageId,stream:t.stream,seq:t.seq})});if(!n.ok)throw new Error(`Failed to get chunk URL (${n.status})`);return await n.json()}}async function F(s,e,t,r){let o=`${s.replace(/\/$/,"")}/${encodeURIComponent(e)}/meta`;await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",keepalive:!0,body:JSON.stringify({pageId:t,meta:r})})}async function z(){let s=await import("libsodium-wrappers"),e=s.default??s;return await e.ready,e}function N(s){let e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}var J=[66,74,83,49],B=class{constructor(){this.sodium=null;this.state=null;this.headerEnvelope=null}async init(e){let t=await z();this.sodium=t;let r=N(e),n=t.crypto_secretstream_xchacha20poly1305_keygen(),o=t.crypto_box_seal(n,r),{state:a,header:c}=t.crypto_secretstream_xchacha20poly1305_init_push(n);this.state=a;let i=new Uint8Array(J),u=new Uint8Array([1]),p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,o.length,!0);let g=X([i,u,p,o,c]);return this.headerEnvelope=g,g}get header(){if(!this.headerEnvelope)throw new Error("StreamEncryptor not initialized");return this.headerEnvelope}encryptChunk(e,t=!1){if(!this.sodium||!this.state)throw new Error("StreamEncryptor not initialized");let r=t?this.sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL:this.sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;return this.sodium.crypto_secretstream_xchacha20poly1305_push(this.state,e,null,r)}};function X(s){let e=s.reduce((n,o)=>n+o.length,0),t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var m=class{constructor(e,t,r,n,o){this.token=e;this.pageId=t;this.stream=r;this.publicKey=n;this.fetchChunkUrl=o;this.encryptor=new B;this.seq=0;this.initialized=!1;this.queue=Promise.resolve()}async ensureInit(){if(this.initialized)return;this.initialized=!0;let e=await this.encryptor.init(this.publicKey);await this.putChunk(e)}pushChunk(e,t=!1){this.queue=this.queue.then(async()=>{await this.ensureInit();let r=this.encryptor.encryptChunk(e,t);await this.putChunk(r)})}async flush(){await this.queue}async putChunk(e){let{uploadUrl:t}=await this.fetchChunkUrl({token:this.token,pageId:this.pageId,stream:this.stream,seq:this.seq});this.seq+=1,await fetch(t,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:e})}};var A="bug-jar-session";function j(){if(typeof window>"u")return;let e=window.location.hostname.split(".");return e.length<2?void 0:`.${e.slice(-2).join(".")}`}function q(){if(typeof document>"u")return null;let s=document.cookie.split("; ").find(t=>t.startsWith(`${A}=`));if(!s)return null;let e=s.slice(A.length+1);return e?decodeURIComponent(e):null}function M(s,e){if(typeof document>"u")return;let t=j(),r=new Date(e).toUTCString(),n=window.location.protocol==="https:"?"; Secure":"",o=t?`; Domain=${t}`:"";document.cookie=`${A}=${encodeURIComponent(s)}; Path=/; Expires=${r}; SameSite=Lax${o}${n}`}function _(){if(typeof document>"u")return;let s=j(),e=s?`; Domain=${s}`:"";document.cookie=`${A}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${e}`}function L(s){let e=[];e.push(`Bug Report: ${s.id}`),e.push(`URL: ${s.url}`),e.push(`Time: ${new Date(s.timestamp).toISOString()}`),e.push(`User Description: "${s.userDescription}"`),e.push(""),e.push("## Environment"),e.push(`Browser: ${K(s.environment.userAgent)}`),e.push(`Viewport: ${s.environment.viewportWidth}x${s.environment.viewportHeight}`),e.push(`Connection: ${s.environment.connection?.effectiveType||"unknown"}`),e.push(`Online: ${s.environment.online}`),e.push(""),e.push("## Network Activity");let t=s.network.length,r=s.network.filter(i=>i.error||i.status&&i.status>=400),n=s.network.filter(i=>i.duration&&i.duration>3e3);if(e.push(`Total requests: ${t}`),r.length>0){e.push(`Failed requests (${r.length}):`);for(let i of r)e.push(` - ${i.method} ${i.url} \u2192 ${i.error||`HTTP ${i.status}`}`)}if(n.length>0){e.push(`Slow requests >3s (${n.length}):`);for(let i of n)e.push(` - ${i.method} ${i.url} (${Math.round(i.duration)}ms)`)}if(e.push(""),e.push("## Errors"),s.errors.length===0)e.push("No errors captured.");else{e.push(`Total errors: ${s.errors.length}`);for(let i of s.errors)e.push(` - [${i.type}] ${i.message}`),i.filename&&e.push(` at ${i.filename}:${i.lineno}:${i.colno}`)}e.push(""),e.push("## Console");let o={log:0,warn:0,error:0,info:0,debug:0};for(let i of s.console)o[i.level]++;e.push(`Logs: ${o.log}, Warnings: ${o.warn}, Errors: ${o.error}, Info: ${o.info}, Debug: ${o.debug}`);let a=s.console.filter(i=>i.level==="error");if(a.length>0){e.push("Console errors:");for(let i of a)e.push(` - ${i.args.map(u=>typeof u=="string"?u:JSON.stringify(u)).join(" ")}`)}e.push(""),e.push("## User Actions"),e.push(`Total actions: ${s.userActions.length}`);let c={};for(let i of s.userActions)c[i.type]=(c[i.type]||0)+1;for(let[i,u]of Object.entries(c))e.push(` - ${i}: ${u}`);if(s.userActions.length>0){let i=s.userActions[0].timestamp,p=((s.userActions[s.userActions.length-1].timestamp-i)/1e3).toFixed(1);e.push(`Session duration: ${p}s`)}if(e.push(""),s.performance){e.push("## Performance");let i=s.performance;i.largestContentfulPaint&&e.push(`LCP: ${Math.round(i.largestContentfulPaint)}ms`),i.firstInputDelay&&e.push(`FID: ${Math.round(i.firstInputDelay)}ms`),i.cumulativeLayoutShift!==null&&e.push(`CLS: ${i.cumulativeLayoutShift?.toFixed(3)}`),i.loadComplete&&e.push(`Page Load: ${Math.round(i.loadComplete)}ms`),e.push(`Resources: ${i.resourceCount} (${G(i.totalTransferSize)})`)}return e.join(`
84
- `)}function K(s){return s.includes("Chrome/")?`Chrome ${s.match(/Chrome\/(\d+)/)?.[1]||""}`:s.includes("Firefox/")?`Firefox ${s.match(/Firefox\/(\d+)/)?.[1]||""}`:s.includes("Safari/")&&!s.includes("Chrome")?`Safari ${s.match(/Version\/(\d+)/)?.[1]||""}`:s.slice(0,50)}function G(s){return s<1024?`${s}B`:s<1024*1024?`${(s/1024).toFixed(1)}KB`:`${(s/(1024*1024)).toFixed(1)}MB`}async function H(s,e){let t=[],r=JSON.stringify(s,null,2);t.push({name:"report.json",content:new TextEncoder().encode(r)});let n=L(s);if(t.push({name:"summary.md",content:new TextEncoder().encode(n)}),s.screenshot){let o=V(s.screenshot);o&&t.push({name:"screenshot.png",content:o})}if(e){let o=new Uint8Array(await e.arrayBuffer());t.push({name:"recording.webm",content:o})}return W(t)}function V(s){try{let e=s.split(",")[1];if(!e)return null;let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}catch{return null}}function W(s){let e=[],t=[],r=0;for(let i of s){let u=new TextEncoder().encode(i.name),p=ee(i.content),g=Z(u,i.content.length,p);e.push(g),e.push(u),e.push(i.content);let O=Y(u,i.content.length,p,r);t.push(O),t.push(u),r+=g.length+u.length+i.content.length}let n=r,o=0;for(let i of t)o+=i.length;let a=Q(s.length,o,n),c=[...e,...t,a].map(i=>i.buffer);return new Blob(c,{type:"application/zip"})}function Z(s,e,t){let r=new Uint8Array(30),n=new DataView(r.buffer);return n.setUint32(0,67324752,!0),n.setUint16(4,20,!0),n.setUint16(6,0,!0),n.setUint16(8,0,!0),n.setUint16(10,0,!0),n.setUint16(12,0,!0),n.setUint32(14,t,!0),n.setUint32(18,e,!0),n.setUint32(22,e,!0),n.setUint16(26,s.length,!0),n.setUint16(28,0,!0),r}function Y(s,e,t,r){let n=new Uint8Array(46),o=new DataView(n.buffer);return o.setUint32(0,33639248,!0),o.setUint16(4,20,!0),o.setUint16(6,20,!0),o.setUint16(8,0,!0),o.setUint16(10,0,!0),o.setUint16(12,0,!0),o.setUint16(14,0,!0),o.setUint32(16,t,!0),o.setUint32(20,e,!0),o.setUint32(24,e,!0),o.setUint16(28,s.length,!0),o.setUint16(30,0,!0),o.setUint16(32,0,!0),o.setUint16(34,0,!0),o.setUint16(36,0,!0),o.setUint32(38,0,!0),o.setUint32(42,r,!0),n}function Q(s,e,t){let r=new Uint8Array(22),n=new DataView(r.buffer);return n.setUint32(0,101010256,!0),n.setUint16(4,0,!0),n.setUint16(6,0,!0),n.setUint16(8,s,!0),n.setUint16(10,s,!0),n.setUint32(12,e,!0),n.setUint32(16,t,!0),n.setUint16(20,0,!0),r}function ee(s){let e=4294967295;for(let t=0;t<s.length;t++){e^=s[t];for(let r=0;r<8;r++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}var te="0.6.0",ne={maxNetworkEntries:100,maxConsoleEntries:200,maxUserActions:150,maxErrors:50,captureScreenshot:!0,captureHtmlSnapshot:!0,captureCookies:!0,captureLocalStorage:!0,captureSessionStorage:!0,capturePerformance:!0,captureWebVitals:!0,captureMemory:!0,captureConnectivity:!0,sensitiveFields:["password","token","secret","authorization","cookie","session","credit_card","cvv","ssn","cpf"],endpoint:void 0,onCapture:void 0,debugToken:void 0,debugSessionEndpoint:void 0},y=class{constructor(e={}){this.sessionBorder=null;this.debugSession=null;this.dataUploader=null;this.videoUploader=null;this.pageId=h();this.dataInterval=null;this.finalized=!1;this.started=!1;this.config={...ne,...e},this.network=new v(this.config),this.console=new w(this.config),this.errors=new b(this.config),this.userActions=new S(this.config),this.environment=new E,this.performance=new k,this.storage=new C(this.config),this.screenshot=new x,this.featureFlags=new R,this.screenRecorder=new U}start(){if(this.started)return;this.started=!0,this.network.start(),this.console.start(),this.errors.start(),this.userActions.start(),this.config.captureWebVitals&&this.performance.start();let e=this.config.debugToken??D()??q();e&&this.startDebugSession(e)}stop(){this.started&&(this.started=!1,this.network.stop(),this.console.stop(),this.errors.stop(),this.userActions.stop(),this.performance.stop(),this.sessionBorder?.unmount())}async startRecording(){await this.screenRecorder.start()}get isRecording(){return this.screenRecorder.isRecording}async capture(e=""){let t={id:h(),timestamp:Date.now(),url:window.location.href,title:document.title,userDescription:e,environment:this.environment.collect(),network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),performance:this.config.capturePerformance?this.performance.collect():null,storage:this.storage.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null,htmlSnapshot:this.config.captureHtmlSnapshot?this.screenshot.captureHtml():null,featureFlags:this.featureFlags.collect(),metadata:{},version:te};return this.config.onCapture&&this.config.onCapture(t),t}async captureAndExport(e=""){let t=await this.screenRecorder.stop(),r=await this.capture(e);if(this.config.endpoint)if(t){let n=new FormData;n.append("report",JSON.stringify(r)),n.append("video",t,"recording.webm"),await fetch(this.config.endpoint,{method:"POST",body:n})}else await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});else{let n=await H(r,t),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=`bug-report-${r.id}.zip`,a.click(),URL.revokeObjectURL(o)}return r}getReport(){return this.capture()}async startDebugSession(e){if(!this.config.debugSessionEndpoint)return;let t=this.config.debugSessionEndpoint,r=()=>{this.sessionBorder=new T,this.sessionBorder.mount()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",r):r();try{this.debugSession=await $(t,e),M(this.debugSession.token,this.debugSession.expiresAt);let n=I(t);this.dataUploader=new m(this.debugSession.token,this.pageId,"data",this.debugSession.publicKey,n),this.videoUploader=new m(this.debugSession.token,this.pageId,"video",this.debugSession.publicKey,n),F(t,this.debugSession.token,this.pageId,{url:window.location.href,title:document.title,startedAt:Date.now(),environment:this.environment.collect()}),this.screenRecorder.setChunkHandler(o=>{this.videoUploader?.pushChunk(o)}),await this.screenRecorder.start(),this.startDataStreaming(),this.registerFlushHandlers()}catch{this.sessionBorder?.unmount()}}startDataStreaming(){let e=t=>{if(!this.dataUploader)return;let r={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),storage:this.storage.collect(),featureFlags:this.featureFlags.collect()},n=new TextEncoder().encode(JSON.stringify(r)+`
85
- `);this.dataUploader.pushChunk(n,t)};this.dataInterval=setInterval(()=>e(!1),5e3)}registerFlushHandlers(){let e=()=>{this.finalizePage()};window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()})}async finalizePage(){if(this.finalized||!this.debugSession)return;this.finalized=!0,this.dataInterval&&(clearInterval(this.dataInterval),this.dataInterval=null);let e={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),storage:this.storage.collect(),featureFlags:this.featureFlags.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null},t=new TextEncoder().encode(JSON.stringify(e)+`
86
- `);this.dataUploader?.pushChunk(t,!0),await this.screenRecorder.stop(),await Promise.allSettled([this.dataUploader?.flush()??Promise.resolve(),this.videoUploader?.flush()??Promise.resolve()])}endDebugSession(){_(),this.sessionBorder?.unmount(),this.finalizePage()}};function re(s={}){let e=new y(s);return e.start(),e}typeof window<"u"&&(window.BugJar={BugJar:y,init:re});var Ne=y;export{y as BugJar,Ne as default,H as exportAsZip,L as generateSummary,re as init};
83
+ `,document.head.appendChild(e)}};function M(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function I(o,e,t=fetch){let r=`${o.replace(/\/$/,"")}/${encodeURIComponent(e)}`,n=await t(r,{method:"GET",credentials:"include"});if(!n.ok){let s=new Error(`Failed to load debug session (${n.status})`);throw s.status=n.status,s}return await n.json()}function j(o,e=fetch){let t=o.replace(/\/$/,"");return async r=>{let n=`${t}/${encodeURIComponent(r.token)}/chunk-url`,s=await e(n,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({pageId:r.pageId,stream:r.stream,seq:r.seq})});if(!s.ok)throw new Error(`Failed to get chunk URL (${s.status})`);return await s.json()}}async function _(o,e,t,r,n=fetch){let a=`${o.replace(/\/$/,"")}/${encodeURIComponent(e)}/meta`;await n(a,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",keepalive:!0,body:JSON.stringify({pageId:t,meta:r})})}async function z(){let o=await import("libsodium-wrappers"),e=o.default??o;return await e.ready,e}function X(o){let e=atob(o),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}var J=[66,74,83,49],A=class{constructor(){this.sodium=null;this.state=null;this.headerEnvelope=null}async init(e){let t=await z();this.sodium=t;let r=X(e),n=t.crypto_secretstream_xchacha20poly1305_keygen(),s=t.crypto_box_seal(n,r),{state:a,header:c}=t.crypto_secretstream_xchacha20poly1305_init_push(n);this.state=a;let i=new Uint8Array(J),l=new Uint8Array([1]),p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,s.length,!0);let g=W([i,l,p,s,c]);return this.headerEnvelope=g,g}get header(){if(!this.headerEnvelope)throw new Error("StreamEncryptor not initialized");return this.headerEnvelope}encryptChunk(e,t=!1){if(!this.sodium||!this.state)throw new Error("StreamEncryptor not initialized");let r=t?this.sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL:this.sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;return this.sodium.crypto_secretstream_xchacha20poly1305_push(this.state,e,null,r)}};function W(o){let e=o.reduce((n,s)=>n+s.length,0),t=new Uint8Array(e),r=0;for(let n of o)t.set(n,r),r+=n.length;return t}var m=class{constructor(e,t,r,n,s,a=fetch){this.token=e;this.pageId=t;this.stream=r;this.publicKey=n;this.fetchChunkUrl=s;this.rawFetch=a;this.encryptor=new A;this.seq=0;this.initialized=!1;this.queue=Promise.resolve()}async ensureInit(){if(this.initialized)return;this.initialized=!0;let e=await this.encryptor.init(this.publicKey);await this.putChunk(e)}pushChunk(e,t=!1){this.queue=this.queue.then(async()=>{await this.ensureInit();let r=this.encryptor.encryptChunk(e,t);await this.putChunk(r)})}async flush(){await this.queue}async putChunk(e){let{uploadUrl:t}=await this.fetchChunkUrl({token:this.token,pageId:this.pageId,stream:this.stream,seq:this.seq});this.seq+=1,await this.rawFetch(t,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:e})}};var B=class{constructor(e,t,r=fetch){this.baseUrl=e;this.token=t;this.rawFetch=r}async run(){let e=performance.now(),t={ranAt:Date.now(),latencyMs:null,jitterMs:null,downloadMbps:null,uploadMbps:null,durationMs:0};try{let r=await this.measureLatency();t.latencyMs=r.min,t.jitterMs=r.jitter}catch{}try{t.downloadMbps=await this.measureDownload()}catch{}try{t.uploadMbps=await this.measureUpload()}catch{}return t.durationMs=Math.round(performance.now()-e),t}url(e){return`${this.baseUrl.replace(/\/$/,"")}/${encodeURIComponent(this.token)}/${e}`}async measureLatency(){let e=[];for(let s=0;s<5;s++){let a=performance.now();await this.rawFetch(this.url(`speedtest/ping?n=${s}`),{cache:"no-store"}),e.push(performance.now()-a)}let t=Math.min(...e),r=e.reduce((s,a)=>s+a,0)/e.length,n=e.reduce((s,a)=>s+Math.abs(a-r),0)/e.length;return{min:Math.round(t),jitter:Math.round(n)}}async measureDownload(){let e=Math.floor(2097152),t=performance.now(),r=Array.from({length:4},(c,i)=>this.rawFetch(this.url(`speedtest/download?bytes=${e}&s=${i}`),{cache:"no-store"}).then(l=>l.arrayBuffer())),n=await Promise.all(r),s=(performance.now()-t)/1e3,a=n.reduce((c,i)=>c+i.byteLength,0);return this.toMbps(a,s)}async measureUpload(){let e=new Uint8Array(4194304);crypto.getRandomValues(e.subarray(0,Math.min(65536,4194304)));let t=performance.now();await this.rawFetch(this.url("speedtest/upload"),{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});let r=(performance.now()-t)/1e3;return this.toMbps(4194304,r)}toMbps(e,t){return t<=0?0:Math.round(e*8/t/1e6*100)/100}};var L="bug-jar-session";function q(){if(typeof window>"u")return;let e=window.location.hostname.split(".");return e.length<2?void 0:`.${e.slice(-2).join(".")}`}function O(){if(typeof document>"u")return null;let o=document.cookie.split("; ").find(t=>t.startsWith(`${L}=`));if(!o)return null;let e=o.slice(L.length+1);return e?decodeURIComponent(e):null}function D(o,e){if(typeof document>"u")return;let t=q(),r=new Date(e).toUTCString(),n=window.location.protocol==="https:"?"; Secure":"",s=t?`; Domain=${t}`:"";document.cookie=`${L}=${encodeURIComponent(o)}; Path=/; Expires=${r}; SameSite=Lax${s}${n}`}function P(){if(typeof document>"u")return;let o=q(),e=o?`; Domain=${o}`:"";document.cookie=`${L}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${e}`}function H(o){let e=[];e.push(`Bug Report: ${o.id}`),e.push(`URL: ${o.url}`),e.push(`Time: ${new Date(o.timestamp).toISOString()}`),e.push(`User Description: "${o.userDescription}"`),e.push(""),e.push("## Environment"),e.push(`Browser: ${K(o.environment.userAgent)}`),e.push(`Viewport: ${o.environment.viewportWidth}x${o.environment.viewportHeight}`),e.push(`Connection: ${o.environment.connection?.effectiveType||"unknown"}`),e.push(`Online: ${o.environment.online}`),e.push(""),e.push("## Network Activity");let t=o.network.length,r=o.network.filter(i=>i.error||i.status&&i.status>=400),n=o.network.filter(i=>i.duration&&i.duration>3e3);if(e.push(`Total requests: ${t}`),r.length>0){e.push(`Failed requests (${r.length}):`);for(let i of r)e.push(` - ${i.method} ${i.url} \u2192 ${i.error||`HTTP ${i.status}`}`)}if(n.length>0){e.push(`Slow requests >3s (${n.length}):`);for(let i of n)e.push(` - ${i.method} ${i.url} (${Math.round(i.duration)}ms)`)}if(e.push(""),e.push("## Errors"),o.errors.length===0)e.push("No errors captured.");else{e.push(`Total errors: ${o.errors.length}`);for(let i of o.errors)e.push(` - [${i.type}] ${i.message}`),i.filename&&e.push(` at ${i.filename}:${i.lineno}:${i.colno}`)}e.push(""),e.push("## Console");let s={log:0,warn:0,error:0,info:0,debug:0};for(let i of o.console)s[i.level]++;e.push(`Logs: ${s.log}, Warnings: ${s.warn}, Errors: ${s.error}, Info: ${s.info}, Debug: ${s.debug}`);let a=o.console.filter(i=>i.level==="error");if(a.length>0){e.push("Console errors:");for(let i of a)e.push(` - ${i.args.map(l=>typeof l=="string"?l:JSON.stringify(l)).join(" ")}`)}e.push(""),e.push("## User Actions"),e.push(`Total actions: ${o.userActions.length}`);let c={};for(let i of o.userActions)c[i.type]=(c[i.type]||0)+1;for(let[i,l]of Object.entries(c))e.push(` - ${i}: ${l}`);if(o.userActions.length>0){let i=o.userActions[0].timestamp,p=((o.userActions[o.userActions.length-1].timestamp-i)/1e3).toFixed(1);e.push(`Session duration: ${p}s`)}if(e.push(""),o.performance){e.push("## Performance");let i=o.performance;i.largestContentfulPaint&&e.push(`LCP: ${Math.round(i.largestContentfulPaint)}ms`),i.firstInputDelay&&e.push(`FID: ${Math.round(i.firstInputDelay)}ms`),i.cumulativeLayoutShift!==null&&e.push(`CLS: ${i.cumulativeLayoutShift?.toFixed(3)}`),i.loadComplete&&e.push(`Page Load: ${Math.round(i.loadComplete)}ms`),e.push(`Resources: ${i.resourceCount} (${V(i.totalTransferSize)})`)}return e.join(`
84
+ `)}function K(o){return o.includes("Chrome/")?`Chrome ${o.match(/Chrome\/(\d+)/)?.[1]||""}`:o.includes("Firefox/")?`Firefox ${o.match(/Firefox\/(\d+)/)?.[1]||""}`:o.includes("Safari/")&&!o.includes("Chrome")?`Safari ${o.match(/Version\/(\d+)/)?.[1]||""}`:o.slice(0,50)}function V(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}async function $(o,e){let t=[],r=JSON.stringify(o,null,2);t.push({name:"report.json",content:new TextEncoder().encode(r)});let n=H(o);if(t.push({name:"summary.md",content:new TextEncoder().encode(n)}),o.screenshot){let s=G(o.screenshot);s&&t.push({name:"screenshot.png",content:s})}if(e){let s=new Uint8Array(await e.arrayBuffer());t.push({name:"recording.webm",content:s})}return Y(t)}function G(o){try{let e=o.split(",")[1];if(!e)return null;let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}catch{return null}}function Y(o){let e=[],t=[],r=0;for(let i of o){let l=new TextEncoder().encode(i.name),p=te(i.content),g=Z(l,i.content.length,p);e.push(g),e.push(l),e.push(i.content);let N=Q(l,i.content.length,p,r);t.push(N),t.push(l),r+=g.length+l.length+i.content.length}let n=r,s=0;for(let i of t)s+=i.length;let a=ee(o.length,s,n),c=[...e,...t,a].map(i=>i.buffer);return new Blob(c,{type:"application/zip"})}function Z(o,e,t){let r=new Uint8Array(30),n=new DataView(r.buffer);return n.setUint32(0,67324752,!0),n.setUint16(4,20,!0),n.setUint16(6,0,!0),n.setUint16(8,0,!0),n.setUint16(10,0,!0),n.setUint16(12,0,!0),n.setUint32(14,t,!0),n.setUint32(18,e,!0),n.setUint32(22,e,!0),n.setUint16(26,o.length,!0),n.setUint16(28,0,!0),r}function Q(o,e,t,r){let n=new Uint8Array(46),s=new DataView(n.buffer);return s.setUint32(0,33639248,!0),s.setUint16(4,20,!0),s.setUint16(6,20,!0),s.setUint16(8,0,!0),s.setUint16(10,0,!0),s.setUint16(12,0,!0),s.setUint16(14,0,!0),s.setUint32(16,t,!0),s.setUint32(20,e,!0),s.setUint32(24,e,!0),s.setUint16(28,o.length,!0),s.setUint16(30,0,!0),s.setUint16(32,0,!0),s.setUint16(34,0,!0),s.setUint16(36,0,!0),s.setUint32(38,0,!0),s.setUint32(42,r,!0),n}function ee(o,e,t){let r=new Uint8Array(22),n=new DataView(r.buffer);return n.setUint32(0,101010256,!0),n.setUint16(4,0,!0),n.setUint16(6,0,!0),n.setUint16(8,o,!0),n.setUint16(10,o,!0),n.setUint32(12,e,!0),n.setUint32(16,t,!0),n.setUint16(20,0,!0),r}function te(o){let e=4294967295;for(let t=0;t<o.length;t++){e^=o[t];for(let r=0;r<8;r++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}var re="0.7.1",ne={maxNetworkEntries:100,maxConsoleEntries:200,maxUserActions:150,maxErrors:50,captureScreenshot:!0,captureHtmlSnapshot:!0,captureCookies:!0,captureLocalStorage:!0,captureSessionStorage:!0,capturePerformance:!0,captureWebVitals:!0,captureMemory:!0,captureConnectivity:!0,sensitiveFields:["password","token","secret","authorization","cookie","session","credit_card","cvv","ssn","cpf"],endpoint:void 0,onCapture:void 0,debugToken:void 0,debugSessionEndpoint:void 0},y=class{constructor(e={}){this.sessionBorder=null;this.debugSession=null;this.dataUploader=null;this.videoUploader=null;this.pageId=h();this.dataInterval=null;this.lastFlushTs=0;this.finalized=!1;this.started=!1;this.config={...ne,...e},this.network=new v(this.config),this.console=new w(this.config),this.errors=new b(this.config),this.userActions=new S(this.config),this.environment=new E,this.performance=new k,this.storage=new U(this.config),this.screenshot=new C,this.featureFlags=new R,this.screenRecorder=new x}start(){if(this.started)return;this.started=!0,this.network.start(),this.console.start(),this.errors.start(),this.userActions.start(),this.config.captureWebVitals&&this.performance.start();let e=this.config.debugToken??M(),t=e??O();e&&D(e,Date.now()+1440*60*1e3),t&&this.startDebugSession(t)}stop(){this.started&&(this.started=!1,this.network.stop(),this.console.stop(),this.errors.stop(),this.userActions.stop(),this.performance.stop(),this.sessionBorder?.unmount())}async startRecording(){await this.screenRecorder.start()}get isRecording(){return this.screenRecorder.isRecording}async capture(e=""){let t={id:h(),timestamp:Date.now(),url:window.location.href,title:document.title,userDescription:e,environment:this.environment.collect(),network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),performance:this.config.capturePerformance?this.performance.collect():null,storage:this.storage.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null,htmlSnapshot:this.config.captureHtmlSnapshot?this.screenshot.captureHtml():null,featureFlags:this.featureFlags.collect(),metadata:{},version:re};return this.config.onCapture&&this.config.onCapture(t),t}async captureAndExport(e=""){let t=await this.screenRecorder.stop(),r=await this.capture(e);if(this.config.endpoint)if(t){let n=new FormData;n.append("report",JSON.stringify(r)),n.append("video",t,"recording.webm"),await fetch(this.config.endpoint,{method:"POST",body:n})}else await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});else{let n=await $(r,t),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=`bug-report-${r.id}.zip`,a.click(),URL.revokeObjectURL(s)}return r}getReport(){return this.capture()}async startDebugSession(e){if(!this.config.debugSessionEndpoint)return;let t=this.config.debugSessionEndpoint,r=()=>{this.sessionBorder=new T,this.sessionBorder.mount()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",r):r();try{let n=this.network.getRawFetch();this.debugSession=await I(t,e,n),D(this.debugSession.token,this.debugSession.expiresAt);let s=j(t,n);this.dataUploader=new m(this.debugSession.token,this.pageId,"data",this.debugSession.publicKey,s,n),this.videoUploader=new m(this.debugSession.token,this.pageId,"video",this.debugSession.publicKey,s,n),this.runSpeedtest(t,this.debugSession.token,n),this.startDataStreaming(),this.registerFlushHandlers(),this.screenRecorder.setChunkHandler(a=>{this.videoUploader?.pushChunk(a)}),this.screenRecorder.start()}catch(n){this.sessionBorder?.unmount();let s=n?.status;(s===401||s===403||s===404)&&P()}}startDataStreaming(){let e=t=>{if(!this.dataUploader)return;let r=this.lastFlushTs,n=Date.now(),s={pageId:this.pageId,timestamp:n,url:window.location.href,network:this.network.getEntries().filter(c=>c.timestamp>r),console:this.console.getEntries().filter(c=>c.timestamp>r),errors:this.errors.getEntries().filter(c=>c.timestamp>r),userActions:this.userActions.getEntries().filter(c=>c.timestamp>r)};this.lastFlushTs=n;let a=new TextEncoder().encode(JSON.stringify(s)+`
85
+ `);this.dataUploader.pushChunk(a,t)};this.dataInterval=setInterval(()=>e(!1),5e3)}registerFlushHandlers(){let e=()=>{this.finalizePage()};window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()})}async finalizePage(){if(this.finalized||!this.debugSession)return;this.finalized=!0,this.dataInterval&&(clearInterval(this.dataInterval),this.dataInterval=null);let e={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,final:!0,network:this.network.getEntries().filter(r=>r.timestamp>this.lastFlushTs),console:this.console.getEntries().filter(r=>r.timestamp>this.lastFlushTs),errors:this.errors.getEntries().filter(r=>r.timestamp>this.lastFlushTs),userActions:this.userActions.getEntries().filter(r=>r.timestamp>this.lastFlushTs),storage:this.storage.collect(),featureFlags:this.featureFlags.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null},t=new TextEncoder().encode(JSON.stringify(e)+`
86
+ `);this.dataUploader?.pushChunk(t,!0),await this.screenRecorder.stop(),await Promise.allSettled([this.dataUploader?.flush()??Promise.resolve(),this.videoUploader?.flush()??Promise.resolve()])}async runSpeedtest(e,t,r){let n=null;try{n=await new B(e,t,r).run()}catch{}await _(e,t,this.pageId,{url:window.location.href,title:document.title,startedAt:Date.now(),environment:this.environment.collect(),speedtest:n},r)}endDebugSession(){P(),this.sessionBorder?.unmount(),this.finalizePage()}};function se(o={}){let e=new y(o);return e.start(),e}typeof window<"u"&&(window.BugJar={BugJar:y,init:se});var We=y;export{y as BugJar,We as default,$ as exportAsZip,H as generateSummary,se as init};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arvoretech/bug-jar",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "Capture everything for non-technical people to help debug. One script tag, zero config.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",