@devskin/browser-sdk 1.0.39 → 1.0.41
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/collectors/heatmap.d.ts +3 -1
- package/dist/collectors/heatmap.d.ts.map +1 -1
- package/dist/devskin.cjs.js +122 -96
- package/dist/devskin.cjs.js.map +1 -1
- package/dist/devskin.esm.js +122 -96
- package/dist/devskin.esm.js.map +1 -1
- package/dist/devskin.umd.js +122 -96
- package/dist/devskin.umd.js.map +1 -1
- package/dist/devskin.umd.min.js +2 -2
- package/dist/devskin.umd.min.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/devskin.umd.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(A,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(A="undefined"!=typeof globalThis?globalThis:A||self).DevSkin=e()}(this,function(){"use strict";function A(A,e,t,r){return new(t||(t=Promise))(function(n,s){function o(A){try{a(r.next(A))}catch(A){s(A)}}function i(A){try{a(r.throw(A))}catch(A){s(A)}}function a(A){var e;A.done?n(A.value):(e=A.value,e instanceof t?e:new t(function(A){A(e)})).then(o,i)}a((r=r.apply(A,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class e{constructor(A){this.config=A}collect(){return{type:this.getDeviceType(),vendor:this.getVendor(),model:this.getModel(),os:this.getOS(),screen:this.getScreenInfo(),memory:this.getMemory(),cores:this.getCores(),connection:this.getConnection()}}getDeviceType(){const A=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(A)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(A)?"mobile":A.includes("Windows")||A.includes("Macintosh")||A.includes("Linux")?"desktop":"unknown"}getVendor(){return navigator.vendor||void 0}getModel(){const A=navigator.userAgent.match(/\(([^)]+)\)/);if(A&&A[1])return A[1]}getOS(){const A=navigator.userAgent;let e="Unknown",t="";if(A.includes("Win"))e="Windows",A.includes("Windows NT 10.0")?t="10":A.includes("Windows NT 6.3")?t="8.1":A.includes("Windows NT 6.2")?t="8":A.includes("Windows NT 6.1")&&(t="7");else if(A.includes("Mac")){e="macOS";const r=A.match(/Mac OS X (\d+[._]\d+[._]\d+)?/);r&&r[1]&&(t=r[1].replace(/_/g,"."))}else if(A.includes("X11")||A.includes("Linux"))e="Linux";else if(A.includes("Android")){e="Android";const r=A.match(/Android (\d+\.?\d*)/);r&&r[1]&&(t=r[1])}else if(A.includes("iOS")||A.includes("iPhone")||A.includes("iPad")){e="iOS";const r=A.match(/OS (\d+_\d+(_\d+)?)/);r&&r[1]&&(t=r[1].replace(/_/g,"."))}return{name:e,version:t}}getScreenInfo(){return{width:window.screen.width,height:window.screen.height,orientation:this.getOrientation(),pixelRatio:window.devicePixelRatio||1}}getOrientation(){return window.screen.orientation?window.screen.orientation.type:window.innerWidth>window.innerHeight?"landscape":"portrait"}getMemory(){return navigator.deviceMemory}getCores(){return navigator.hardwareConcurrency}getConnection(){const A=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(A)return{effectiveType:A.effectiveType,downlink:A.downlink,rtt:A.rtt,saveData:A.saveData}}}class t{constructor(A){this.config=A,this.geoData=null,this.config.captureLocation&&this.requestGeolocation()}collect(){return Object.assign({url:window.location.href,hostname:window.location.hostname,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,protocol:window.location.protocol,port:window.location.port,referrer:document.referrer},this.geoData)}requestGeolocation(){return A(this,void 0,void 0,function*(){try{const A=Intl.DateTimeFormat().resolvedOptions().timeZone;this.geoData={timezone:A},"geolocation"in navigator&&navigator.geolocation.getCurrentPosition(A=>{this.geoData=Object.assign(Object.assign({},this.geoData),{latitude:A.coords.latitude,longitude:A.coords.longitude}),this.reverseGeocode(A.coords.latitude,A.coords.longitude)},A=>{this.config.debug&&console.log("[DevSkin] Geolocation permission denied or error:",A)},{timeout:5e3,maximumAge:6e5})}catch(A){this.config.debug&&console.error("[DevSkin] Error requesting geolocation:",A)}})}reverseGeocode(e,t){return A(this,void 0,void 0,function*(){try{const A=yield fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${e}&lon=${t}&zoom=10&addressdetails=1`,{headers:{"User-Agent":"DevSkin-SDK/1.0"}});if(A.ok){const e=yield A.json();e.address&&(this.geoData=Object.assign(Object.assign({},this.geoData),{country:e.address.country,region:e.address.state||e.address.region,city:e.address.city||e.address.town||e.address.village}))}}catch(A){this.config.debug&&console.error("[DevSkin] Error reverse geocoding:",A)}})}}class r{constructor(A){this.config=A}collect(){return{name:this.getBrowserName(),version:this.getBrowserVersion(),engine:this.getEngine(),userAgent:navigator.userAgent,language:navigator.language,languages:navigator.languages?Array.from(navigator.languages):[navigator.language],cookieEnabled:navigator.cookieEnabled,doNotTrack:this.getDoNotTrack(),viewport:{width:window.innerWidth,height:window.innerHeight},timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:(new Date).getTimezoneOffset()}}getBrowserName(){const A=navigator.userAgent;return A.includes("Firefox")?"Firefox":A.includes("Edg")?"Edge":A.includes("Chrome")?"Chrome":A.includes("Safari")&&!A.includes("Chrome")?"Safari":A.includes("Opera")||A.includes("OPR")?"Opera":A.includes("Trident")||A.includes("MSIE")?"Internet Explorer":"Unknown"}getBrowserVersion(){const A=navigator.userAgent;let e=null;switch(this.getBrowserName()){case"Chrome":e=A.match(/Chrome\/(\d+\.\d+)/);break;case"Firefox":e=A.match(/Firefox\/(\d+\.\d+)/);break;case"Safari":e=A.match(/Version\/(\d+\.\d+)/);break;case"Edge":e=A.match(/Edg\/(\d+\.\d+)/);break;case"Opera":if(e=A.match(/(Opera|OPR)\/(\d+\.\d+)/),e)return e[2];break;case"Internet Explorer":if(e=A.match(/(MSIE |rv:)(\d+\.\d+)/),e)return e[2]}return e&&e[1]?e[1]:""}getEngine(){const A=navigator.userAgent;return A.includes("Gecko")&&A.includes("Firefox")?"Gecko":A.includes("AppleWebKit")?A.includes("Chrome")||A.includes("Edg")?"Blink":"WebKit":A.includes("Trident")?"Trident":"Unknown"}getDoNotTrack(){const A=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===A||"yes"===A||"0"!==A&&"no"!==A&&null}}var n,s,o,i,a=-1,c=function(A){addEventListener("pageshow",function(e){e.persisted&&(a=e.timeStamp,A(e))},!0)},B=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},l=function(){var A=B();return A&&A.activationStart||0},u=function(A,e){var t=B(),r="navigate";return a>=0?r="back-forward-cache":t&&(document.prerendering||l()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:A,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},g=function(A,e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(A)){var r=new PerformanceObserver(function(A){Promise.resolve().then(function(){e(A.getEntries())})});return r.observe(Object.assign({type:A,buffered:!0},t||{})),r}}catch(A){}},d=function(A,e,t,r){var n,s;return function(o){e.value>=0&&(o||r)&&((s=e.value-(n||0))||void 0===n)&&(n=e.value,e.delta=s,e.rating=function(A,e){return A>e[1]?"poor":A>e[0]?"needs-improvement":"good"}(e.value,t),A(e))}},h=function(A){requestAnimationFrame(function(){return requestAnimationFrame(function(){return A()})})},w=function(A){var e=function(e){"pagehide"!==e.type&&"hidden"!==document.visibilityState||A(e)};addEventListener("visibilitychange",e,!0),addEventListener("pagehide",e,!0)},Q=function(A){var e=!1;return function(t){e||(A(t),e=!0)}},p=-1,C=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},f=function(A){"hidden"===document.visibilityState&&p>-1&&(p="visibilitychange"===A.type?A.timeStamp:0,F())},U=function(){addEventListener("visibilitychange",f,!0),addEventListener("prerenderingchange",f,!0)},F=function(){removeEventListener("visibilitychange",f,!0),removeEventListener("prerenderingchange",f,!0)},m=function(){return p<0&&(p=C(),U(),c(function(){setTimeout(function(){p=C(),U()},0)})),{get firstHiddenTime(){return p}}},y=function(A){document.prerendering?addEventListener("prerenderingchange",function(){return A()},!0):A()},I=[1800,3e3],E=function(A,e){e=e||{},y(function(){var t,r=m(),n=u("FCP"),s=g("paint",function(A){A.forEach(function(A){"first-contentful-paint"===A.name&&(s.disconnect(),A.startTime<r.firstHiddenTime&&(n.value=Math.max(A.startTime-l(),0),n.entries.push(A),t(!0)))})});s&&(t=d(A,n,I,e.reportAllChanges),c(function(r){n=u("FCP"),t=d(A,n,I,e.reportAllChanges),h(function(){n.value=performance.now()-r.timeStamp,t(!0)})}))})},H=[.1,.25],v={passive:!0,capture:!0},b=new Date,S=function(A,e){n||(n=e,s=A,o=new Date,D(removeEventListener),L())},L=function(){if(s>=0&&s<o-b){var A={entryType:"first-input",name:n.type,target:n.target,cancelable:n.cancelable,startTime:n.timeStamp,processingStart:n.timeStamp+s};i.forEach(function(e){e(A)}),i=[]}},K=function(A){if(A.cancelable){var e=(A.timeStamp>1e12?new Date:performance.now())-A.timeStamp;"pointerdown"==A.type?function(A,e){var t=function(){S(A,e),n()},r=function(){n()},n=function(){removeEventListener("pointerup",t,v),removeEventListener("pointercancel",r,v)};addEventListener("pointerup",t,v),addEventListener("pointercancel",r,v)}(e,A):S(e,A)}},D=function(A){["mousedown","keydown","touchstart","pointerdown"].forEach(function(e){return A(e,K,v)})},M=[100,300],k=[2500,4e3],T={},O=[800,1800],x=function A(e){document.prerendering?y(function(){return A(e)}):"complete"!==document.readyState?addEventListener("load",function(){return A(e)},!0):setTimeout(e,0)},R=function(A,e){e=e||{};var t=u("TTFB"),r=d(A,t,O,e.reportAllChanges);x(function(){var n=B();if(n){var s=n.responseStart;if(s<=0||s>performance.now())return;t.value=Math.max(s-l(),0),t.entries=[n],r(!0),c(function(){t=u("TTFB",0),(r=d(A,t,O,e.reportAllChanges))(!0)})}})};class N{constructor(A,e){this.config=A,this.transport=e,this.metrics={}}start(){!function(A,e){e=e||{},E(Q(function(){var t,r=u("CLS",0),n=0,s=[],o=function(A){A.forEach(function(A){if(!A.hadRecentInput){var e=s[0],t=s[s.length-1];n&&A.startTime-t.startTime<1e3&&A.startTime-e.startTime<5e3?(n+=A.value,s.push(A)):(n=A.value,s=[A])}}),n>r.value&&(r.value=n,r.entries=s,t())},i=g("layout-shift",o);i&&(t=d(A,r,H,e.reportAllChanges),w(function(){o(i.takeRecords()),t(!0)}),c(function(){n=0,r=u("CLS",0),t=d(A,r,H,e.reportAllChanges),h(function(){return t()})}),setTimeout(t,0))}))}(A=>this.handleMetric(A)),E(A=>this.handleMetric(A)),function(A,e){e=e||{},y(function(){var t,r=m(),o=u("FID"),a=function(A){A.startTime<r.firstHiddenTime&&(o.value=A.processingStart-A.startTime,o.entries.push(A),t(!0))},B=function(A){A.forEach(a)},l=g("first-input",B);t=d(A,o,M,e.reportAllChanges),l&&w(Q(function(){B(l.takeRecords()),l.disconnect()})),l&&c(function(){var r;o=u("FID"),t=d(A,o,M,e.reportAllChanges),i=[],s=-1,n=null,D(addEventListener),r=a,i.push(r),L()})})}(A=>this.handleMetric(A)),function(A,e){e=e||{},y(function(){var t,r=m(),n=u("LCP"),s=function(A){var e=A[A.length-1];e&&e.startTime<r.firstHiddenTime&&(n.value=Math.max(e.startTime-l(),0),n.entries=[e],t())},o=g("largest-contentful-paint",s);if(o){t=d(A,n,k,e.reportAllChanges);var i=Q(function(){T[n.id]||(s(o.takeRecords()),o.disconnect(),T[n.id]=!0,t(!0))});["keydown","click"].forEach(function(A){addEventListener(A,function(){return setTimeout(i,0)},!0)}),w(i),c(function(r){n=u("LCP"),t=d(A,n,k,e.reportAllChanges),h(function(){n.value=performance.now()-r.timeStamp,T[n.id]=!0,t(!0)})})}})}(A=>this.handleMetric(A)),R(A=>this.handleMetric(A)),this.collectNavigationTimings(),this.collectResourceTimings(),this.config.longTaskThreshold&&this.observeLongTasks()}handleMetric(A){const e=A.name.toLowerCase();this.metrics[e]=A.value,this.config.debug&&console.log(`[DevSkin] Web Vital ${A.name}:`,A.value),this.transport.sendPerformanceMetric({metricName:A.name,value:A.value,rating:A.rating,url:window.location.href,timestamp:(new Date).toISOString()})}collectNavigationTimings(){window.performance&&window.performance.timing&&window.addEventListener("load",()=>{setTimeout(()=>{const A=window.performance.timing,e=window.performance.navigation,t=A.domContentLoadedEventEnd-A.navigationStart,r=A.loadEventEnd-A.navigationStart;this.metrics.domLoad=t,this.metrics.windowLoad=r,this.config.debug&&console.log("[DevSkin] Navigation Timings:",{domLoad:t,windowLoad:r,navigationType:e.type}),this.transport.sendPerformanceMetric({metricName:"Navigation",value:r,url:window.location.href,timestamp:(new Date).toISOString()})},0)})}collectResourceTimings(){window.performance&&window.performance.getEntriesByType&&window.addEventListener("load",()=>{setTimeout(()=>{const A=window.performance.getEntriesByType("resource"),e={total:A.length,byType:{},slowest:[]};A.forEach(A=>{const t=A.initiatorType||"other";e.byType[t]=(e.byType[t]||0)+1}),e.slowest=A.map(A=>({name:A.name,duration:A.duration,type:A.initiatorType})).sort((A,e)=>e.duration-A.duration).slice(0,10),this.config.debug&&console.log("[DevSkin] Resource Timings:",e),this.transport.sendPerformanceMetric({metricName:"Resources",value:A.length,url:window.location.href,timestamp:(new Date).toISOString()})},1e3)})}observeLongTasks(){if("PerformanceObserver"in window)try{new PerformanceObserver(A=>{for(const e of A.getEntries())e.duration>=(this.config.longTaskThreshold||50)&&(this.config.debug&&console.log("[DevSkin] Long Task detected:",e),this.transport.sendPerformanceMetric({metricName:"LongTask",value:e.duration,url:window.location.href,timestamp:(new Date).toISOString()}))}).observe({entryTypes:["longtask"]})}catch(A){this.config.debug&&console.error("[DevSkin] Error observing long tasks:",A)}}getMetrics(){return Object.assign({},this.metrics)}}class G{constructor(A,e){var t;this.config=A,this.transport=e,this.breadcrumbs=[],this.maxBreadcrumbs=(null===(t=A.errorOptions)||void 0===t?void 0:t.maxBreadcrumbs)||30}start(){window.addEventListener("error",A=>{this.handleError(A.error||A.message,{filename:A.filename,lineno:A.lineno,colno:A.colno})}),window.addEventListener("unhandledrejection",A=>{this.handleError(A.reason,{type:"unhandledrejection"})}),this.setupAutomaticBreadcrumbs()}captureError(A,e){this.handleError(A,e)}addBreadcrumb(A){const e={category:A.category,message:A.message,level:A.level||"info",timestamp:(new Date).toISOString(),data:A.data};this.breadcrumbs.push(e),this.breadcrumbs.length>this.maxBreadcrumbs&&this.breadcrumbs.shift(),this.config.debug&&console.log("[DevSkin] Breadcrumb added:",e)}handleError(A,e){var t;if(this.shouldIgnoreError(A))return;let r;if(A instanceof Error){if(r={message:A.message,stack:A.stack,type:A.name||"Error",timestamp:(new Date).toISOString(),sessionId:"",url:window.location.href,breadcrumbs:[...this.breadcrumbs],context:Object.assign(Object.assign({},e),{userAgent:navigator.userAgent,viewport:{width:window.innerWidth,height:window.innerHeight}})},A.stack){const e=A.stack.match(/:(\d+):(\d+)/);e&&(r.line=parseInt(e[1],10),r.column=parseInt(e[2],10))}}else r={message:String(A),type:"Error",timestamp:(new Date).toISOString(),sessionId:"",url:window.location.href,breadcrumbs:[...this.breadcrumbs],context:e};(null===(t=this.config.errorOptions)||void 0===t?void 0:t.includeLocalVariables)&&e&&(r.context=Object.assign(Object.assign({},r.context),{localVariables:e})),this.config.debug&&console.log("[DevSkin] Error captured:",r),this.addBreadcrumb({category:"error",message:r.message,level:"error",data:{type:r.type,stack:r.stack}}),this.transport.sendError(r)}shouldIgnoreError(A){var e,t;const r=(null===(e=this.config.errorOptions)||void 0===e?void 0:e.ignoreErrors)||[],n=A instanceof Error?A.message:String(A);for(const A of r)if(A instanceof RegExp){if(A.test(n))return!0}else if("string"==typeof A&&n.includes(A))return!0;const s=(null===(t=this.config.errorOptions)||void 0===t?void 0:t.denyUrls)||[],o=A instanceof Error?A.stack:"";for(const A of s)if(A.test(o||""))return!0;return!1}setupAutomaticBreadcrumbs(){this.wrapConsole(),document.addEventListener("click",A=>{var e;const t=A.target;this.addBreadcrumb({category:"ui.click",message:`Clicked on ${t.tagName}`,data:{tagName:t.tagName,id:t.id,className:t.className,innerText:null===(e=t.innerText)||void 0===e?void 0:e.substring(0,100)}})},!0);let A=window.location.href;const e=()=>{A!==window.location.href&&(this.addBreadcrumb({category:"navigation",message:`Navigated to ${window.location.pathname}`,data:{from:A,to:window.location.href}}),A=window.location.href)};window.addEventListener("popstate",e),window.addEventListener("hashchange",e);const t=history.pushState;history.pushState=function(...A){t.apply(this,A),e()};const r=history.replaceState;history.replaceState=function(...A){r.apply(this,A),e()}}wrapConsole(){["log","info","warn","error"].forEach(A=>{const e=console[A];console[A]=(...t)=>{if(e.apply(console,t),"warn"===A||"error"===A){const e=t.map(A=>String(A)).join(" ");if(e.startsWith("[DevSkin]"))return;this.addBreadcrumb({category:"console",message:e,level:"warn"===A?"warning":"error",data:{arguments:t}})}}})}getBreadcrumbs(){return[...this.breadcrumbs]}}class V{constructor(A,e){this.config=A,this.transport=e}start(){this.interceptFetch(),this.interceptXHR()}interceptFetch(){if(!window.fetch)return;const e=window.fetch;window.fetch=(...t)=>A(this,void 0,void 0,function*(){var A,r;const[n,s]=t,o="string"==typeof n?n:n instanceof Request?n.url:n.toString(),i=(null==s?void 0:s.method)||"GET",a=Date.now();try{const n=yield e(...t),s=n.clone(),c=Date.now()-a;if(this.shouldIgnoreUrl(o))return n;if((null===(A=this.config.networkRequestOptions)||void 0===A?void 0:A.captureFailedOnly)&&n.ok)return n;const B={url:o,method:i,statusCode:n.status,durationMs:c,responseSize:yield this.getResponseSize(s),timestamp:(new Date).toISOString()};return(null===(r=this.config.networkRequestOptions)||void 0===r?void 0:r.captureHeaders)&&(B.responseHeaders=this.headersToObject(n.headers)),n.ok||(B.errorMessage=`HTTP ${n.status} ${n.statusText}`),this.config.debug&&console.log("[DevSkin] Network request tracked:",B),this.transport.sendNetworkRequest(B),n}catch(A){const e=Date.now()-a;if(!this.shouldIgnoreUrl(o)){const t={url:o,method:i,durationMs:e,timestamp:(new Date).toISOString(),errorMessage:A instanceof Error?A.message:"Network request failed"};this.config.debug&&console.log("[DevSkin] Network request failed:",t),this.transport.sendNetworkRequest(t)}throw A}})}interceptXHR(){const A=XMLHttpRequest.prototype.open,e=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,r,n,s){return this.__devskin={method:e,url:t.toString(),startTime:Date.now()},void 0!==n?A.call(this,e,t,null==r||r,n,null!=s?s:void 0):void 0!==r?A.call(this,e,t,r):A.call(this,e,t,!0)},XMLHttpRequest.prototype.send=function(A){const t=this,r=t.__devskin;if(!r)return e.call(this,A);const n=window.__devskinNetworkCollector,s=()=>{const A=Date.now()-r.startTime;if(!(null==n?void 0:n.shouldIgnoreUrl(r.url))){const e={url:r.url,method:r.method,durationMs:A,timestamp:(new Date).toISOString(),errorMessage:"XHR request failed"};(null==n?void 0:n.config.debug)&&console.log("[DevSkin] XHR request failed:",e),null==n||n.transport.sendNetworkRequest(e)}};return t.addEventListener("load",()=>{var A,e;const s=Date.now()-r.startTime;if(null==n?void 0:n.shouldIgnoreUrl(r.url))return;if((null===(A=null==n?void 0:n.config.networkRequestOptions)||void 0===A?void 0:A.captureFailedOnly)&&t.status>=200&&t.status<400)return;const o={url:r.url,method:r.method,statusCode:t.status,durationMs:s,timestamp:(new Date).toISOString()};(null===(e=null==n?void 0:n.config.networkRequestOptions)||void 0===e?void 0:e.captureHeaders)&&(o.responseHeaders=n.parseResponseHeaders(t.getAllResponseHeaders())),(0===t.status||t.status>=400)&&(o.errorMessage=`HTTP ${t.status} ${t.statusText}`),(null==n?void 0:n.config.debug)&&console.log("[DevSkin] XHR request tracked:",o),null==n||n.transport.sendNetworkRequest(o)}),t.addEventListener("error",s),t.addEventListener("abort",s),e.call(this,A)},window.__devskinNetworkCollector=this}shouldIgnoreUrl(A){var e;if(A.includes(this.config.apiUrl||""))return!0;const t=(null===(e=this.config.networkRequestOptions)||void 0===e?void 0:e.ignoreUrls)||[];for(const e of t)if(e.test(A))return!0;return!1}getResponseSize(e){return A(this,void 0,void 0,function*(){try{return(yield e.blob()).size}catch(A){return}})}headersToObject(A){const e={};return A.forEach((A,t)=>{e[t]=A}),e}parseResponseHeaders(A){const e={};if(!A)return e;return A.trim().split(/[\r\n]+/).forEach(A=>{const t=A.split(": "),r=t.shift(),n=t.join(": ");r&&(e[r]=n)}),e}}class P{constructor(A,e){this.config=A,this.transport=e,this.clickData=[],this.scrollData=[],this.mouseMoveData=[],this.maxScrollDepth=0,this.flushInterval=null,this.mouseMoveSampling=.1}start(){var A;(null===(A=this.config.heatmapOptions)||void 0===A?void 0:A.enabled)&&(this.config.debug&&console.log("[DevSkin] Starting heatmap collection"),!1!==this.config.heatmapOptions.trackClicks&&this.trackClicks(),!1!==this.config.heatmapOptions.trackScroll&&this.trackScrollDepth(),this.config.heatmapOptions.trackMouseMovement&&(this.mouseMoveSampling=this.config.heatmapOptions.mouseMoveSampling||.1,this.trackMouseMovement()),this.flushInterval=setInterval(()=>{this.flush()},1e4),window.addEventListener("beforeunload",()=>{this.flush()}))}stop(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}trackClicks(){document.addEventListener("click",A=>{const e=A.target,t=e.getBoundingClientRect(),r=A.clientX-t.left,n=A.clientY-t.top,s=A.clientX+window.scrollX,o=A.clientY+window.scrollY,i={x:A.clientX,y:A.clientY,relativeX:r,relativeY:n,pageX:s,pageY:o,element:this.getElementSelector(e),elementId:e.id||void 0,elementClass:e.className||void 0,pageUrl:window.location.href,timestamp:(new Date).toISOString(),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight};this.clickData.push(i),this.config.debug&&console.log("[DevSkin] Click tracked:",i),this.clickData.length>=50&&this.flush()},!0)}trackScrollDepth(){const A=()=>{const A=window.innerHeight,e=document.documentElement.scrollHeight,t=window.scrollY||document.documentElement.scrollTop,r=Math.round((t+A)/e*100);if(r>this.maxScrollDepth){this.maxScrollDepth=r;const t={depth:r,maxDepth:this.maxScrollDepth,pageHeight:e,viewportHeight:A,pageUrl:window.location.href,timestamp:(new Date).toISOString()};this.scrollData.push(t),this.config.debug&&console.log("[DevSkin] Scroll depth:",r+"%")}};let e=null;window.addEventListener("scroll",()=>{e&&clearTimeout(e),e=setTimeout(A,100)}),A()}trackMouseMovement(){let A=null;window.addEventListener("mousemove",e=>{if(Math.random()>this.mouseMoveSampling)return;if(A)return;A=setTimeout(()=>{A=null},100);const t={x:e.clientX+window.scrollX,y:e.clientY+window.scrollY,pageUrl:window.location.href,timestamp:(new Date).toISOString()};this.mouseMoveData.push(t),this.mouseMoveData.length>=100&&this.flush()})}flush(){this.clickData.length>0&&(this.clickData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"click"},A))}),this.clickData=[]),this.scrollData.length>0&&(this.scrollData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"scroll"},A))}),this.scrollData=[]),this.mouseMoveData.length>0&&(this.mouseMoveData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"mousemove"},A))}),this.mouseMoveData=[])}getElementSelector(A){if(A.id)return`#${A.id}`;if(A.className){const e=A.className.split(" ").filter(A=>A);if(e.length>0)return`${A.tagName.toLowerCase()}.${e.join(".")}`}return A.tagName.toLowerCase()}}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function X(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var J={exports:{}};
|
|
1
|
+
!function(A,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(A="undefined"!=typeof globalThis?globalThis:A||self).DevSkin=e()}(this,function(){"use strict";function A(A,e,t,r){return new(t||(t=Promise))(function(n,s){function o(A){try{a(r.next(A))}catch(A){s(A)}}function i(A){try{a(r.throw(A))}catch(A){s(A)}}function a(A){var e;A.done?n(A.value):(e=A.value,e instanceof t?e:new t(function(A){A(e)})).then(o,i)}a((r=r.apply(A,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class e{constructor(A){this.config=A}collect(){return{type:this.getDeviceType(),vendor:this.getVendor(),model:this.getModel(),os:this.getOS(),screen:this.getScreenInfo(),memory:this.getMemory(),cores:this.getCores(),connection:this.getConnection()}}getDeviceType(){const A=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(A)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(A)?"mobile":A.includes("Windows")||A.includes("Macintosh")||A.includes("Linux")?"desktop":"unknown"}getVendor(){return navigator.vendor||void 0}getModel(){const A=navigator.userAgent.match(/\(([^)]+)\)/);if(A&&A[1])return A[1]}getOS(){const A=navigator.userAgent;let e="Unknown",t="";if(A.includes("Win"))e="Windows",A.includes("Windows NT 10.0")?t="10":A.includes("Windows NT 6.3")?t="8.1":A.includes("Windows NT 6.2")?t="8":A.includes("Windows NT 6.1")&&(t="7");else if(A.includes("Mac")){e="macOS";const r=A.match(/Mac OS X (\d+[._]\d+[._]\d+)?/);r&&r[1]&&(t=r[1].replace(/_/g,"."))}else if(A.includes("X11")||A.includes("Linux"))e="Linux";else if(A.includes("Android")){e="Android";const r=A.match(/Android (\d+\.?\d*)/);r&&r[1]&&(t=r[1])}else if(A.includes("iOS")||A.includes("iPhone")||A.includes("iPad")){e="iOS";const r=A.match(/OS (\d+_\d+(_\d+)?)/);r&&r[1]&&(t=r[1].replace(/_/g,"."))}return{name:e,version:t}}getScreenInfo(){return{width:window.screen.width,height:window.screen.height,orientation:this.getOrientation(),pixelRatio:window.devicePixelRatio||1}}getOrientation(){return window.screen.orientation?window.screen.orientation.type:window.innerWidth>window.innerHeight?"landscape":"portrait"}getMemory(){return navigator.deviceMemory}getCores(){return navigator.hardwareConcurrency}getConnection(){const A=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(A)return{effectiveType:A.effectiveType,downlink:A.downlink,rtt:A.rtt,saveData:A.saveData}}}class t{constructor(A){this.config=A,this.geoData=null,this.config.captureLocation&&this.requestGeolocation()}collect(){return Object.assign({url:window.location.href,hostname:window.location.hostname,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,protocol:window.location.protocol,port:window.location.port,referrer:document.referrer},this.geoData)}requestGeolocation(){return A(this,void 0,void 0,function*(){try{const A=Intl.DateTimeFormat().resolvedOptions().timeZone;this.geoData={timezone:A},"geolocation"in navigator&&navigator.geolocation.getCurrentPosition(A=>{this.geoData=Object.assign(Object.assign({},this.geoData),{latitude:A.coords.latitude,longitude:A.coords.longitude}),this.reverseGeocode(A.coords.latitude,A.coords.longitude)},A=>{this.config.debug&&console.log("[DevSkin] Geolocation permission denied or error:",A)},{timeout:5e3,maximumAge:6e5})}catch(A){this.config.debug&&console.error("[DevSkin] Error requesting geolocation:",A)}})}reverseGeocode(e,t){return A(this,void 0,void 0,function*(){try{const A=yield fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${e}&lon=${t}&zoom=10&addressdetails=1`,{headers:{"User-Agent":"DevSkin-SDK/1.0"}});if(A.ok){const e=yield A.json();e.address&&(this.geoData=Object.assign(Object.assign({},this.geoData),{country:e.address.country,region:e.address.state||e.address.region,city:e.address.city||e.address.town||e.address.village}))}}catch(A){this.config.debug&&console.error("[DevSkin] Error reverse geocoding:",A)}})}}class r{constructor(A){this.config=A}collect(){return{name:this.getBrowserName(),version:this.getBrowserVersion(),engine:this.getEngine(),userAgent:navigator.userAgent,language:navigator.language,languages:navigator.languages?Array.from(navigator.languages):[navigator.language],cookieEnabled:navigator.cookieEnabled,doNotTrack:this.getDoNotTrack(),viewport:{width:window.innerWidth,height:window.innerHeight},timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:(new Date).getTimezoneOffset()}}getBrowserName(){const A=navigator.userAgent;return A.includes("Firefox")?"Firefox":A.includes("Edg")?"Edge":A.includes("Chrome")?"Chrome":A.includes("Safari")&&!A.includes("Chrome")?"Safari":A.includes("Opera")||A.includes("OPR")?"Opera":A.includes("Trident")||A.includes("MSIE")?"Internet Explorer":"Unknown"}getBrowserVersion(){const A=navigator.userAgent;let e=null;switch(this.getBrowserName()){case"Chrome":e=A.match(/Chrome\/(\d+\.\d+)/);break;case"Firefox":e=A.match(/Firefox\/(\d+\.\d+)/);break;case"Safari":e=A.match(/Version\/(\d+\.\d+)/);break;case"Edge":e=A.match(/Edg\/(\d+\.\d+)/);break;case"Opera":if(e=A.match(/(Opera|OPR)\/(\d+\.\d+)/),e)return e[2];break;case"Internet Explorer":if(e=A.match(/(MSIE |rv:)(\d+\.\d+)/),e)return e[2]}return e&&e[1]?e[1]:""}getEngine(){const A=navigator.userAgent;return A.includes("Gecko")&&A.includes("Firefox")?"Gecko":A.includes("AppleWebKit")?A.includes("Chrome")||A.includes("Edg")?"Blink":"WebKit":A.includes("Trident")?"Trident":"Unknown"}getDoNotTrack(){const A=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===A||"yes"===A||"0"!==A&&"no"!==A&&null}}var n,s,o,i,a=-1,c=function(A){addEventListener("pageshow",function(e){e.persisted&&(a=e.timeStamp,A(e))},!0)},B=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},l=function(){var A=B();return A&&A.activationStart||0},u=function(A,e){var t=B(),r="navigate";return a>=0?r="back-forward-cache":t&&(document.prerendering||l()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:A,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},g=function(A,e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(A)){var r=new PerformanceObserver(function(A){Promise.resolve().then(function(){e(A.getEntries())})});return r.observe(Object.assign({type:A,buffered:!0},t||{})),r}}catch(A){}},d=function(A,e,t,r){var n,s;return function(o){e.value>=0&&(o||r)&&((s=e.value-(n||0))||void 0===n)&&(n=e.value,e.delta=s,e.rating=function(A,e){return A>e[1]?"poor":A>e[0]?"needs-improvement":"good"}(e.value,t),A(e))}},h=function(A){requestAnimationFrame(function(){return requestAnimationFrame(function(){return A()})})},w=function(A){var e=function(e){"pagehide"!==e.type&&"hidden"!==document.visibilityState||A(e)};addEventListener("visibilitychange",e,!0),addEventListener("pagehide",e,!0)},Q=function(A){var e=!1;return function(t){e||(A(t),e=!0)}},p=-1,C=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},f=function(A){"hidden"===document.visibilityState&&p>-1&&(p="visibilitychange"===A.type?A.timeStamp:0,F())},U=function(){addEventListener("visibilitychange",f,!0),addEventListener("prerenderingchange",f,!0)},F=function(){removeEventListener("visibilitychange",f,!0),removeEventListener("prerenderingchange",f,!0)},m=function(){return p<0&&(p=C(),U(),c(function(){setTimeout(function(){p=C(),U()},0)})),{get firstHiddenTime(){return p}}},y=function(A){document.prerendering?addEventListener("prerenderingchange",function(){return A()},!0):A()},I=[1800,3e3],E=function(A,e){e=e||{},y(function(){var t,r=m(),n=u("FCP"),s=g("paint",function(A){A.forEach(function(A){"first-contentful-paint"===A.name&&(s.disconnect(),A.startTime<r.firstHiddenTime&&(n.value=Math.max(A.startTime-l(),0),n.entries.push(A),t(!0)))})});s&&(t=d(A,n,I,e.reportAllChanges),c(function(r){n=u("FCP"),t=d(A,n,I,e.reportAllChanges),h(function(){n.value=performance.now()-r.timeStamp,t(!0)})}))})},H=[.1,.25],v={passive:!0,capture:!0},b=new Date,S=function(A,e){n||(n=e,s=A,o=new Date,D(removeEventListener),L())},L=function(){if(s>=0&&s<o-b){var A={entryType:"first-input",name:n.type,target:n.target,cancelable:n.cancelable,startTime:n.timeStamp,processingStart:n.timeStamp+s};i.forEach(function(e){e(A)}),i=[]}},K=function(A){if(A.cancelable){var e=(A.timeStamp>1e12?new Date:performance.now())-A.timeStamp;"pointerdown"==A.type?function(A,e){var t=function(){S(A,e),n()},r=function(){n()},n=function(){removeEventListener("pointerup",t,v),removeEventListener("pointercancel",r,v)};addEventListener("pointerup",t,v),addEventListener("pointercancel",r,v)}(e,A):S(e,A)}},D=function(A){["mousedown","keydown","touchstart","pointerdown"].forEach(function(e){return A(e,K,v)})},M=[100,300],k=[2500,4e3],T={},O=[800,1800],x=function A(e){document.prerendering?y(function(){return A(e)}):"complete"!==document.readyState?addEventListener("load",function(){return A(e)},!0):setTimeout(e,0)},R=function(A,e){e=e||{};var t=u("TTFB"),r=d(A,t,O,e.reportAllChanges);x(function(){var n=B();if(n){var s=n.responseStart;if(s<=0||s>performance.now())return;t.value=Math.max(s-l(),0),t.entries=[n],r(!0),c(function(){t=u("TTFB",0),(r=d(A,t,O,e.reportAllChanges))(!0)})}})};class N{constructor(A,e){this.config=A,this.transport=e,this.metrics={}}start(){!function(A,e){e=e||{},E(Q(function(){var t,r=u("CLS",0),n=0,s=[],o=function(A){A.forEach(function(A){if(!A.hadRecentInput){var e=s[0],t=s[s.length-1];n&&A.startTime-t.startTime<1e3&&A.startTime-e.startTime<5e3?(n+=A.value,s.push(A)):(n=A.value,s=[A])}}),n>r.value&&(r.value=n,r.entries=s,t())},i=g("layout-shift",o);i&&(t=d(A,r,H,e.reportAllChanges),w(function(){o(i.takeRecords()),t(!0)}),c(function(){n=0,r=u("CLS",0),t=d(A,r,H,e.reportAllChanges),h(function(){return t()})}),setTimeout(t,0))}))}(A=>this.handleMetric(A)),E(A=>this.handleMetric(A)),function(A,e){e=e||{},y(function(){var t,r=m(),o=u("FID"),a=function(A){A.startTime<r.firstHiddenTime&&(o.value=A.processingStart-A.startTime,o.entries.push(A),t(!0))},B=function(A){A.forEach(a)},l=g("first-input",B);t=d(A,o,M,e.reportAllChanges),l&&w(Q(function(){B(l.takeRecords()),l.disconnect()})),l&&c(function(){var r;o=u("FID"),t=d(A,o,M,e.reportAllChanges),i=[],s=-1,n=null,D(addEventListener),r=a,i.push(r),L()})})}(A=>this.handleMetric(A)),function(A,e){e=e||{},y(function(){var t,r=m(),n=u("LCP"),s=function(A){var e=A[A.length-1];e&&e.startTime<r.firstHiddenTime&&(n.value=Math.max(e.startTime-l(),0),n.entries=[e],t())},o=g("largest-contentful-paint",s);if(o){t=d(A,n,k,e.reportAllChanges);var i=Q(function(){T[n.id]||(s(o.takeRecords()),o.disconnect(),T[n.id]=!0,t(!0))});["keydown","click"].forEach(function(A){addEventListener(A,function(){return setTimeout(i,0)},!0)}),w(i),c(function(r){n=u("LCP"),t=d(A,n,k,e.reportAllChanges),h(function(){n.value=performance.now()-r.timeStamp,T[n.id]=!0,t(!0)})})}})}(A=>this.handleMetric(A)),R(A=>this.handleMetric(A)),this.collectNavigationTimings(),this.collectResourceTimings(),this.config.longTaskThreshold&&this.observeLongTasks()}handleMetric(A){const e=A.name.toLowerCase();this.metrics[e]=A.value,this.config.debug&&console.log(`[DevSkin] Web Vital ${A.name}:`,A.value),this.transport.sendPerformanceMetric({metricName:A.name,value:A.value,rating:A.rating,url:window.location.href,timestamp:(new Date).toISOString()})}collectNavigationTimings(){window.performance&&window.performance.timing&&window.addEventListener("load",()=>{setTimeout(()=>{const A=window.performance.timing,e=window.performance.navigation,t=A.domContentLoadedEventEnd-A.navigationStart,r=A.loadEventEnd-A.navigationStart;this.metrics.domLoad=t,this.metrics.windowLoad=r,this.config.debug&&console.log("[DevSkin] Navigation Timings:",{domLoad:t,windowLoad:r,navigationType:e.type}),this.transport.sendPerformanceMetric({metricName:"Navigation",value:r,url:window.location.href,timestamp:(new Date).toISOString()})},0)})}collectResourceTimings(){window.performance&&window.performance.getEntriesByType&&window.addEventListener("load",()=>{setTimeout(()=>{const A=window.performance.getEntriesByType("resource"),e={total:A.length,byType:{},slowest:[]};A.forEach(A=>{const t=A.initiatorType||"other";e.byType[t]=(e.byType[t]||0)+1}),e.slowest=A.map(A=>({name:A.name,duration:A.duration,type:A.initiatorType})).sort((A,e)=>e.duration-A.duration).slice(0,10),this.config.debug&&console.log("[DevSkin] Resource Timings:",e),this.transport.sendPerformanceMetric({metricName:"Resources",value:A.length,url:window.location.href,timestamp:(new Date).toISOString()})},1e3)})}observeLongTasks(){if("PerformanceObserver"in window)try{new PerformanceObserver(A=>{for(const e of A.getEntries())e.duration>=(this.config.longTaskThreshold||50)&&(this.config.debug&&console.log("[DevSkin] Long Task detected:",e),this.transport.sendPerformanceMetric({metricName:"LongTask",value:e.duration,url:window.location.href,timestamp:(new Date).toISOString()}))}).observe({entryTypes:["longtask"]})}catch(A){this.config.debug&&console.error("[DevSkin] Error observing long tasks:",A)}}getMetrics(){return Object.assign({},this.metrics)}}class G{constructor(A,e){var t;this.config=A,this.transport=e,this.breadcrumbs=[],this.maxBreadcrumbs=(null===(t=A.errorOptions)||void 0===t?void 0:t.maxBreadcrumbs)||30}start(){window.addEventListener("error",A=>{this.handleError(A.error||A.message,{filename:A.filename,lineno:A.lineno,colno:A.colno})}),window.addEventListener("unhandledrejection",A=>{this.handleError(A.reason,{type:"unhandledrejection"})}),this.setupAutomaticBreadcrumbs()}captureError(A,e){this.handleError(A,e)}addBreadcrumb(A){const e={category:A.category,message:A.message,level:A.level||"info",timestamp:(new Date).toISOString(),data:A.data};this.breadcrumbs.push(e),this.breadcrumbs.length>this.maxBreadcrumbs&&this.breadcrumbs.shift(),this.config.debug&&console.log("[DevSkin] Breadcrumb added:",e)}handleError(A,e){var t;if(this.shouldIgnoreError(A))return;let r;if(A instanceof Error){if(r={message:A.message,stack:A.stack,type:A.name||"Error",timestamp:(new Date).toISOString(),sessionId:"",url:window.location.href,breadcrumbs:[...this.breadcrumbs],context:Object.assign(Object.assign({},e),{userAgent:navigator.userAgent,viewport:{width:window.innerWidth,height:window.innerHeight}})},A.stack){const e=A.stack.match(/:(\d+):(\d+)/);e&&(r.line=parseInt(e[1],10),r.column=parseInt(e[2],10))}}else r={message:String(A),type:"Error",timestamp:(new Date).toISOString(),sessionId:"",url:window.location.href,breadcrumbs:[...this.breadcrumbs],context:e};(null===(t=this.config.errorOptions)||void 0===t?void 0:t.includeLocalVariables)&&e&&(r.context=Object.assign(Object.assign({},r.context),{localVariables:e})),this.config.debug&&console.log("[DevSkin] Error captured:",r),this.addBreadcrumb({category:"error",message:r.message,level:"error",data:{type:r.type,stack:r.stack}}),this.transport.sendError(r)}shouldIgnoreError(A){var e,t;const r=(null===(e=this.config.errorOptions)||void 0===e?void 0:e.ignoreErrors)||[],n=A instanceof Error?A.message:String(A);for(const A of r)if(A instanceof RegExp){if(A.test(n))return!0}else if("string"==typeof A&&n.includes(A))return!0;const s=(null===(t=this.config.errorOptions)||void 0===t?void 0:t.denyUrls)||[],o=A instanceof Error?A.stack:"";for(const A of s)if(A.test(o||""))return!0;return!1}setupAutomaticBreadcrumbs(){this.wrapConsole(),document.addEventListener("click",A=>{var e;const t=A.target;this.addBreadcrumb({category:"ui.click",message:`Clicked on ${t.tagName}`,data:{tagName:t.tagName,id:t.id,className:t.className,innerText:null===(e=t.innerText)||void 0===e?void 0:e.substring(0,100)}})},!0);let A=window.location.href;const e=()=>{A!==window.location.href&&(this.addBreadcrumb({category:"navigation",message:`Navigated to ${window.location.pathname}`,data:{from:A,to:window.location.href}}),A=window.location.href)};window.addEventListener("popstate",e),window.addEventListener("hashchange",e);const t=history.pushState;history.pushState=function(...A){t.apply(this,A),e()};const r=history.replaceState;history.replaceState=function(...A){r.apply(this,A),e()}}wrapConsole(){["log","info","warn","error"].forEach(A=>{const e=console[A];console[A]=(...t)=>{if(e.apply(console,t),"warn"===A||"error"===A){const e=t.map(A=>String(A)).join(" ");if(e.startsWith("[DevSkin]"))return;this.addBreadcrumb({category:"console",message:e,level:"warn"===A?"warning":"error",data:{arguments:t}})}}})}getBreadcrumbs(){return[...this.breadcrumbs]}}class V{constructor(A,e){this.config=A,this.transport=e}start(){this.interceptFetch(),this.interceptXHR()}interceptFetch(){if(!window.fetch)return;const e=window.fetch;window.fetch=(...t)=>A(this,void 0,void 0,function*(){var A,r;const[n,s]=t,o="string"==typeof n?n:n instanceof Request?n.url:n.toString(),i=(null==s?void 0:s.method)||"GET",a=Date.now();try{const n=yield e(...t),s=n.clone(),c=Date.now()-a;if(this.shouldIgnoreUrl(o))return n;if((null===(A=this.config.networkRequestOptions)||void 0===A?void 0:A.captureFailedOnly)&&n.ok)return n;const B={url:o,method:i,statusCode:n.status,durationMs:c,responseSize:yield this.getResponseSize(s),timestamp:(new Date).toISOString()};return(null===(r=this.config.networkRequestOptions)||void 0===r?void 0:r.captureHeaders)&&(B.responseHeaders=this.headersToObject(n.headers)),n.ok||(B.errorMessage=`HTTP ${n.status} ${n.statusText}`),this.config.debug&&console.log("[DevSkin] Network request tracked:",B),this.transport.sendNetworkRequest(B),n}catch(A){const e=Date.now()-a;if(!this.shouldIgnoreUrl(o)){const t={url:o,method:i,durationMs:e,timestamp:(new Date).toISOString(),errorMessage:A instanceof Error?A.message:"Network request failed"};this.config.debug&&console.log("[DevSkin] Network request failed:",t),this.transport.sendNetworkRequest(t)}throw A}})}interceptXHR(){const A=XMLHttpRequest.prototype.open,e=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,r,n,s){return this.__devskin={method:e,url:t.toString(),startTime:Date.now()},void 0!==n?A.call(this,e,t,null==r||r,n,null!=s?s:void 0):void 0!==r?A.call(this,e,t,r):A.call(this,e,t,!0)},XMLHttpRequest.prototype.send=function(A){const t=this,r=t.__devskin;if(!r)return e.call(this,A);const n=window.__devskinNetworkCollector,s=()=>{const A=Date.now()-r.startTime;if(!(null==n?void 0:n.shouldIgnoreUrl(r.url))){const e={url:r.url,method:r.method,durationMs:A,timestamp:(new Date).toISOString(),errorMessage:"XHR request failed"};(null==n?void 0:n.config.debug)&&console.log("[DevSkin] XHR request failed:",e),null==n||n.transport.sendNetworkRequest(e)}};return t.addEventListener("load",()=>{var A,e;const s=Date.now()-r.startTime;if(null==n?void 0:n.shouldIgnoreUrl(r.url))return;if((null===(A=null==n?void 0:n.config.networkRequestOptions)||void 0===A?void 0:A.captureFailedOnly)&&t.status>=200&&t.status<400)return;const o={url:r.url,method:r.method,statusCode:t.status,durationMs:s,timestamp:(new Date).toISOString()};(null===(e=null==n?void 0:n.config.networkRequestOptions)||void 0===e?void 0:e.captureHeaders)&&(o.responseHeaders=n.parseResponseHeaders(t.getAllResponseHeaders())),(0===t.status||t.status>=400)&&(o.errorMessage=`HTTP ${t.status} ${t.statusText}`),(null==n?void 0:n.config.debug)&&console.log("[DevSkin] XHR request tracked:",o),null==n||n.transport.sendNetworkRequest(o)}),t.addEventListener("error",s),t.addEventListener("abort",s),e.call(this,A)},window.__devskinNetworkCollector=this}shouldIgnoreUrl(A){var e;if(A.includes(this.config.apiUrl||""))return!0;const t=(null===(e=this.config.networkRequestOptions)||void 0===e?void 0:e.ignoreUrls)||[];for(const e of t)if(e.test(A))return!0;return!1}getResponseSize(e){return A(this,void 0,void 0,function*(){try{return(yield e.blob()).size}catch(A){return}})}headersToObject(A){const e={};return A.forEach((A,t)=>{e[t]=A}),e}parseResponseHeaders(A){const e={};if(!A)return e;return A.trim().split(/[\r\n]+/).forEach(A=>{const t=A.split(": "),r=t.shift(),n=t.join(": ");r&&(e[r]=n)}),e}}class P{constructor(A,e,t,r){this.config=A,this.transport=e,this.anonymousId=t,this.sessionId=r,this.clickData=[],this.scrollData=[],this.mouseMoveData=[],this.maxScrollDepth=0,this.flushInterval=null,this.mouseMoveSampling=.1}start(){var A;(null===(A=this.config.heatmapOptions)||void 0===A?void 0:A.enabled)&&(this.config.debug&&console.log("[DevSkin] Starting heatmap collection"),!1!==this.config.heatmapOptions.trackClicks&&this.trackClicks(),!1!==this.config.heatmapOptions.trackScroll&&this.trackScrollDepth(),this.config.heatmapOptions.trackMouseMovement&&(this.mouseMoveSampling=this.config.heatmapOptions.mouseMoveSampling||.1,this.trackMouseMovement()),this.flushInterval=setInterval(()=>{this.flush()},1e4),window.addEventListener("beforeunload",()=>{this.flush()}))}stop(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}trackClicks(){document.addEventListener("click",A=>{const e=A.target,t=e.getBoundingClientRect(),r=A.clientX-t.left,n=A.clientY-t.top,s=A.clientX+window.scrollX,o=A.clientY+window.scrollY,i={x:A.clientX,y:A.clientY,relativeX:r,relativeY:n,pageX:s,pageY:o,element:this.getElementSelector(e),elementId:e.id||void 0,elementClass:e.className||void 0,pageUrl:window.location.href,timestamp:(new Date).toISOString(),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight};this.clickData.push(i),this.config.debug&&console.log("[DevSkin] Click tracked:",i),this.clickData.length>=50&&this.flush()},!0)}trackScrollDepth(){const A=()=>{const A=window.innerHeight,e=document.documentElement.scrollHeight,t=window.scrollY||document.documentElement.scrollTop,r=Math.round((t+A)/e*100);if(r>this.maxScrollDepth){this.maxScrollDepth=r;const t={depth:r,maxDepth:this.maxScrollDepth,pageHeight:e,viewportHeight:A,pageUrl:window.location.href,timestamp:(new Date).toISOString()};this.scrollData.push(t),this.config.debug&&console.log("[DevSkin] Scroll depth:",r+"%")}};let e=null;window.addEventListener("scroll",()=>{e&&clearTimeout(e),e=setTimeout(A,100)}),A()}trackMouseMovement(){let A=null;window.addEventListener("mousemove",e=>{if(Math.random()>this.mouseMoveSampling)return;if(A)return;A=setTimeout(()=>{A=null},100);const t={x:e.clientX+window.scrollX,y:e.clientY+window.scrollY,pageUrl:window.location.href,timestamp:(new Date).toISOString()};this.mouseMoveData.push(t),this.mouseMoveData.length>=100&&this.flush()})}flush(){this.clickData.length>0&&(this.clickData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"click",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.clickData=[]),this.scrollData.length>0&&(this.scrollData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"scroll",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.scrollData=[]),this.mouseMoveData.length>0&&(this.mouseMoveData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"mousemove",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.mouseMoveData=[])}getElementSelector(A){if(A.id)return`#${A.id}`;if(A.className){const e=A.className.split(" ").filter(A=>A);if(e.length>0)return`${A.tagName.toLowerCase()}.${e.join(".")}`}return A.tagName.toLowerCase()}}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function X(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var J={exports:{}};
|
|
2
2
|
/*!
|
|
3
3
|
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
|
|
4
4
|
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
|
|
@@ -47,5 +47,5 @@ var A=function(e,t){return A=Object.setPrototypeOf||{__proto__:[]}instanceof Arr
|
|
|
47
47
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
48
48
|
PERFORMANCE OF THIS SOFTWARE.
|
|
49
49
|
***************************************************************************** */
|
|
50
|
-
function A(A,e,t,r){return new(t||(t=Promise))(function(e,n){function s(A){try{i(r.next(A))}catch(A){n(A)}}function o(A){try{i(r.throw(A))}catch(A){n(A)}}function i(A){var r;A.done?e(A.value):(r=A.value,r instanceof t?r:new t(function(A){A(r)})).then(s,o)}i((r=r.apply(A,[])).next())})}for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="undefined"==typeof Uint8Array?[]:new Uint8Array(256),r=0;r<64;r++)t[e.charCodeAt(r)]=r;var n=function(A){var t,r=new Uint8Array(A),n=r.length,s="";for(t=0;t<n;t+=3)s+=e[r[t]>>2],s+=e[(3&r[t])<<4|r[t+1]>>4],s+=e[(15&r[t+1])<<2|r[t+2]>>6],s+=e[63&r[t+2]];return n%3==2?s=s.substring(0,s.length-1)+"=":n%3==1&&(s=s.substring(0,s.length-2)+"=="),s};const s=new Map,o=new Map,i=self;i.onmessage=function(e){return A(this,0,void 0,function*(){if(!("OffscreenCanvas"in globalThis))return i.postMessage({id:e.data.id});{const{id:t,bitmap:r,width:a,height:c,dataURLOptions:B}=e.data,l=function(e,t,r){return A(this,0,void 0,function*(){const A=`${e}-${t}`;if("OffscreenCanvas"in globalThis){if(o.has(A))return o.get(A);const s=new OffscreenCanvas(e,t);s.getContext("2d");const i=yield s.convertToBlob(r),a=yield i.arrayBuffer(),c=n(a);return o.set(A,c),c}return""})}(a,c,B),u=new OffscreenCanvas(a,c);u.getContext("2d").drawImage(r,0,0),r.close();const g=yield u.convertToBlob(B),d=g.type,h=yield g.arrayBuffer(),w=n(h);if(!s.has(t)&&(yield l)===w)return s.set(t,w),i.postMessage({id:t});if(s.get(t)===w)return i.postMessage({id:t});i.postMessage({id:t,type:d,base64:w,width:a,height:c}),s.set(t,w)}})}}()},function(A){return Ge=Ge||function(A){var e=function(A){var e=A.toString().split("\n");e.pop(),e.shift();for(var t=e[0].search(/\S/),r=/(['"])__worker_loader_strict__(['"])/g,n=0,s=e.length;n<s;++n)e[n]=e[n].substring(t).replace(r,"$1use strict$2")+"\n";return e}(A),t=new Blob(e,{type:"application/javascript"});return URL.createObjectURL(t)}(Ne),new Worker(Ge,A)});class Pe{reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}constructor(A){this.pendingCanvasMutations=new Map,this.rafStamps={latestId:0,invokeId:null},this.frozen=!1,this.locked=!1,this.processMutation=(A,e)=>{!(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId)&&this.rafStamps.invokeId||(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(A)||this.pendingCanvasMutations.set(A,[]),this.pendingCanvasMutations.get(A).push(e)};const{sampling:e="all",win:t,blockClass:r,blockSelector:n,recordCanvas:s,dataURLOptions:o}=A;this.mutationCb=A.mutationCb,this.mirror=A.mirror,s&&"all"===e&&this.initCanvasMutationObserver(t,r,n),s&&"number"==typeof e&&this.initCanvasFPSObserver(e,t,r,n,{dataURLOptions:o})}initCanvasFPSObserver(A,e,t,r,n){const s=xe(e,t,r,!0),o=new Map,i=new Ve;i.onmessage=A=>{const{id:e}=A.data;if(o.set(e,!1),!("base64"in A.data))return;const{base64:t,type:r,width:n,height:s}=A.data;this.mutationCb({id:e,type:$A["2D"],commands:[{property:"clearRect",args:[0,0,n,s]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:t}],type:r}]},0,0]}]})};const a=1e3/A;let c,B=0;const l=A=>{B&&A-B<a||(B=A,(()=>{const A=[];return e.document.querySelectorAll("canvas").forEach(e=>{xA(e,t,r,!0)||A.push(e)}),A})().forEach(A=>be(this,0,void 0,function*(){var e;const t=this.mirror.getId(A);if(o.get(t))return;if(0===A.width||0===A.height)return;if(o.set(t,!0),["webgl","webgl2"].includes(A.__context)){const t=A.getContext(A.__context);!1===(null===(e=null==t?void 0:t.getContextAttributes())||void 0===e?void 0:e.preserveDrawingBuffer)&&t.clear(t.COLOR_BUFFER_BIT)}const r=yield createImageBitmap(A);i.postMessage({id:t,bitmap:r,width:A.width,height:A.height,dataURLOptions:n.dataURLOptions},[r])}))),c=requestAnimationFrame(l)};c=requestAnimationFrame(l),this.resetObservers=()=>{s(),cancelAnimationFrame(c)}}initCanvasMutationObserver(A,e,t){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=xe(A,e,t,!1),n=function(A,e,t,r){const n=[],s=Object.getOwnPropertyNames(e.CanvasRenderingContext2D.prototype);for(const o of s)try{if("function"!=typeof e.CanvasRenderingContext2D.prototype[o])continue;const s=KA(e.CanvasRenderingContext2D.prototype,o,function(n){return function(...s){return xA(this.canvas,t,r,!0)||setTimeout(()=>{const t=Te(s,e,this);A(this.canvas,{type:$A["2D"],property:o,args:t})},0),n.apply(this,s)}});n.push(s)}catch(t){const r=LA(e.CanvasRenderingContext2D.prototype,o,{set(e){A(this.canvas,{type:$A["2D"],property:o,args:[e],setter:!0})}});n.push(r)}return()=>{n.forEach(A=>A())}}(this.processMutation.bind(this),A,e,t),s=function(A,e,t,r){const n=[];return n.push(...Re(e.WebGLRenderingContext.prototype,$A.WebGL,A,t,r,0,e)),void 0!==e.WebGL2RenderingContext&&n.push(...Re(e.WebGL2RenderingContext.prototype,$A.WebGL2,A,t,r,0,e)),()=>{n.forEach(A=>A())}}(this.processMutation.bind(this),A,e,t,this.mirror);this.resetObservers=()=>{r(),n(),s()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const A=e=>{this.rafStamps.latestId=e,requestAnimationFrame(A)};requestAnimationFrame(A)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((A,e)=>{const t=this.mirror.getId(e);this.flushPendingCanvasMutationFor(e,t)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(A,e){if(this.frozen||this.locked)return;const t=this.pendingCanvasMutations.get(A);if(!t||-1===e)return;const r=t.map(A=>{const e=function(A,e){var t={};for(var r in A)Object.prototype.hasOwnProperty.call(A,r)&&e.indexOf(r)<0&&(t[r]=A[r]);if(null!=A&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(A);n<r.length;n++)e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(A,r[n])&&(t[r[n]]=A[r[n]])}return t}(A,["type"]);return e}),{type:n}=t[0];this.mutationCb({id:e,type:n,commands:r}),this.pendingCanvasMutations.delete(A)}}class Xe{constructor(A){this.trackedLinkElements=new WeakSet,this.styleMirror=new JA,this.mutationCb=A.mutationCb,this.adoptedStyleSheetCb=A.adoptedStyleSheetCb}attachLinkElement(A,e){"_cssText"in e.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:e.id,attributes:e.attributes}]}),this.trackLinkElement(A)}trackLinkElement(A){this.trackedLinkElements.has(A)||(this.trackedLinkElements.add(A),this.trackStylesheetInLinkElement(A))}adoptStyleSheets(A,e){if(0===A.length)return;const t={id:e,styleIds:[]},r=[];for(const e of A){let A;this.styleMirror.has(e)?A=this.styleMirror.getId(e):(A=this.styleMirror.add(e),r.push({styleId:A,rules:Array.from(e.rules||CSSRule,(A,e)=>({rule:z(A),index:e}))})),t.styleIds.push(A)}r.length>0&&(t.styles=r),this.adoptedStyleSheetCb(t)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(A){}}class Je{constructor(){this.nodeMap=new WeakMap,this.loop=!0,this.periodicallyClear()}periodicallyClear(){requestAnimationFrame(()=>{this.clear(),this.loop&&this.periodicallyClear()})}inOtherBuffer(A,e){const t=this.nodeMap.get(A);return t&&Array.from(t).some(A=>A!==e)}add(A,e){this.nodeMap.set(A,(this.nodeMap.get(A)||new Set).add(e))}clear(){this.nodeMap=new WeakMap}destroy(){this.loop=!1}}function We(A){return Object.assign(Object.assign({},A),{timestamp:DA()})}let Ye,_e,Ze,je=!1;const qe=new $;function ze(A={}){const{emit:e,checkoutEveryNms:t,checkoutEveryNth:r,blockClass:n="rr-block",blockSelector:s=null,ignoreClass:o="rr-ignore",ignoreSelector:i=null,maskTextClass:a="rr-mask",maskTextSelector:c=null,inlineStylesheet:B=!0,maskAllInputs:l,maskInputOptions:u,slimDOMOptions:g,maskInputFn:d,maskTextFn:h,hooks:w,packFn:Q,sampling:p={},dataURLOptions:C={},mousemoveWait:f,recordDOM:U=!0,recordCanvas:F=!1,recordCrossOriginIframes:m=!1,recordAfter:y=("DOMContentLoaded"===A.recordAfter?A.recordAfter:"load"),userTriggeredOnInput:I=!1,collectFonts:E=!1,inlineImages:H=!1,plugins:v,keepIframeSrcFn:b=()=>!1,ignoreCSSAttributes:S=new Set([]),errorHandler:L}=A;Be(L);const K=!m||window.parent===window;let D=!1;if(!K)try{window.parent.document&&(D=!1)}catch(A){D=!0}if(K&&!e)throw new Error("emit function is required");void 0!==f&&void 0===p.mousemove&&(p.mousemove=f),qe.reset();const M=!0===l?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==u?u:{password:!0},k=!0===g||"all"===g?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===g,headMetaDescKeywords:"all"===g}:g||{};let T;!function(A=window){"NodeList"in A&&!A.NodeList.prototype.forEach&&(A.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in A&&!A.DOMTokenList.prototype.forEach&&(A.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...A)=>{let e=A[0];if(!(0 in A))throw new TypeError("1 argument is required");do{if(this===e)return!0}while(e=e&&e.parentNode);return!1})}();let O=0;const x=A=>{for(const e of v||[])e.eventProcessor&&(A=e.eventProcessor(A));return Q&&!D&&(A=Q(A)),A};Ye=(A,n)=>{var s;if(!(null===(s=ge[0])||void 0===s?void 0:s.isFrozen())||A.type===ZA.FullSnapshot||A.type===ZA.IncrementalSnapshot&&A.data.source===jA.Mutation||ge.forEach(A=>A.unfreeze()),K)null==e||e(x(A),n);else if(D){const e={type:"rrweb",event:x(A),origin:window.location.origin,isCheckout:n};window.parent.postMessage(e,"*")}if(A.type===ZA.FullSnapshot)T=A,O=0;else if(A.type===ZA.IncrementalSnapshot){if(A.data.source===jA.Mutation&&A.data.isAttachIframe)return;O++;const e=r&&O>=r,n=t&&A.timestamp-T.timestamp>t;(e||n)&&_e(!0)}};const R=A=>{Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Mutation},A)}))},N=A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Scroll},A)})),G=A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.CanvasMutation},A)})),V=new Xe({mutationCb:R,adoptedStyleSheetCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.AdoptedStyleSheet},A)}))}),P=new He({mirror:qe,mutationCb:R,stylesheetManager:V,recordCrossOriginIframes:m,wrappedEmit:Ye});for(const A of v||[])A.getMirror&&A.getMirror({nodeMirror:qe,crossOriginIframeMirror:P.crossOriginIframeMirror,crossOriginIframeStyleMirror:P.crossOriginIframeStyleMirror});const X=new Je;Ze=new Pe({recordCanvas:F,mutationCb:G,win:window,blockClass:n,blockSelector:s,mirror:qe,sampling:p.canvas,dataURLOptions:C});const J=new ve({mutationCb:R,scrollCb:N,bypassOptions:{blockClass:n,blockSelector:s,maskTextClass:a,maskTextSelector:c,inlineStylesheet:B,maskInputOptions:M,dataURLOptions:C,maskTextFn:h,maskInputFn:d,recordCanvas:F,inlineImages:H,sampling:p,slimDOMOptions:k,iframeManager:P,stylesheetManager:V,canvasManager:Ze,keepIframeSrcFn:b,processedNodeManager:X},mirror:qe});_e=(A=!1)=>{if(!U)return;Ye(We({type:ZA.Meta,data:{href:window.location.href,width:TA(),height:kA()}}),A),V.reset(),J.init(),ge.forEach(A=>A.lock());const e=function(A,e){const{mirror:t=new $,blockClass:r="rr-block",blockSelector:n=null,maskTextClass:s="rr-mask",maskTextSelector:o=null,inlineStylesheet:i=!0,inlineImages:a=!1,recordCanvas:c=!1,maskAllInputs:B=!1,maskTextFn:l,maskInputFn:u,slimDOM:g=!1,dataURLOptions:d,preserveWhiteSpace:h,onSerialize:w,onIframeLoad:Q,iframeLoadTimeout:p,onStylesheetLoad:C,stylesheetLoadTimeout:f,keepIframeSrcFn:U=()=>!1}=e||{};return EA(A,{doc:A,mirror:t,blockClass:r,blockSelector:n,maskTextClass:s,maskTextSelector:o,skipChild:!1,inlineStylesheet:i,maskInputOptions:!0===B?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===B?{password:!0}:B,maskTextFn:l,maskInputFn:u,slimDOMOptions:!0===g||"all"===g?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===g,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===g?{}:g,dataURLOptions:d,inlineImages:a,recordCanvas:c,preserveWhiteSpace:h,onSerialize:w,onIframeLoad:Q,iframeLoadTimeout:p,onStylesheetLoad:C,stylesheetLoadTimeout:f,keepIframeSrcFn:U,newlyAddedElement:!1})}(document,{mirror:qe,blockClass:n,blockSelector:s,maskTextClass:a,maskTextSelector:c,inlineStylesheet:B,maskAllInputs:M,maskTextFn:h,slimDOM:k,dataURLOptions:C,recordCanvas:F,inlineImages:H,onSerialize:A=>{VA(A,qe)&&P.addIframe(A),PA(A,qe)&&V.trackLinkElement(A),XA(A)&&J.addShadowRoot(A.shadowRoot,document)},onIframeLoad:(A,e)=>{P.attachIframe(A,e),J.observeAttachShadow(A)},onStylesheetLoad:(A,e)=>{V.attachLinkElement(A,e)},keepIframeSrcFn:b});if(!e)return console.warn("Failed to snapshot the document");Ye(We({type:ZA.FullSnapshot,data:{node:e,initialOffset:MA(window)}}),A),ge.forEach(A=>A.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&V.adoptStyleSheets(document.adoptedStyleSheets,qe.getId(document))};try{const A=[],e=A=>{var e;return ue(me)({mutationCb:R,mousemoveCb:(A,e)=>Ye(We({type:ZA.IncrementalSnapshot,data:{source:e,positions:A}})),mouseInteractionCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.MouseInteraction},A)})),scrollCb:N,viewportResizeCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.ViewportResize},A)})),inputCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Input},A)})),mediaInteractionCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.MediaInteraction},A)})),styleSheetRuleCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.StyleSheetRule},A)})),styleDeclarationCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.StyleDeclaration},A)})),canvasMutationCb:G,fontCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Font},A)})),selectionCb:A=>{Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Selection},A)}))},customElementCb:A=>{Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.CustomElement},A)}))},blockClass:n,ignoreClass:o,ignoreSelector:i,maskTextClass:a,maskTextSelector:c,maskInputOptions:M,inlineStylesheet:B,sampling:p,recordDOM:U,recordCanvas:F,inlineImages:H,userTriggeredOnInput:I,collectFonts:E,doc:A,maskInputFn:d,maskTextFn:h,keepIframeSrcFn:b,blockSelector:s,slimDOMOptions:k,dataURLOptions:C,mirror:qe,iframeManager:P,stylesheetManager:V,shadowDomManager:J,processedNodeManager:X,canvasManager:Ze,ignoreCSSAttributes:S,plugins:(null===(e=null==v?void 0:v.filter(A=>A.observer))||void 0===e?void 0:e.map(A=>({observer:A.observer,options:A.options,callback:e=>Ye(We({type:ZA.Plugin,data:{plugin:A.name,payload:e}}))})))||[]},w)};P.addLoadListener(t=>{try{A.push(e(t.contentDocument))}catch(A){console.warn(A)}});const t=()=>{_e(),A.push(e(document)),je=!0};return"interactive"===document.readyState||"complete"===document.readyState?t():(A.push(HA("DOMContentLoaded",()=>{Ye(We({type:ZA.DomContentLoaded,data:{}})),"DOMContentLoaded"===y&&t()})),A.push(HA("load",()=>{Ye(We({type:ZA.Load,data:{}})),"load"===y&&t()},window))),()=>{A.forEach(A=>A()),X.destroy(),je=!1,le()}}catch(A){console.warn(A)}}ze.addCustomEvent=(A,e)=>{if(!je)throw new Error("please add custom event after start recording");Ye(We({type:ZA.Custom,data:{tag:A,payload:e}}))},ze.freezePage=()=>{ge.forEach(A=>A.freeze())},ze.takeFullSnapshot=A=>{if(!je)throw new Error("please take full snapshot after start recording");_e(A)},ze.mirror=qe;class $e{constructor(A,e,t,r=0){this.stopFn=null,this.events=[],this.onEventsReady=null,this.flushInterval=null,this.hasFullSnapshot=!1,this.sessionStartTime=0,this.recordingStartTime=0,this.sessionId=A,this.config=e,this.onEventsReady=t,this.sessionStartTime=r||Date.now(),this.recordingStartTime=Date.now(),console.log(`[RRWeb] Recording initialized - session started at ${this.sessionStartTime}, recording started at ${this.recordingStartTime}`)}start(){if(this.config.enabled)if(this.stopFn)console.warn("[RRWeb] Recording already started");else try{this.stopFn=ze({emit:A=>{const e=A.timestamp;A.timestamp=A.timestamp-this.sessionStartTime,this.config.enabled&&2===A.type&&console.log(`[RRWeb] FullSnapshot - original: ${e}, relative: ${A.timestamp}, session start: ${this.sessionStartTime}`),this.events.push(A),2===A.type?(this.hasFullSnapshot=!0,this.flush()):this.hasFullSnapshot&&this.events.length>=20&&this.flush()},sampling:{mousemove:void 0===this.config.sampleRate||Math.floor(100/this.config.sampleRate),mouseInteraction:!0,scroll:150,media:800,input:"last"},checkoutEveryNms:this.config.checkoutEveryNms||3e5,checkoutEveryNth:this.config.checkoutEveryNth||200,blockClass:this.config.blockClass||"rr-block",ignoreClass:this.config.ignoreClass||"rr-ignore",maskAllInputs:void 0===this.config.maskAllInputs||this.config.maskAllInputs,maskInputOptions:this.config.maskInputOptions||{password:!0,email:!0,tel:!0},maskTextClass:"rr-mask",inlineStylesheet:void 0===this.config.inlineStylesheet||this.config.inlineStylesheet,recordCanvas:this.config.recordCanvas||!1,collectFonts:void 0===this.config.collectFonts||this.config.collectFonts,recordCrossOriginIframes:!1}),this.flushInterval=window.setInterval(()=>{this.hasFullSnapshot&&this.events.length>0&&this.flush()},2e3),setTimeout(()=>{if(!this.hasFullSnapshot)try{ze.takeFullSnapshot()}catch(A){this.events.length>0&&(this.hasFullSnapshot=!0,this.flush())}},2e3)}catch(A){console.error("[RRWeb] Failed to start recording:",A)}else console.log("[RRWeb] Recording disabled in config")}stop(){this.stopFn&&(this.stopFn(),this.stopFn=null),this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.events.length>0&&this.flush()}flush(){if(0===this.events.length)return;const A=[...this.events];this.events=[],this.onEventsReady&&this.onEventsReady(A)}getEventCount(){return this.events.length}isRecording(){return null!==this.stopFn}}class At{constructor(A){this.config=A,this.queue=[],this.flushInterval=null,this.maxQueueSize=20,this.flushIntervalMs=2e3,this.sessionId=null,this.apiUrl=A.apiUrl||"https://api.devskin.com",this.startPeriodicFlush(),"undefined"!=typeof window&&(window.addEventListener("beforeunload",()=>{this.flush()}),window.addEventListener("visibilitychange",()=>{document.hidden&&this.flush(!0)}))}setSessionId(A){this.sessionId=A}sendEvent(A){this.enqueue("event",A)}identifyUser(A){this.sendToBackend("/v1/analytics/identify",A)}startSession(e){return A(this,arguments,void 0,function*(A,e=!1){yield this.sendToBackend("/v1/rum/sessions",A,e)})}sendError(A){this.enqueue("error",A)}sendNetworkRequest(A){this.enqueue("network",A)}sendPerformanceMetric(A){this.enqueue("performance",A)}sendPageView(e){return A(this,void 0,void 0,function*(){this.sendToBackend("/v1/rum/page-views",e)})}sendRecordingEvents(e,t){return A(this,void 0,void 0,function*(){const A={session_id:e,events:t,timestamp:(new Date).toISOString(),apiKey:this.config.apiKey,appId:this.config.appId},r=new Blob([JSON.stringify(A)]).size,n=t.some(A=>2===A.type),s=n?3:1;let o=null;for(let A=1;A<=s;A++)try{return void(r>1e5?yield this.sendToBackendXHR("/v1/rum/recordings",{session_id:e,events:t,timestamp:(new Date).toISOString()}):yield this.sendToBackend("/v1/rum/recordings",{session_id:e,events:t,timestamp:(new Date).toISOString()}))}catch(e){if(o=e,A<s){const e=1e3*A;yield new Promise(A=>setTimeout(A,e))}}this.config.debug&&console.error(`[DevSkin SDK] Failed to send recording events after ${s} attempts:`,o)})}sendHeatmapData(A){this.enqueue("heatmap",A)}sendScreenshot(e){return A(this,void 0,void 0,function*(){yield this.sendToBackend("/v1/sdk/screenshot",{screenshot:e})})}flush(A=!1){if(0===this.queue.length)return;const e=[...this.queue];this.queue=[];const t={};e.forEach(A=>{t[A.type]||(t[A.type]=[]),t[A.type].push(A.data)}),Object.entries(t).forEach(([e,t])=>{const r=this.getEndpointForType(e);"event"===e&&t.length>1?this.sendToBackend("/v1/rum/events/batch",{events:t},A):"heatmap"===e?this.sendToBackend(r,{heatmaps:t,apiKey:this.config.apiKey,appId:this.config.appId},A):t.forEach(e=>{this.sendToBackend(r,e,A)})}),this.config.debug&&console.log(`[DevSkin] Flushed ${e.length} items to backend`)}enqueue(A,e){let t=e;"heatmap"!==A&&(t=Object.assign(Object.assign({},e),{applicationId:this.config.appId}),"network"!==A&&"performance"!==A||!this.sessionId||(t.sessionId=this.sessionId)),this.queue.push({type:A,data:t,timestamp:Date.now()}),this.queue.length>=this.maxQueueSize&&this.flush()}startPeriodicFlush(){this.flushInterval=setInterval(()=>{this.flush()},this.flushIntervalMs)}getEndpointForType(A){switch(A){case"event":default:return"/v1/rum/events";case"error":return"/v1/errors/errors";case"network":return"/v1/rum/network-requests";case"performance":return"/v1/rum/web-vitals";case"heatmap":return"/v1/sdk/heatmap"}}sendToBackendXHR(e,t){return A(this,void 0,void 0,function*(){const A=`${this.apiUrl}${e}`,r=Object.assign(Object.assign({},t),{apiKey:this.config.apiKey,applicationId:this.config.appId,environment:this.config.environment,release:this.config.release});if(this.config.beforeSend){if(!this.config.beforeSend(r))return}return new Promise((t,n)=>{const s=new XMLHttpRequest;s.open("POST",A,!0),s.setRequestHeader("Content-Type","application/json"),s.setRequestHeader("Authorization",`Bearer ${this.config.apiKey}`),s.onload=()=>{s.status>=200&&s.status<300?(this.config.debug&&console.log("[DevSkin] Data sent successfully via XHR:",e),t()):(console.error("[DevSkin] XHR HTTP Error:",s.status,s.responseText),n(new Error(`HTTP ${s.status}: ${s.statusText}`)))},s.onerror=()=>{console.error("[DevSkin] XHR network error:",e),n(new Error("Network error"))},s.ontimeout=()=>{console.error("[DevSkin] XHR timeout:",e),n(new Error("Request timeout"))},s.timeout=3e4;try{const A=JSON.stringify(r);s.send(A)}catch(A){console.error("[DevSkin] Failed to send XHR request:",A),n(A)}})})}sendToBackend(e,t){return A(this,arguments,void 0,function*(A,e,t=!1){const r=`${this.apiUrl}${A}`,n=Object.assign(Object.assign({},e),{apiKey:this.config.apiKey,applicationId:this.config.appId,environment:this.config.environment,release:this.config.release});if(this.config.beforeSend){if(!this.config.beforeSend(n))return}if(t&&navigator.sendBeacon){const A=new Blob([JSON.stringify(n)],{type:"application/json"});return void navigator.sendBeacon(r,A)}try{const e=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(n),keepalive:!0});if(!e.ok){const A=yield e.text();throw console.error("[DevSkin] HTTP Error:",e.status,A),new Error(`HTTP ${e.status}: ${e.statusText}`)}this.config.debug&&console.log("[DevSkin] Data sent successfully:",A)}catch(e){throw console.error("[DevSkin] Failed to send data to",A,":",e),e}})}destroy(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}}return new class{constructor(){this.config=null,this.transport=null,this.sessionId=null,this.userId=null,this.anonymousId=null,this.sessionStartTime=0,this.initialized=!1,this.heartbeatInterval=null,this.deviceCollector=null,this.locationCollector=null,this.browserCollector=null,this.performanceCollector=null,this.errorCollector=null,this.networkCollector=null,this.heatmapCollector=null,this.screenshotCollector=null,this.rrwebRecorder=null}init(A){this.initialized?console.warn("[DevSkin] SDK already initialized"):(this.config=Object.assign({debug:!1,captureWebVitals:!0,captureNetworkRequests:!0,captureErrors:!0,captureUserAgent:!0,captureLocation:!0,captureDevice:!0,heatmapOptions:{enabled:!0,trackClicks:!0,trackScroll:!0,trackMouseMovement:!1}},A),this.config.debug&&console.log("[DevSkin] Initializing SDK with config:",this.config),this.transport=new At(this.config),this.anonymousId=this.getOrCreateAnonymousId(),this.deviceCollector=new e(this.config),this.locationCollector=new t(this.config),this.browserCollector=new r(this.config),this.startSession().then(()=>{var A,e;this.config.captureWebVitals&&(this.performanceCollector=new N(this.config,this.transport),this.performanceCollector.start()),this.config.captureErrors&&(this.errorCollector=new G(this.config,this.transport),this.errorCollector.start()),this.config.captureNetworkRequests&&(this.networkCollector=new V(this.config,this.transport),this.networkCollector.start());const t=Object.assign({enabled:!0,trackClicks:!0,trackScroll:!0,trackMouseMovement:!0,mouseMoveSampling:.1},this.config.heatmapOptions);this.config.heatmapOptions=t,this.heatmapCollector=new P(this.config,this.transport),this.heatmapCollector.start(),this.screenshotCollector=new _(this.config,this.transport),this.screenshotCollector.captureAndSend(this.sessionId,window.location.href),this.config.debug&&console.log("[DevSkin] Heatmap collection enabled (always on)"),(null===(A=this.config.sessionRecording)||void 0===A?void 0:A.enabled)&&(this.rrwebRecorder=new $e(this.sessionId,{enabled:!0,sampleRate:this.config.sessionRecording.sampling||.5,blockClass:"rr-block",ignoreClass:this.config.sessionRecording.ignoreClass||"rr-ignore",maskAllInputs:void 0===this.config.sessionRecording.maskAllInputs||this.config.sessionRecording.maskAllInputs,maskInputOptions:{password:!0,email:!0,tel:!0},recordCanvas:this.config.sessionRecording.recordCanvas||!1,collectFonts:!0,inlineStylesheet:!0,checkoutEveryNms:3e5,checkoutEveryNth:200},A=>{var e;null===(e=this.transport)||void 0===e||e.sendRecordingEvents(this.sessionId,A)},this.sessionStartTime),this.rrwebRecorder.start(),(null===(e=this.config)||void 0===e?void 0:e.debug)&&console.log("[DevSkin] RRWeb recording started for session:",this.sessionId)),this.trackPageView(),this.startHeartbeat()}).catch(A=>{console.error("[DevSkin] Failed to create session:",A)}),this.setupVisibilityTracking(),this.setupUnloadTracking(),this.initialized=!0,this.config.debug&&console.log("[DevSkin] SDK initialized successfully"))}track(A,e){var t,r;if(!this.initialized)return void console.warn("[DevSkin] SDK not initialized. Call init() first.");const n={eventName:A,eventType:"track",timestamp:(new Date).toISOString(),sessionId:this.sessionId,userId:this.userId||void 0,anonymousId:this.anonymousId||void 0,properties:Object.assign(Object.assign({},e),this.getContextData()),pageUrl:window.location.href,pageTitle:document.title};null===(t=this.transport)||void 0===t||t.sendEvent(n),(null===(r=this.config)||void 0===r?void 0:r.debug)&&console.log("[DevSkin] Event tracked:",n)}trackPageView(A){var e,t;if(!this.initialized)return void console.warn("[DevSkin] SDK not initialized. Call init() first.");const r=this.generateId();null===(e=this.transport)||void 0===e||e.sendPageView(Object.assign({sessionId:this.sessionId,pageViewId:r,url:window.location.href,path:window.location.pathname,queryParams:window.location.search,referrer:document.referrer,title:document.title,timestamp:(new Date).toISOString()},A)),this.track("page_view",Object.assign({path:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer},A)),(null===(t=this.config)||void 0===t?void 0:t.debug)&&console.log("[DevSkin] Page view tracked:",{sessionId:this.sessionId,pageViewId:r,url:window.location.href})}identify(A,e){var t,r;if(!this.initialized)return void console.warn("[DevSkin] SDK not initialized. Call init() first.");this.userId=A;const n={userId:A,anonymousId:this.anonymousId||void 0,traits:Object.assign(Object.assign({},e),this.getContextData()),sessionId:this.sessionId,timestamp:(new Date).toISOString()};null===(t=this.transport)||void 0===t||t.identifyUser(n),(null===(r=this.config)||void 0===r?void 0:r.debug)&&console.log("[DevSkin] User identified:",n)}captureError(A,e){var t;this.initialized?null===(t=this.errorCollector)||void 0===t||t.captureError(A,Object.assign(Object.assign({},e),{session_id:this.sessionId,user_id:this.userId||void 0})):console.warn("[DevSkin] SDK not initialized. Call init() first.")}addBreadcrumb(A){var e;this.initialized&&(null===(e=this.errorCollector)||void 0===e||e.addBreadcrumb(A))}startRecording(){var A;null===(A=this.rrwebRecorder)||void 0===A||A.start()}stopRecording(){var A;null===(A=this.rrwebRecorder)||void 0===A||A.stop()}optOut(){localStorage.setItem("devskin_opt_out","true"),this.initialized=!1}optIn(){localStorage.removeItem("devskin_opt_out")}startSession(){return A(this,void 0,void 0,function*(){var A,e,t,r,n;const s=sessionStorage.getItem("devskin_session_id"),o=sessionStorage.getItem("devskin_session_start");if(s&&o)return this.sessionId=s,this.sessionStartTime=parseInt(o,10),null===(A=this.transport)||void 0===A||A.setSessionId(this.sessionId),void((null===(e=this.config)||void 0===e?void 0:e.debug)&&console.log("[DevSkin] Resuming existing session:",this.sessionId));this.sessionId=this.generateId(),this.sessionStartTime=Date.now(),sessionStorage.setItem("devskin_session_id",this.sessionId),sessionStorage.setItem("devskin_session_start",this.sessionStartTime.toString()),null===(t=this.transport)||void 0===t||t.setSessionId(this.sessionId);const i=Object.assign({sessionId:this.sessionId,userId:this.userId||void 0,anonymousId:this.anonymousId,startedAt:(new Date).toISOString(),platform:"web"},this.getContextData());yield null===(r=this.transport)||void 0===r?void 0:r.startSession(i),(null===(n=this.config)||void 0===n?void 0:n.debug)&&console.log("[DevSkin] New session created:",this.sessionId)})}getContextData(){var A,e,t,r;const n={};if(this.deviceCollector){const s=this.deviceCollector.collect();n.deviceType=s.type,n.deviceModel=s.model,n.osName=null===(A=s.os)||void 0===A?void 0:A.name,n.osVersion=null===(e=s.os)||void 0===e?void 0:e.version,n.screenWidth=null===(t=s.screen)||void 0===t?void 0:t.width,n.screenHeight=null===(r=s.screen)||void 0===r?void 0:r.height,n.viewportWidth=window.innerWidth,n.viewportHeight=window.innerHeight}if(this.browserCollector){const A=this.browserCollector.collect();n.browserName=A.name,n.browserVersion=A.version,n.userAgent=A.userAgent}if(this.locationCollector){const A=this.locationCollector.collect();n.country=A.country,n.city=A.city,n.ipAddress=void 0}return n}getOrCreateAnonymousId(){let A=localStorage.getItem("devskin_anonymous_id");return A||(A=this.generateId(),localStorage.setItem("devskin_anonymous_id",A)),A}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}setupVisibilityTracking(){document.addEventListener("visibilitychange",()=>{document.hidden?this.track("page_hidden"):this.track("page_visible")})}setupUnloadTracking(){document.addEventListener("visibilitychange",()=>{var A,e;document.hidden&&(this.updateSessionDuration(),null===(A=this.rrwebRecorder)||void 0===A||A.stop(),null===(e=this.transport)||void 0===e||e.flush(!0))}),window.addEventListener("pagehide",()=>{var A,e;this.track("page_navigation"),this.updateSessionDuration(!1),null===(A=this.rrwebRecorder)||void 0===A||A.stop(),null===(e=this.transport)||void 0===e||e.flush(!0)}),window.addEventListener("beforeunload",()=>{var A,e;this.updateSessionDuration(!1),null===(A=this.rrwebRecorder)||void 0===A||A.stop(),null===(e=this.transport)||void 0===e||e.flush(!0)})}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{this.updateSessionDuration()},3e4)}updateSessionDuration(A=!1){var e,t;if(!this.sessionId||!this.sessionStartTime)return;const r=Date.now()-this.sessionStartTime,n=Object.assign({sessionId:this.sessionId,userId:this.userId||void 0,anonymousId:this.anonymousId,durationMs:r,platform:"web"},this.getContextData());A&&(n.endedAt=(new Date).toISOString()),null===(e=this.transport)||void 0===e||e.startSession(n,A),(null===(t=this.config)||void 0===t?void 0:t.debug)&&console.log("[DevSkin] Session duration updated:",r,"ms",A?"(ending)":"")}}});
|
|
50
|
+
function A(A,e,t,r){return new(t||(t=Promise))(function(e,n){function s(A){try{i(r.next(A))}catch(A){n(A)}}function o(A){try{i(r.throw(A))}catch(A){n(A)}}function i(A){var r;A.done?e(A.value):(r=A.value,r instanceof t?r:new t(function(A){A(r)})).then(s,o)}i((r=r.apply(A,[])).next())})}for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="undefined"==typeof Uint8Array?[]:new Uint8Array(256),r=0;r<64;r++)t[e.charCodeAt(r)]=r;var n=function(A){var t,r=new Uint8Array(A),n=r.length,s="";for(t=0;t<n;t+=3)s+=e[r[t]>>2],s+=e[(3&r[t])<<4|r[t+1]>>4],s+=e[(15&r[t+1])<<2|r[t+2]>>6],s+=e[63&r[t+2]];return n%3==2?s=s.substring(0,s.length-1)+"=":n%3==1&&(s=s.substring(0,s.length-2)+"=="),s};const s=new Map,o=new Map,i=self;i.onmessage=function(e){return A(this,0,void 0,function*(){if(!("OffscreenCanvas"in globalThis))return i.postMessage({id:e.data.id});{const{id:t,bitmap:r,width:a,height:c,dataURLOptions:B}=e.data,l=function(e,t,r){return A(this,0,void 0,function*(){const A=`${e}-${t}`;if("OffscreenCanvas"in globalThis){if(o.has(A))return o.get(A);const s=new OffscreenCanvas(e,t);s.getContext("2d");const i=yield s.convertToBlob(r),a=yield i.arrayBuffer(),c=n(a);return o.set(A,c),c}return""})}(a,c,B),u=new OffscreenCanvas(a,c);u.getContext("2d").drawImage(r,0,0),r.close();const g=yield u.convertToBlob(B),d=g.type,h=yield g.arrayBuffer(),w=n(h);if(!s.has(t)&&(yield l)===w)return s.set(t,w),i.postMessage({id:t});if(s.get(t)===w)return i.postMessage({id:t});i.postMessage({id:t,type:d,base64:w,width:a,height:c}),s.set(t,w)}})}}()},function(A){return Ge=Ge||function(A){var e=function(A){var e=A.toString().split("\n");e.pop(),e.shift();for(var t=e[0].search(/\S/),r=/(['"])__worker_loader_strict__(['"])/g,n=0,s=e.length;n<s;++n)e[n]=e[n].substring(t).replace(r,"$1use strict$2")+"\n";return e}(A),t=new Blob(e,{type:"application/javascript"});return URL.createObjectURL(t)}(Ne),new Worker(Ge,A)});class Pe{reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}constructor(A){this.pendingCanvasMutations=new Map,this.rafStamps={latestId:0,invokeId:null},this.frozen=!1,this.locked=!1,this.processMutation=(A,e)=>{!(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId)&&this.rafStamps.invokeId||(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(A)||this.pendingCanvasMutations.set(A,[]),this.pendingCanvasMutations.get(A).push(e)};const{sampling:e="all",win:t,blockClass:r,blockSelector:n,recordCanvas:s,dataURLOptions:o}=A;this.mutationCb=A.mutationCb,this.mirror=A.mirror,s&&"all"===e&&this.initCanvasMutationObserver(t,r,n),s&&"number"==typeof e&&this.initCanvasFPSObserver(e,t,r,n,{dataURLOptions:o})}initCanvasFPSObserver(A,e,t,r,n){const s=xe(e,t,r,!0),o=new Map,i=new Ve;i.onmessage=A=>{const{id:e}=A.data;if(o.set(e,!1),!("base64"in A.data))return;const{base64:t,type:r,width:n,height:s}=A.data;this.mutationCb({id:e,type:$A["2D"],commands:[{property:"clearRect",args:[0,0,n,s]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:t}],type:r}]},0,0]}]})};const a=1e3/A;let c,B=0;const l=A=>{B&&A-B<a||(B=A,(()=>{const A=[];return e.document.querySelectorAll("canvas").forEach(e=>{xA(e,t,r,!0)||A.push(e)}),A})().forEach(A=>be(this,0,void 0,function*(){var e;const t=this.mirror.getId(A);if(o.get(t))return;if(0===A.width||0===A.height)return;if(o.set(t,!0),["webgl","webgl2"].includes(A.__context)){const t=A.getContext(A.__context);!1===(null===(e=null==t?void 0:t.getContextAttributes())||void 0===e?void 0:e.preserveDrawingBuffer)&&t.clear(t.COLOR_BUFFER_BIT)}const r=yield createImageBitmap(A);i.postMessage({id:t,bitmap:r,width:A.width,height:A.height,dataURLOptions:n.dataURLOptions},[r])}))),c=requestAnimationFrame(l)};c=requestAnimationFrame(l),this.resetObservers=()=>{s(),cancelAnimationFrame(c)}}initCanvasMutationObserver(A,e,t){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const r=xe(A,e,t,!1),n=function(A,e,t,r){const n=[],s=Object.getOwnPropertyNames(e.CanvasRenderingContext2D.prototype);for(const o of s)try{if("function"!=typeof e.CanvasRenderingContext2D.prototype[o])continue;const s=KA(e.CanvasRenderingContext2D.prototype,o,function(n){return function(...s){return xA(this.canvas,t,r,!0)||setTimeout(()=>{const t=Te(s,e,this);A(this.canvas,{type:$A["2D"],property:o,args:t})},0),n.apply(this,s)}});n.push(s)}catch(t){const r=LA(e.CanvasRenderingContext2D.prototype,o,{set(e){A(this.canvas,{type:$A["2D"],property:o,args:[e],setter:!0})}});n.push(r)}return()=>{n.forEach(A=>A())}}(this.processMutation.bind(this),A,e,t),s=function(A,e,t,r){const n=[];return n.push(...Re(e.WebGLRenderingContext.prototype,$A.WebGL,A,t,r,0,e)),void 0!==e.WebGL2RenderingContext&&n.push(...Re(e.WebGL2RenderingContext.prototype,$A.WebGL2,A,t,r,0,e)),()=>{n.forEach(A=>A())}}(this.processMutation.bind(this),A,e,t,this.mirror);this.resetObservers=()=>{r(),n(),s()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const A=e=>{this.rafStamps.latestId=e,requestAnimationFrame(A)};requestAnimationFrame(A)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((A,e)=>{const t=this.mirror.getId(e);this.flushPendingCanvasMutationFor(e,t)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(A,e){if(this.frozen||this.locked)return;const t=this.pendingCanvasMutations.get(A);if(!t||-1===e)return;const r=t.map(A=>{const e=function(A,e){var t={};for(var r in A)Object.prototype.hasOwnProperty.call(A,r)&&e.indexOf(r)<0&&(t[r]=A[r]);if(null!=A&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(A);n<r.length;n++)e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(A,r[n])&&(t[r[n]]=A[r[n]])}return t}(A,["type"]);return e}),{type:n}=t[0];this.mutationCb({id:e,type:n,commands:r}),this.pendingCanvasMutations.delete(A)}}class Xe{constructor(A){this.trackedLinkElements=new WeakSet,this.styleMirror=new JA,this.mutationCb=A.mutationCb,this.adoptedStyleSheetCb=A.adoptedStyleSheetCb}attachLinkElement(A,e){"_cssText"in e.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:e.id,attributes:e.attributes}]}),this.trackLinkElement(A)}trackLinkElement(A){this.trackedLinkElements.has(A)||(this.trackedLinkElements.add(A),this.trackStylesheetInLinkElement(A))}adoptStyleSheets(A,e){if(0===A.length)return;const t={id:e,styleIds:[]},r=[];for(const e of A){let A;this.styleMirror.has(e)?A=this.styleMirror.getId(e):(A=this.styleMirror.add(e),r.push({styleId:A,rules:Array.from(e.rules||CSSRule,(A,e)=>({rule:z(A),index:e}))})),t.styleIds.push(A)}r.length>0&&(t.styles=r),this.adoptedStyleSheetCb(t)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(A){}}class Je{constructor(){this.nodeMap=new WeakMap,this.loop=!0,this.periodicallyClear()}periodicallyClear(){requestAnimationFrame(()=>{this.clear(),this.loop&&this.periodicallyClear()})}inOtherBuffer(A,e){const t=this.nodeMap.get(A);return t&&Array.from(t).some(A=>A!==e)}add(A,e){this.nodeMap.set(A,(this.nodeMap.get(A)||new Set).add(e))}clear(){this.nodeMap=new WeakMap}destroy(){this.loop=!1}}function We(A){return Object.assign(Object.assign({},A),{timestamp:DA()})}let Ye,_e,Ze,je=!1;const qe=new $;function ze(A={}){const{emit:e,checkoutEveryNms:t,checkoutEveryNth:r,blockClass:n="rr-block",blockSelector:s=null,ignoreClass:o="rr-ignore",ignoreSelector:i=null,maskTextClass:a="rr-mask",maskTextSelector:c=null,inlineStylesheet:B=!0,maskAllInputs:l,maskInputOptions:u,slimDOMOptions:g,maskInputFn:d,maskTextFn:h,hooks:w,packFn:Q,sampling:p={},dataURLOptions:C={},mousemoveWait:f,recordDOM:U=!0,recordCanvas:F=!1,recordCrossOriginIframes:m=!1,recordAfter:y=("DOMContentLoaded"===A.recordAfter?A.recordAfter:"load"),userTriggeredOnInput:I=!1,collectFonts:E=!1,inlineImages:H=!1,plugins:v,keepIframeSrcFn:b=()=>!1,ignoreCSSAttributes:S=new Set([]),errorHandler:L}=A;Be(L);const K=!m||window.parent===window;let D=!1;if(!K)try{window.parent.document&&(D=!1)}catch(A){D=!0}if(K&&!e)throw new Error("emit function is required");void 0!==f&&void 0===p.mousemove&&(p.mousemove=f),qe.reset();const M=!0===l?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==u?u:{password:!0},k=!0===g||"all"===g?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===g,headMetaDescKeywords:"all"===g}:g||{};let T;!function(A=window){"NodeList"in A&&!A.NodeList.prototype.forEach&&(A.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in A&&!A.DOMTokenList.prototype.forEach&&(A.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...A)=>{let e=A[0];if(!(0 in A))throw new TypeError("1 argument is required");do{if(this===e)return!0}while(e=e&&e.parentNode);return!1})}();let O=0;const x=A=>{for(const e of v||[])e.eventProcessor&&(A=e.eventProcessor(A));return Q&&!D&&(A=Q(A)),A};Ye=(A,n)=>{var s;if(!(null===(s=ge[0])||void 0===s?void 0:s.isFrozen())||A.type===ZA.FullSnapshot||A.type===ZA.IncrementalSnapshot&&A.data.source===jA.Mutation||ge.forEach(A=>A.unfreeze()),K)null==e||e(x(A),n);else if(D){const e={type:"rrweb",event:x(A),origin:window.location.origin,isCheckout:n};window.parent.postMessage(e,"*")}if(A.type===ZA.FullSnapshot)T=A,O=0;else if(A.type===ZA.IncrementalSnapshot){if(A.data.source===jA.Mutation&&A.data.isAttachIframe)return;O++;const e=r&&O>=r,n=t&&A.timestamp-T.timestamp>t;(e||n)&&_e(!0)}};const R=A=>{Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Mutation},A)}))},N=A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Scroll},A)})),G=A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.CanvasMutation},A)})),V=new Xe({mutationCb:R,adoptedStyleSheetCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.AdoptedStyleSheet},A)}))}),P=new He({mirror:qe,mutationCb:R,stylesheetManager:V,recordCrossOriginIframes:m,wrappedEmit:Ye});for(const A of v||[])A.getMirror&&A.getMirror({nodeMirror:qe,crossOriginIframeMirror:P.crossOriginIframeMirror,crossOriginIframeStyleMirror:P.crossOriginIframeStyleMirror});const X=new Je;Ze=new Pe({recordCanvas:F,mutationCb:G,win:window,blockClass:n,blockSelector:s,mirror:qe,sampling:p.canvas,dataURLOptions:C});const J=new ve({mutationCb:R,scrollCb:N,bypassOptions:{blockClass:n,blockSelector:s,maskTextClass:a,maskTextSelector:c,inlineStylesheet:B,maskInputOptions:M,dataURLOptions:C,maskTextFn:h,maskInputFn:d,recordCanvas:F,inlineImages:H,sampling:p,slimDOMOptions:k,iframeManager:P,stylesheetManager:V,canvasManager:Ze,keepIframeSrcFn:b,processedNodeManager:X},mirror:qe});_e=(A=!1)=>{if(!U)return;Ye(We({type:ZA.Meta,data:{href:window.location.href,width:TA(),height:kA()}}),A),V.reset(),J.init(),ge.forEach(A=>A.lock());const e=function(A,e){const{mirror:t=new $,blockClass:r="rr-block",blockSelector:n=null,maskTextClass:s="rr-mask",maskTextSelector:o=null,inlineStylesheet:i=!0,inlineImages:a=!1,recordCanvas:c=!1,maskAllInputs:B=!1,maskTextFn:l,maskInputFn:u,slimDOM:g=!1,dataURLOptions:d,preserveWhiteSpace:h,onSerialize:w,onIframeLoad:Q,iframeLoadTimeout:p,onStylesheetLoad:C,stylesheetLoadTimeout:f,keepIframeSrcFn:U=()=>!1}=e||{};return EA(A,{doc:A,mirror:t,blockClass:r,blockSelector:n,maskTextClass:s,maskTextSelector:o,skipChild:!1,inlineStylesheet:i,maskInputOptions:!0===B?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===B?{password:!0}:B,maskTextFn:l,maskInputFn:u,slimDOMOptions:!0===g||"all"===g?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===g,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===g?{}:g,dataURLOptions:d,inlineImages:a,recordCanvas:c,preserveWhiteSpace:h,onSerialize:w,onIframeLoad:Q,iframeLoadTimeout:p,onStylesheetLoad:C,stylesheetLoadTimeout:f,keepIframeSrcFn:U,newlyAddedElement:!1})}(document,{mirror:qe,blockClass:n,blockSelector:s,maskTextClass:a,maskTextSelector:c,inlineStylesheet:B,maskAllInputs:M,maskTextFn:h,slimDOM:k,dataURLOptions:C,recordCanvas:F,inlineImages:H,onSerialize:A=>{VA(A,qe)&&P.addIframe(A),PA(A,qe)&&V.trackLinkElement(A),XA(A)&&J.addShadowRoot(A.shadowRoot,document)},onIframeLoad:(A,e)=>{P.attachIframe(A,e),J.observeAttachShadow(A)},onStylesheetLoad:(A,e)=>{V.attachLinkElement(A,e)},keepIframeSrcFn:b});if(!e)return console.warn("Failed to snapshot the document");Ye(We({type:ZA.FullSnapshot,data:{node:e,initialOffset:MA(window)}}),A),ge.forEach(A=>A.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&V.adoptStyleSheets(document.adoptedStyleSheets,qe.getId(document))};try{const A=[],e=A=>{var e;return ue(me)({mutationCb:R,mousemoveCb:(A,e)=>Ye(We({type:ZA.IncrementalSnapshot,data:{source:e,positions:A}})),mouseInteractionCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.MouseInteraction},A)})),scrollCb:N,viewportResizeCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.ViewportResize},A)})),inputCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Input},A)})),mediaInteractionCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.MediaInteraction},A)})),styleSheetRuleCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.StyleSheetRule},A)})),styleDeclarationCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.StyleDeclaration},A)})),canvasMutationCb:G,fontCb:A=>Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Font},A)})),selectionCb:A=>{Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.Selection},A)}))},customElementCb:A=>{Ye(We({type:ZA.IncrementalSnapshot,data:Object.assign({source:jA.CustomElement},A)}))},blockClass:n,ignoreClass:o,ignoreSelector:i,maskTextClass:a,maskTextSelector:c,maskInputOptions:M,inlineStylesheet:B,sampling:p,recordDOM:U,recordCanvas:F,inlineImages:H,userTriggeredOnInput:I,collectFonts:E,doc:A,maskInputFn:d,maskTextFn:h,keepIframeSrcFn:b,blockSelector:s,slimDOMOptions:k,dataURLOptions:C,mirror:qe,iframeManager:P,stylesheetManager:V,shadowDomManager:J,processedNodeManager:X,canvasManager:Ze,ignoreCSSAttributes:S,plugins:(null===(e=null==v?void 0:v.filter(A=>A.observer))||void 0===e?void 0:e.map(A=>({observer:A.observer,options:A.options,callback:e=>Ye(We({type:ZA.Plugin,data:{plugin:A.name,payload:e}}))})))||[]},w)};P.addLoadListener(t=>{try{A.push(e(t.contentDocument))}catch(A){console.warn(A)}});const t=()=>{_e(),A.push(e(document)),je=!0};return"interactive"===document.readyState||"complete"===document.readyState?t():(A.push(HA("DOMContentLoaded",()=>{Ye(We({type:ZA.DomContentLoaded,data:{}})),"DOMContentLoaded"===y&&t()})),A.push(HA("load",()=>{Ye(We({type:ZA.Load,data:{}})),"load"===y&&t()},window))),()=>{A.forEach(A=>A()),X.destroy(),je=!1,le()}}catch(A){console.warn(A)}}ze.addCustomEvent=(A,e)=>{if(!je)throw new Error("please add custom event after start recording");Ye(We({type:ZA.Custom,data:{tag:A,payload:e}}))},ze.freezePage=()=>{ge.forEach(A=>A.freeze())},ze.takeFullSnapshot=A=>{if(!je)throw new Error("please take full snapshot after start recording");_e(A)},ze.mirror=qe;class $e{constructor(A,e,t,r=0){this.stopFn=null,this.events=[],this.onEventsReady=null,this.flushInterval=null,this.hasFullSnapshot=!1,this.sessionStartTime=0,this.recordingStartTime=0,this.sessionId=A,this.config=e,this.onEventsReady=t,this.sessionStartTime=r||Date.now(),this.recordingStartTime=Date.now(),console.log(`[RRWeb] Recording initialized - session started at ${this.sessionStartTime}, recording started at ${this.recordingStartTime}`)}start(){if(this.config.enabled)if(this.stopFn)console.warn("[RRWeb] Recording already started");else try{this.stopFn=ze({emit:A=>{const e=A.timestamp;A.timestamp=A.timestamp-this.sessionStartTime,this.config.enabled&&2===A.type&&console.log(`[RRWeb] FullSnapshot - original: ${e}, relative: ${A.timestamp}, session start: ${this.sessionStartTime}`),this.events.push(A),2===A.type?(this.hasFullSnapshot=!0,this.flush()):this.hasFullSnapshot&&this.events.length>=20&&this.flush()},sampling:{mousemove:void 0===this.config.sampleRate||Math.floor(100/this.config.sampleRate),mouseInteraction:!0,scroll:150,media:800,input:"last"},checkoutEveryNms:this.config.checkoutEveryNms||3e5,checkoutEveryNth:this.config.checkoutEveryNth||200,blockClass:this.config.blockClass||"rr-block",ignoreClass:this.config.ignoreClass||"rr-ignore",maskAllInputs:void 0===this.config.maskAllInputs||this.config.maskAllInputs,maskInputOptions:this.config.maskInputOptions||{password:!0,email:!0,tel:!0},maskTextClass:"rr-mask",inlineStylesheet:void 0===this.config.inlineStylesheet||this.config.inlineStylesheet,recordCanvas:this.config.recordCanvas||!1,collectFonts:void 0===this.config.collectFonts||this.config.collectFonts,recordCrossOriginIframes:!1}),this.flushInterval=window.setInterval(()=>{this.hasFullSnapshot&&this.events.length>0&&this.flush()},2e3),setTimeout(()=>{if(!this.hasFullSnapshot)try{ze.takeFullSnapshot()}catch(A){this.events.length>0&&(this.hasFullSnapshot=!0,this.flush())}},2e3)}catch(A){console.error("[RRWeb] Failed to start recording:",A)}else console.log("[RRWeb] Recording disabled in config")}stop(){this.stopFn&&(this.stopFn(),this.stopFn=null),this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.events.length>0&&this.flush()}flush(){if(0===this.events.length)return;const A=[...this.events];this.events=[],this.onEventsReady&&this.onEventsReady(A)}getEventCount(){return this.events.length}isRecording(){return null!==this.stopFn}}class At{constructor(A){this.config=A,this.queue=[],this.flushInterval=null,this.maxQueueSize=20,this.flushIntervalMs=2e3,this.sessionId=null,this.apiUrl=A.apiUrl||"https://api.devskin.com",this.startPeriodicFlush(),"undefined"!=typeof window&&(window.addEventListener("beforeunload",()=>{this.flush()}),window.addEventListener("visibilitychange",()=>{document.hidden&&this.flush(!0)}))}setSessionId(A){this.sessionId=A}sendEvent(A){this.enqueue("event",A)}identifyUser(A){this.sendToBackend("/v1/analytics/identify",A)}startSession(e){return A(this,arguments,void 0,function*(A,e=!1){yield this.sendToBackend("/v1/rum/sessions",A,e)})}sendError(A){this.enqueue("error",A)}sendNetworkRequest(A){this.enqueue("network",A)}sendPerformanceMetric(A){this.enqueue("performance",A)}sendPageView(e){return A(this,void 0,void 0,function*(){this.sendToBackend("/v1/rum/page-views",e)})}sendRecordingEvents(e,t){return A(this,void 0,void 0,function*(){const A={session_id:e,events:t,timestamp:(new Date).toISOString(),apiKey:this.config.apiKey,appId:this.config.appId},r=new Blob([JSON.stringify(A)]).size,n=t.some(A=>2===A.type),s=n?3:1;let o=null;for(let A=1;A<=s;A++)try{return void(r>1e5?yield this.sendToBackendXHR("/v1/rum/recordings",{session_id:e,events:t,timestamp:(new Date).toISOString()}):yield this.sendToBackend("/v1/rum/recordings",{session_id:e,events:t,timestamp:(new Date).toISOString()}))}catch(e){if(o=e,A<s){const e=1e3*A;yield new Promise(A=>setTimeout(A,e))}}this.config.debug&&console.error(`[DevSkin SDK] Failed to send recording events after ${s} attempts:`,o)})}sendHeatmapData(A){this.enqueue("heatmap",A)}sendScreenshot(e){return A(this,void 0,void 0,function*(){yield this.sendToBackend("/v1/sdk/screenshot",{screenshot:e})})}flush(A=!1){if(0===this.queue.length)return;const e=[...this.queue];this.queue=[];const t={};e.forEach(A=>{t[A.type]||(t[A.type]=[]),t[A.type].push(A.data)}),Object.entries(t).forEach(([e,t])=>{const r=this.getEndpointForType(e);"event"===e&&t.length>1?this.sendToBackend("/v1/rum/events/batch",{events:t},A):"heatmap"===e?this.sendToBackend(r,{heatmaps:t,apiKey:this.config.apiKey,appId:this.config.appId},A):t.forEach(e=>{this.sendToBackend(r,e,A)})}),this.config.debug&&console.log(`[DevSkin] Flushed ${e.length} items to backend`)}enqueue(A,e){let t=e;"heatmap"!==A&&(t=Object.assign(Object.assign({},e),{applicationId:this.config.appId}),"network"!==A&&"performance"!==A||!this.sessionId||(t.sessionId=this.sessionId)),this.queue.push({type:A,data:t,timestamp:Date.now()}),this.queue.length>=this.maxQueueSize&&this.flush()}startPeriodicFlush(){this.flushInterval=setInterval(()=>{this.flush()},this.flushIntervalMs)}getEndpointForType(A){switch(A){case"event":default:return"/v1/rum/events";case"error":return"/v1/errors/errors";case"network":return"/v1/rum/network-requests";case"performance":return"/v1/rum/web-vitals";case"heatmap":return"/v1/sdk/heatmap"}}sendToBackendXHR(e,t){return A(this,void 0,void 0,function*(){const A=`${this.apiUrl}${e}`,r=Object.assign(Object.assign({},t),{apiKey:this.config.apiKey,applicationId:this.config.appId,environment:this.config.environment,release:this.config.release});if(this.config.beforeSend){if(!this.config.beforeSend(r))return}return new Promise((t,n)=>{const s=new XMLHttpRequest;s.open("POST",A,!0),s.setRequestHeader("Content-Type","application/json"),s.setRequestHeader("Authorization",`Bearer ${this.config.apiKey}`),s.onload=()=>{s.status>=200&&s.status<300?(this.config.debug&&console.log("[DevSkin] Data sent successfully via XHR:",e),t()):(console.error("[DevSkin] XHR HTTP Error:",s.status,s.responseText),n(new Error(`HTTP ${s.status}: ${s.statusText}`)))},s.onerror=()=>{console.error("[DevSkin] XHR network error:",e),n(new Error("Network error"))},s.ontimeout=()=>{console.error("[DevSkin] XHR timeout:",e),n(new Error("Request timeout"))},s.timeout=3e4;try{const A=JSON.stringify(r);s.send(A)}catch(A){console.error("[DevSkin] Failed to send XHR request:",A),n(A)}})})}sendToBackend(e,t){return A(this,arguments,void 0,function*(A,e,t=!1){const r=`${this.apiUrl}${A}`,n=Object.assign(Object.assign({},e),{apiKey:this.config.apiKey,applicationId:this.config.appId,environment:this.config.environment,release:this.config.release});if(this.config.beforeSend){if(!this.config.beforeSend(n))return}if(t&&navigator.sendBeacon){const A=new Blob([JSON.stringify(n)],{type:"application/json"});return void navigator.sendBeacon(r,A)}try{const e=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(n),keepalive:!0});if(!e.ok){const A=yield e.text();throw console.error("[DevSkin] HTTP Error:",e.status,A),new Error(`HTTP ${e.status}: ${e.statusText}`)}this.config.debug&&console.log("[DevSkin] Data sent successfully:",A)}catch(e){throw console.error("[DevSkin] Failed to send data to",A,":",e),e}})}destroy(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}}return new class{constructor(){this.config=null,this.transport=null,this.sessionId=null,this.userId=null,this.anonymousId=null,this.sessionStartTime=0,this.initialized=!1,this.initializing=!1,this.heartbeatInterval=null,this.deviceCollector=null,this.locationCollector=null,this.browserCollector=null,this.performanceCollector=null,this.errorCollector=null,this.networkCollector=null,this.heatmapCollector=null,this.screenshotCollector=null,this.rrwebRecorder=null}init(A){if(this.initialized||this.initializing)return void console.warn("[DevSkin] SDK already initialized or initializing");this.initializing=!0,this.config=Object.assign({debug:!1,captureWebVitals:!0,captureNetworkRequests:!0,captureErrors:!0,captureUserAgent:!0,captureLocation:!0,captureDevice:!0,heatmapOptions:{enabled:!0,trackClicks:!0,trackScroll:!0,trackMouseMovement:!1}},A),this.config.debug&&console.log("[DevSkin] Initializing SDK with config:",this.config),this.transport=new At(this.config),this.anonymousId=this.getOrCreateAnonymousId(),this.deviceCollector=new e(this.config),this.locationCollector=new t(this.config),this.browserCollector=new r(this.config);const n=()=>{this.startSession().then(()=>{var A,e;this.config.captureWebVitals&&(this.performanceCollector=new N(this.config,this.transport),this.performanceCollector.start()),this.config.captureErrors&&(this.errorCollector=new G(this.config,this.transport),this.errorCollector.start()),this.config.captureNetworkRequests&&(this.networkCollector=new V(this.config,this.transport),this.networkCollector.start());const t=Object.assign({enabled:!0,trackClicks:!0,trackScroll:!0,trackMouseMovement:!0,mouseMoveSampling:.1},this.config.heatmapOptions);this.config.heatmapOptions=t,this.heatmapCollector=new P(this.config,this.transport,this.anonymousId,this.sessionId),this.heatmapCollector.start(),this.screenshotCollector=new _(this.config,this.transport),this.screenshotCollector.captureAndSend(this.sessionId,window.location.href),this.config.debug&&console.log("[DevSkin] Heatmap collection enabled (always on)"),(null===(A=this.config.sessionRecording)||void 0===A?void 0:A.enabled)&&(this.rrwebRecorder=new $e(this.sessionId,{enabled:!0,sampleRate:this.config.sessionRecording.sampling||.5,blockClass:"rr-block",ignoreClass:this.config.sessionRecording.ignoreClass||"rr-ignore",maskAllInputs:void 0===this.config.sessionRecording.maskAllInputs||this.config.sessionRecording.maskAllInputs,maskInputOptions:{password:!0,email:!0,tel:!0},recordCanvas:this.config.sessionRecording.recordCanvas||!1,collectFonts:!0,inlineStylesheet:!0,checkoutEveryNms:3e5,checkoutEveryNth:200},A=>{var e;null===(e=this.transport)||void 0===e||e.sendRecordingEvents(this.sessionId,A)},this.sessionStartTime),this.rrwebRecorder.start(),(null===(e=this.config)||void 0===e?void 0:e.debug)&&console.log("[DevSkin] RRWeb recording started for session:",this.sessionId)),this.trackPageView(),this.startHeartbeat()}).catch(A=>{console.error("[DevSkin] Failed to create session:",A)}),this.setupVisibilityTracking(),this.setupUnloadTracking(),this.initialized=!0,this.initializing=!1};"undefined"!=typeof window?"requestIdleCallback"in window?window.requestIdleCallback(n,{timeout:2e3}):setTimeout(n,1):n(),this.config.debug&&console.log("[DevSkin] SDK initialization started (heavy collectors loading in background)")}track(A,e){var t,r,n,s;if(!this.transport)return void console.warn("[DevSkin] SDK not initialized. Call init() first.");const o={eventName:A,eventType:"track",timestamp:(new Date).toISOString(),sessionId:null!==(t=this.sessionId)&&void 0!==t?t:void 0,userId:null!==(r=this.userId)&&void 0!==r?r:void 0,anonymousId:null!==(n=this.anonymousId)&&void 0!==n?n:void 0,properties:Object.assign(Object.assign({},e),this.getContextData()),pageUrl:window.location.href,pageTitle:document.title};this.transport.sendEvent(o),(null===(s=this.config)||void 0===s?void 0:s.debug)&&console.log("[DevSkin] Event tracked:",o)}trackPageView(A){var e,t;if(!this.initialized)return void console.warn("[DevSkin] SDK not initialized. Call init() first.");const r=this.generateId();null===(e=this.transport)||void 0===e||e.sendPageView(Object.assign({sessionId:this.sessionId,pageViewId:r,url:window.location.href,path:window.location.pathname,queryParams:window.location.search,referrer:document.referrer,title:document.title,timestamp:(new Date).toISOString()},A)),this.track("page_view",Object.assign({path:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer},A)),(null===(t=this.config)||void 0===t?void 0:t.debug)&&console.log("[DevSkin] Page view tracked:",{sessionId:this.sessionId,pageViewId:r,url:window.location.href})}identify(A,e){var t,r,n;if(!this.transport)return void console.warn("[DevSkin] SDK not initialized. Call init() first.");this.userId=A;const s={userId:A,anonymousId:null!==(t=this.anonymousId)&&void 0!==t?t:void 0,traits:Object.assign(Object.assign({},e),this.getContextData()),sessionId:null!==(r=this.sessionId)&&void 0!==r?r:void 0,timestamp:(new Date).toISOString()};this.transport.identifyUser(s),(null===(n=this.config)||void 0===n?void 0:n.debug)&&console.log("[DevSkin] User identified:",s)}captureError(A,e){var t;this.initialized?null===(t=this.errorCollector)||void 0===t||t.captureError(A,Object.assign(Object.assign({},e),{session_id:this.sessionId,user_id:this.userId||void 0})):console.warn("[DevSkin] SDK not initialized. Call init() first.")}addBreadcrumb(A){var e;this.initialized&&(null===(e=this.errorCollector)||void 0===e||e.addBreadcrumb(A))}startRecording(){var A;null===(A=this.rrwebRecorder)||void 0===A||A.start()}stopRecording(){var A;null===(A=this.rrwebRecorder)||void 0===A||A.stop()}optOut(){localStorage.setItem("devskin_opt_out","true"),this.initialized=!1}optIn(){localStorage.removeItem("devskin_opt_out")}startSession(){return A(this,void 0,void 0,function*(){var A,e,t,r,n;const s=sessionStorage.getItem("devskin_session_id"),o=sessionStorage.getItem("devskin_session_start");if(s&&o)return this.sessionId=s,this.sessionStartTime=parseInt(o,10),null===(A=this.transport)||void 0===A||A.setSessionId(this.sessionId),void((null===(e=this.config)||void 0===e?void 0:e.debug)&&console.log("[DevSkin] Resuming existing session:",this.sessionId));this.sessionId=this.generateId(),this.sessionStartTime=Date.now(),sessionStorage.setItem("devskin_session_id",this.sessionId),sessionStorage.setItem("devskin_session_start",this.sessionStartTime.toString()),null===(t=this.transport)||void 0===t||t.setSessionId(this.sessionId);const i=Object.assign({sessionId:this.sessionId,userId:this.userId||void 0,anonymousId:this.anonymousId,startedAt:(new Date).toISOString(),platform:"web"},this.getContextData());yield null===(r=this.transport)||void 0===r?void 0:r.startSession(i),(null===(n=this.config)||void 0===n?void 0:n.debug)&&console.log("[DevSkin] New session created:",this.sessionId)})}getContextData(){var A,e,t,r;const n={};if(this.deviceCollector){const s=this.deviceCollector.collect();n.deviceType=s.type,n.deviceModel=s.model,n.osName=null===(A=s.os)||void 0===A?void 0:A.name,n.osVersion=null===(e=s.os)||void 0===e?void 0:e.version,n.screenWidth=null===(t=s.screen)||void 0===t?void 0:t.width,n.screenHeight=null===(r=s.screen)||void 0===r?void 0:r.height,n.viewportWidth=window.innerWidth,n.viewportHeight=window.innerHeight}if(this.browserCollector){const A=this.browserCollector.collect();n.browserName=A.name,n.browserVersion=A.version,n.userAgent=A.userAgent}if(this.locationCollector){const A=this.locationCollector.collect();n.country=A.country,n.city=A.city,n.ipAddress=void 0}return n}getOrCreateAnonymousId(){let A=localStorage.getItem("devskin_anonymous_id");return A||(A=this.generateId(),localStorage.setItem("devskin_anonymous_id",A)),A}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}setupVisibilityTracking(){document.addEventListener("visibilitychange",()=>{document.hidden?this.track("page_hidden"):this.track("page_visible")})}setupUnloadTracking(){document.addEventListener("visibilitychange",()=>{var A,e;document.hidden&&(this.updateSessionDuration(),null===(A=this.rrwebRecorder)||void 0===A||A.stop(),null===(e=this.transport)||void 0===e||e.flush(!0))}),window.addEventListener("pagehide",()=>{var A,e;this.track("page_navigation"),this.updateSessionDuration(!1),null===(A=this.rrwebRecorder)||void 0===A||A.stop(),null===(e=this.transport)||void 0===e||e.flush(!0)}),window.addEventListener("beforeunload",()=>{var A,e;this.updateSessionDuration(!1),null===(A=this.rrwebRecorder)||void 0===A||A.stop(),null===(e=this.transport)||void 0===e||e.flush(!0)})}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{this.updateSessionDuration()},3e4)}updateSessionDuration(A=!1){var e,t;if(!this.sessionId||!this.sessionStartTime)return;const r=Date.now()-this.sessionStartTime,n=Object.assign({sessionId:this.sessionId,userId:this.userId||void 0,anonymousId:this.anonymousId,durationMs:r,platform:"web"},this.getContextData());A&&(n.endedAt=(new Date).toISOString()),null===(e=this.transport)||void 0===e||e.startSession(n,A),(null===(t=this.config)||void 0===t?void 0:t.debug)&&console.log("[DevSkin] Session duration updated:",r,"ms",A?"(ending)":"")}}});
|
|
51
51
|
//# sourceMappingURL=devskin.umd.min.js.map
|