@brainfish-ai/web-tracker 0.0.8-alpha.0 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -26,5 +26,5 @@ PERFORMANCE OF THIS SOFTWARE.
26
26
  `),n=[];for(let r=2,i=a.length;r<i;r+=2){const o=e.exec(a[r]);o&&n.push(new _e({fileName:o[2],lineNumber:parseFloat(o[1])}))}return n},parseOpera10:function(t){const e=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,a=t.stacktrace.split(`
27
27
  `),n=[];for(let r=0,i=a.length;r<i;r+=2){const o=e.exec(a[r]);o&&n.push(new _e({functionName:o[3]||void 0,fileName:o[2],lineNumber:parseFloat(o[1])}))}return n},parseOpera11:function(t){return t.stack.split(`
28
28
  `).filter(function(e){return!!e.match(Ci)&&!e.match(/^Error created at/)},this).map(function(e){const a=e.split("@"),n=this.extractLocation(a.pop()),r=(a.shift()||"").replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0;return new _e({functionName:r,fileName:n[0],lineNumber:n[1],columnNumber:n[2]})},this)}};function Ai(t){if(!t||!t.outerHTML)return"";let e="";for(;t.parentElement;){let a=t.localName;if(!a)break;a=a.toLowerCase();const n=t.parentElement,r=[];if(n.children&&n.children.length>0)for(let i=0;i<n.children.length;i++){const o=n.children[i];o.localName&&o.localName.toLowerCase&&o.localName.toLowerCase()===a&&r.push(o)}r.length>1&&(a+=`:eq(${r.indexOf(t)})`),e=a+(e?">"+e:""),t=n}return e}function Wa(t){return Object.prototype.toString.call(t)==="[object Object]"}function Rn(t,e){if(e===0)return!0;const a=Object.keys(t);for(const n of a)if(Wa(t[n])&&Rn(t[n],e-1))return!0;return!1}function Ta(t,e){const a={numOfKeysLimit:50,depthOfLimit:4};Object.assign(a,e);const n=[],r=[];return JSON.stringify(t,function(i,o){if(n.length>0){const s=n.indexOf(this);~s?n.splice(s+1):n.push(this),~s?r.splice(s,1/0,i):r.push(i),~n.indexOf(o)&&(o=n[0]===o?"[Circular ~]":"[Circular ~."+r.slice(0,n.indexOf(o)).join(".")+"]")}else n.push(o);if(o===null)return o;if(o===void 0)return"undefined";if(function(s){return!!(Wa(s)&&Object.keys(s).length>a.numOfKeysLimit||typeof s=="function"||Wa(s)&&Rn(s,a.depthOfLimit))}(o))return function(s){let l=s.toString();return a.stringLengthLimit&&l.length>a.stringLengthLimit&&(l=`${l.slice(0,a.stringLengthLimit)}...`),l}(o);if(o instanceof Event){const s={};for(const l in o){const c=o[l];Array.isArray(c)?s[l]=Ai(c.length?c[0]:null):s[l]=c}return s}return o instanceof Node?o instanceof HTMLElement?o?o.outerHTML:"":o.nodeName:o instanceof Error?o.stack?o.stack+`
29
- End of stack for Error object`:o.name+": "+o.message:o})}const Ft={level:["assert","clear","count","countReset","debug","dir","dirxml","error","group","groupCollapsed","groupEnd","info","log","table","time","timeEnd","timeLog","trace","warn"],lengthThreshold:1e3,logger:"console"};function zi(t,e,a){const n=a?Object.assign({},Ft,a):Ft,r=n.logger;if(!r)return()=>{};let i;i=typeof r=="string"?e[r]:r;let o=0;const s=[];if(n.level.includes("error")&&window){const c=h=>{const d=h.message,u=h.error,p=Lt.parse(u).map(R=>R.toString()),f=[Ta(d,n.stringifyOptions)];t({level:"error",trace:p,payload:f})};window.addEventListener("error",c),s.push(()=>{window&&window.removeEventListener("error",c)})}for(const c of n.level)s.push(l(i,c));return()=>{s.forEach(c=>c())};function l(c,h){return c[h]?Re(c,h,d=>(...u)=>{d.apply(this,u);try{const p=Lt.parse(new Error).map(R=>R.toString()).splice(1),f=u.map(R=>Ta(R,n.stringifyOptions));o++,o<n.lengthThreshold?t({level:h,trace:p,payload:f}):o===n.lengthThreshold&&t({level:"warn",trace:[],payload:[Ta("The number of log records reached the threshold.")]})}catch(p){d("rrweb logger error:",p,...u)}}):()=>{}}}class ji extends Array{constructor(){super()}isEmpty(){return this.length===0}isFull(){return this.length===10}flush(){return this.splice(0,this.length)}}class Ei{constructor(e){N(this,"agent");N(this,"eventBuffer");this.agent=e,this.eventBuffer=new ji}start(){document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.send()})}handle(e){this.eventBuffer.push(e),this.eventBuffer.isFull()&&this.send()}send(){return M(this,null,function*(){if(!this.eventBuffer.isEmpty())if(this.agent.sendEvents){const e=this.eventBuffer.flush();yield this.agent.sendEvents(e)}else console.warn("No send function provided to Agent")})}}var Ua=(t=>(t[t.DomContentLoaded=0]="DomContentLoaded",t[t.Load=1]="Load",t[t.FullSnapshot=2]="FullSnapshot",t[t.IncrementalSnapshot=3]="IncrementalSnapshot",t[t.Meta=4]="Meta",t[t.Custom=5]="Custom",t[t.Plugin=6]="Plugin",t))(Ua||{}),Nn=(t=>(t[t.Mutation=0]="Mutation",t[t.MouseMove=1]="MouseMove",t[t.MouseInteraction=2]="MouseInteraction",t[t.Scroll=3]="Scroll",t[t.ViewportResize=4]="ViewportResize",t[t.Input=5]="Input",t[t.TouchMove=6]="TouchMove",t[t.MediaInteraction=7]="MediaInteraction",t[t.StyleSheetRule=8]="StyleSheetRule",t[t.CanvasMutation=9]="CanvasMutation",t[t.Font=10]="Font",t[t.Log=11]="Log",t[t.Drag=12]="Drag",t[t.StyleDeclaration=13]="StyleDeclaration",t[t.Selection=14]="Selection",t[t.AdoptedStyleSheet=15]="AdoptedStyleSheet",t[t.CustomElement=16]="CustomElement",t))(Nn||{}),Mn=(t=>(t[t.MouseUp=0]="MouseUp",t[t.MouseDown=1]="MouseDown",t[t.Click=2]="Click",t[t.ContextMenu=3]="ContextMenu",t[t.DblClick=4]="DblClick",t[t.Focus=5]="Focus",t[t.Blur=6]="Blur",t[t.TouchStart=7]="TouchStart",t[t.TouchMove_Departed=8]="TouchMove_Departed",t[t.TouchEnd=9]="TouchEnd",t[t.TouchCancel=10]="TouchCancel",t))(Mn||{});const Ti={recordOptions:{blockClass:"rr-block",blockSelector:null,ignoreClass:"rr-ignore",ignoreCSSAttributes:null,maskTextClass:"rr-mask",maskTextSelector:null,maskAllInputs:!0,maskInputOptions:{password:!0},maskInputFn:void 0,maskTextFn:void 0},recordConsolePlugin:{level:["error"],lengthThreshold:Number.POSITIVE_INFINITY,stringifyOptions:{stringLengthLimit:Number.POSITIVE_INFINITY,numOfKeysLimit:Number.POSITIVE_INFINITY,depthOfLimit:Number.POSITIVE_INFINITY}}};class Dt{constructor(e){N(this,"options");N(this,"stop");var a;this.options=Me(de({},Ti),{emit:e,plugins:[{name:"rrweb/console@1",observer:zi,options:a}]}),this.stop=null}static mockImplementation(e){throw new Error("Method not implemented.")}start(){var e;this.stop=(e=Ce(this.options))!=null?e:null}getMirror(){return Ce.mirror}takeFullSnapshot(){return Ce.takeFullSnapshot()}}class xi{constructor(e){N(this,"recordingManager");N(this,"isRunning");N(this,"events");this.recordingManager=e,this.isRunning=!1,this.events=[]}start(){this.isRunning=!0}handle(e){this.isInitializingEvent(e)?this.events.push(e):this.stop(e)}isInitializingEvent(e){return[2,4].includes(e.type)||this.isSelectionEvent(e)||this.isConsoleEvent(e)}isSelectionEvent(e){return e.type===3&&e.data.source===14}isConsoleEvent(e){return e.type===6}stop(e){this.stamp(this.events,e.timestamp-1),this.publish(...this.events,e),this.events=[],this.isRunning=!1}stamp(e,a){e.forEach(n=>n.timestamp=a)}publish(...e){e.forEach(a=>{this.recordingManager.publishEvent(a)})}}class Ri{constructor(e){N(this,"agent");N(this,"recorder");N(this,"stasher");this.agent=e,this.recorder=new Dt(this.handleEvent.bind(this)),this.stasher=new xi(this)}start(){this.recorder.start()}handleEvent(e){var r;const a=new URL(window.location.href),n=a.origin+a.pathname;if(this.isClick(e)){let i=Ce.mirror.getNode(e.data.id);i&&this.nodeIsInteresting(i)&&(e.conversionData={},e.conversionData.eventType="click",e.conversionData.textContent=i.textContent,e.conversionData.htmlElement=(r=i.nodeName)==null?void 0:r.toLowerCase(),e.conversionData.location=n)}this.isCustom(e)&&(e.conversionData={},e.conversionData.eventType="custom",e.conversionData.customEventType=e.data.tag,e.conversionData.location=n),this.stasher.isRunning?this.stasher.handle(e):this.publishEvent(e)}publishEvent(e){this.agent.sender.handle(e),this.agent.timer&&this.agent.timer.restart()}startRecorderWithStasher(){this.stasher.start(),this.recorder=new Dt(this.handleEvent.bind(this)),this.recorder.start()}isClick(e){return e.type===Ua.IncrementalSnapshot&&e.data.source===Nn.MouseInteraction&&e.data.type===Mn.Click}nodeIsInteresting(e){return e.nodeName==="BUTTON"||e.nodeName==="ANCHOR"}isCustom(e){return e.type===Ua.Custom}}class Ni{constructor(e,a){N(this,"agent");N(this,"MAX_IDLE_TIME");N(this,"timeoutId");this.agent=e,this.MAX_IDLE_TIME=a,this.timeoutId=0}restart(){this.stop(),this.start()}stop(){clearTimeout(this.timeoutId)}start(){this.timeoutId=window.setTimeout(this.agent.handleTimeout.bind(this.agent),this.MAX_IDLE_TIME)}}class Mi{constructor(){N(this,"recordingManager");N(this,"sender");N(this,"endpoint");N(this,"MAX_IDLE_TIME");N(this,"timer");N(this,"sendEvents");this.recordingManager=new Ri(this),this.sender=new Ei(this)}start(n){return M(this,arguments,function*({endpoint:e,sendEvents:a}){this.endpoint=e,this.sendEvents=a,this.MAX_IDLE_TIME=6e4,this.timer=new Ni(this,this.MAX_IDLE_TIME),this.sender.start(),this.recordingManager.start()})}handleTimeout(){this.recordingManager.recorder.stop&&this.recordingManager.recorder.stop(),this.sender.send(),this.recordingManager.startRecorderWithStasher()}takeFullSnapshot(){return this.recordingManager.recorder.takeFullSnapshot()}static handleCustomEvent(e){Ce.addCustomEvent(e,null)}}const Te=class Te{constructor(){N(this,"sessionId",null)}static getInstance(){return Te.instance||(Te.instance=new Te),Te.instance}determineSessionState(e){return!this.sessionId&&e?"new":this.sessionId&&e&&this.sessionId!==e?"changed":this.sessionId===e?"active":"expired"}handleSessionTransition(e,a,n){var r;switch(e){case"new":this.sessionId=a;break;case"changed":this.sessionId=a,(r=n.onSessionChanged)==null||r.call(n)}}updateSession(e,a={}){const n=this.determineSessionState(e);this.handleSessionTransition(n,e,a)}getCurrentSessionId(){return this.sessionId}};N(Te,"instance");let Va=Te;const Bt="0.0.8-alpha.0";exports.Tracker=class e extends Er{constructor(a){super(de({sdk:"web",sdkVersion:Bt},a));N(this,"lastPath","");N(this,"debounceTimer",null);N(this,"agent");N(this,"sessionManager",Va.getInstance());this.options=a,this.agent=new Mi,this.isServer()||(this.setGlobalProperties({__referrer:document.referrer}),this.options.trackOutgoingLinks&&this.trackOutgoingLinks(),this.options.trackScreenViews&&this.trackScreenViews(),this.options.trackAttributes&&this.trackAttributes(),this.options.enableRecording&&typeof window!="undefined"&&window.location.hostname==="localhost"&&this.startRecording())}debounce(a,n){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(a,n)}isServer(){return typeof document=="undefined"}trackOutgoingLinks(){this.isServer()||document.addEventListener("click",a=>{const n=a.target,r=n.closest("a");if(r&&n){const i=r.getAttribute("href");i!=null&&i.startsWith("http")&&super.track("link_out",{href:i,text:r.innerText||r.getAttribute("title")||n.getAttribute("alt")||n.getAttribute("title")})}})}trackScreenViews(){if(this.isServer())return;this.screenView();const a=history.pushState;history.pushState=function(...i){const o=a.apply(this,i);return window.dispatchEvent(new Event("pushstate")),window.dispatchEvent(new Event("locationchange")),o};const n=history.replaceState;history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event("replacestate")),window.dispatchEvent(new Event("locationchange")),o},window.addEventListener("popstate",function(){window.dispatchEvent(new Event("locationchange"))});const r=()=>this.debounce(()=>this.screenView(),100);this.options.trackHashChanges?window.addEventListener("hashchange",r):window.addEventListener("locationchange",r)}trackAttributes(){this.isServer()||document.addEventListener("click",a=>{const n=a.target,r=n.closest("button"),i=n.closest("a"),o=r!=null&&r.getAttribute("data-track")?r:i!=null&&i.getAttribute("data-track")?i:null;if(o){const l={};for(const h of o.attributes)h.name.startsWith("data-")&&h.name!=="data-track"&&(l[s=h.name.replace(/^data-/,""),s.replace(/([-_][a-z])/gi,d=>d.toUpperCase().replace("-","").replace("_",""))]=h.value);const c=o.getAttribute("data-track");c&&super.track(c,l)}var s})}startRecording(){if(this.isServer())return;const{apiUrl:a}=this.options;if(!a)throw new Error("API URL is required");this.agent.start({endpoint:a,sendEvents:this.recordEventsToServer.bind(this)})}screenView(a,n){return M(this,null,function*(){if(this.isServer())return;let r,i;if(typeof a=="string"?(r=a,i=n):(r=window.location.href,i=a),this.lastPath===r)return;this.lastPath=r;const o=Me(de({},i!=null?i:{}),{__path:r,__title:document.title});if(this.options.enableRecording){const s=yield function(l){return M(this,null,function*(){try{yield Jr(l);const c=document.body.cloneNode(!0);return Hr(c),yield Vr(c)}catch(c){console.error("An error occurred:",c)}})}();o.__screenshot=s}it(e.prototype,this,"track").call(this,"screen_view",o)})}recordEventsToServer(a){return M(this,null,function*(){this.record(a,n=>{this.sessionManager.updateSession(n.sessionId,{onSessionChanged:()=>{this.agent.takeFullSnapshot()}})})})}},exports.VERSION=Bt;
29
+ End of stack for Error object`:o.name+": "+o.message:o})}const Ft={level:["assert","clear","count","countReset","debug","dir","dirxml","error","group","groupCollapsed","groupEnd","info","log","table","time","timeEnd","timeLog","trace","warn"],lengthThreshold:1e3,logger:"console"};function zi(t,e,a){const n=a?Object.assign({},Ft,a):Ft,r=n.logger;if(!r)return()=>{};let i;i=typeof r=="string"?e[r]:r;let o=0;const s=[];if(n.level.includes("error")&&window){const c=h=>{const d=h.message,u=h.error,p=Lt.parse(u).map(R=>R.toString()),f=[Ta(d,n.stringifyOptions)];t({level:"error",trace:p,payload:f})};window.addEventListener("error",c),s.push(()=>{window&&window.removeEventListener("error",c)})}for(const c of n.level)s.push(l(i,c));return()=>{s.forEach(c=>c())};function l(c,h){return c[h]?Re(c,h,d=>(...u)=>{d.apply(this,u);try{const p=Lt.parse(new Error).map(R=>R.toString()).splice(1),f=u.map(R=>Ta(R,n.stringifyOptions));o++,o<n.lengthThreshold?t({level:h,trace:p,payload:f}):o===n.lengthThreshold&&t({level:"warn",trace:[],payload:[Ta("The number of log records reached the threshold.")]})}catch(p){d("rrweb logger error:",p,...u)}}):()=>{}}}class ji extends Array{constructor(){super()}isEmpty(){return this.length===0}isFull(){return this.length===10}flush(){return this.splice(0,this.length)}}class Ei{constructor(e){N(this,"agent");N(this,"eventBuffer");this.agent=e,this.eventBuffer=new ji}start(){document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.send()})}handle(e){this.eventBuffer.push(e),this.eventBuffer.isFull()&&this.send()}send(){return M(this,null,function*(){if(!this.eventBuffer.isEmpty())if(this.agent.sendEvents){const e=this.eventBuffer.flush();yield this.agent.sendEvents(e)}else console.warn("No send function provided to Agent")})}}var Ua=(t=>(t[t.DomContentLoaded=0]="DomContentLoaded",t[t.Load=1]="Load",t[t.FullSnapshot=2]="FullSnapshot",t[t.IncrementalSnapshot=3]="IncrementalSnapshot",t[t.Meta=4]="Meta",t[t.Custom=5]="Custom",t[t.Plugin=6]="Plugin",t))(Ua||{}),Nn=(t=>(t[t.Mutation=0]="Mutation",t[t.MouseMove=1]="MouseMove",t[t.MouseInteraction=2]="MouseInteraction",t[t.Scroll=3]="Scroll",t[t.ViewportResize=4]="ViewportResize",t[t.Input=5]="Input",t[t.TouchMove=6]="TouchMove",t[t.MediaInteraction=7]="MediaInteraction",t[t.StyleSheetRule=8]="StyleSheetRule",t[t.CanvasMutation=9]="CanvasMutation",t[t.Font=10]="Font",t[t.Log=11]="Log",t[t.Drag=12]="Drag",t[t.StyleDeclaration=13]="StyleDeclaration",t[t.Selection=14]="Selection",t[t.AdoptedStyleSheet=15]="AdoptedStyleSheet",t[t.CustomElement=16]="CustomElement",t))(Nn||{}),Mn=(t=>(t[t.MouseUp=0]="MouseUp",t[t.MouseDown=1]="MouseDown",t[t.Click=2]="Click",t[t.ContextMenu=3]="ContextMenu",t[t.DblClick=4]="DblClick",t[t.Focus=5]="Focus",t[t.Blur=6]="Blur",t[t.TouchStart=7]="TouchStart",t[t.TouchMove_Departed=8]="TouchMove_Departed",t[t.TouchEnd=9]="TouchEnd",t[t.TouchCancel=10]="TouchCancel",t))(Mn||{});const Ti={recordOptions:{blockClass:"rr-block",blockSelector:null,ignoreClass:"rr-ignore",ignoreCSSAttributes:null,maskTextClass:"rr-mask",maskTextSelector:null,maskAllInputs:!0,maskInputOptions:{password:!0},maskInputFn:void 0,maskTextFn:void 0},recordConsolePlugin:{level:["error"],lengthThreshold:Number.POSITIVE_INFINITY,stringifyOptions:{stringLengthLimit:Number.POSITIVE_INFINITY,numOfKeysLimit:Number.POSITIVE_INFINITY,depthOfLimit:Number.POSITIVE_INFINITY}}};class Dt{constructor(e){N(this,"options");N(this,"stop");var a;this.options=Me(de({},Ti),{emit:e,plugins:[{name:"rrweb/console@1",observer:zi,options:a}]}),this.stop=null}static mockImplementation(e){throw new Error("Method not implemented.")}start(){var e;this.stop=(e=Ce(this.options))!=null?e:null}getMirror(){return Ce.mirror}takeFullSnapshot(){return Ce.takeFullSnapshot()}}class xi{constructor(e){N(this,"recordingManager");N(this,"isRunning");N(this,"events");this.recordingManager=e,this.isRunning=!1,this.events=[]}start(){this.isRunning=!0}handle(e){this.isInitializingEvent(e)?this.events.push(e):this.stop(e)}isInitializingEvent(e){return[2,4].includes(e.type)||this.isSelectionEvent(e)||this.isConsoleEvent(e)}isSelectionEvent(e){return e.type===3&&e.data.source===14}isConsoleEvent(e){return e.type===6}stop(e){this.stamp(this.events,e.timestamp-1),this.publish(...this.events,e),this.events=[],this.isRunning=!1}stamp(e,a){e.forEach(n=>n.timestamp=a)}publish(...e){e.forEach(a=>{this.recordingManager.publishEvent(a)})}}class Ri{constructor(e){N(this,"agent");N(this,"recorder");N(this,"stasher");this.agent=e,this.recorder=new Dt(this.handleEvent.bind(this)),this.stasher=new xi(this)}start(){this.recorder.start()}handleEvent(e){var r;const a=new URL(window.location.href),n=a.origin+a.pathname;if(this.isClick(e)){let i=Ce.mirror.getNode(e.data.id);i&&this.nodeIsInteresting(i)&&(e.conversionData={},e.conversionData.eventType="click",e.conversionData.textContent=i.textContent,e.conversionData.htmlElement=(r=i.nodeName)==null?void 0:r.toLowerCase(),e.conversionData.location=n)}this.isCustom(e)&&(e.conversionData={},e.conversionData.eventType="custom",e.conversionData.customEventType=e.data.tag,e.conversionData.location=n),this.stasher.isRunning?this.stasher.handle(e):this.publishEvent(e)}publishEvent(e){this.agent.sender.handle(e),this.agent.timer&&this.agent.timer.restart()}startRecorderWithStasher(){this.stasher.start(),this.recorder=new Dt(this.handleEvent.bind(this)),this.recorder.start()}isClick(e){return e.type===Ua.IncrementalSnapshot&&e.data.source===Nn.MouseInteraction&&e.data.type===Mn.Click}nodeIsInteresting(e){return e.nodeName==="BUTTON"||e.nodeName==="ANCHOR"}isCustom(e){return e.type===Ua.Custom}}class Ni{constructor(e,a){N(this,"agent");N(this,"MAX_IDLE_TIME");N(this,"timeoutId");this.agent=e,this.MAX_IDLE_TIME=a,this.timeoutId=0}restart(){this.stop(),this.start()}stop(){clearTimeout(this.timeoutId)}start(){this.timeoutId=window.setTimeout(this.agent.handleTimeout.bind(this.agent),this.MAX_IDLE_TIME)}}class Mi{constructor(){N(this,"recordingManager");N(this,"sender");N(this,"endpoint");N(this,"MAX_IDLE_TIME");N(this,"timer");N(this,"sendEvents");this.recordingManager=new Ri(this),this.sender=new Ei(this)}start(n){return M(this,arguments,function*({endpoint:e,sendEvents:a}){this.endpoint=e,this.sendEvents=a,this.MAX_IDLE_TIME=6e4,this.timer=new Ni(this,this.MAX_IDLE_TIME),this.sender.start(),this.recordingManager.start()})}handleTimeout(){this.recordingManager.recorder.stop&&this.recordingManager.recorder.stop(),this.sender.send(),this.recordingManager.startRecorderWithStasher()}takeFullSnapshot(){return this.recordingManager.recorder.takeFullSnapshot()}static handleCustomEvent(e){Ce.addCustomEvent(e,null)}}const Te=class Te{constructor(){N(this,"sessionId",null)}static getInstance(){return Te.instance||(Te.instance=new Te),Te.instance}determineSessionState(e){return!this.sessionId&&e?"new":this.sessionId&&e&&this.sessionId!==e?"changed":this.sessionId===e?"active":"expired"}handleSessionTransition(e,a,n){var r;switch(e){case"new":this.sessionId=a;break;case"changed":this.sessionId=a,(r=n.onSessionChanged)==null||r.call(n)}}updateSession(e,a={}){const n=this.determineSessionState(e);this.handleSessionTransition(n,e,a)}getCurrentSessionId(){return this.sessionId}};N(Te,"instance");let Va=Te;const Bt="0.0.8";exports.Tracker=class e extends Er{constructor(a){super(de({sdk:"web",sdkVersion:Bt},a));N(this,"lastPath","");N(this,"debounceTimer",null);N(this,"agent");N(this,"sessionManager",Va.getInstance());this.options=a,this.agent=new Mi,this.isServer()||(this.setGlobalProperties({__referrer:document.referrer}),this.options.trackOutgoingLinks&&this.trackOutgoingLinks(),this.options.trackScreenViews&&this.trackScreenViews(),this.options.trackAttributes&&this.trackAttributes(),this.options.enableRecording&&typeof window!="undefined"&&window.location.hostname==="localhost"&&this.startRecording())}debounce(a,n){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(a,n)}isServer(){return typeof document=="undefined"}trackOutgoingLinks(){this.isServer()||document.addEventListener("click",a=>{const n=a.target,r=n.closest("a");if(r&&n){const i=r.getAttribute("href");i!=null&&i.startsWith("http")&&super.track("link_out",{href:i,text:r.innerText||r.getAttribute("title")||n.getAttribute("alt")||n.getAttribute("title")})}})}trackScreenViews(){if(this.isServer())return;this.screenView();const a=history.pushState;history.pushState=function(...i){const o=a.apply(this,i);return window.dispatchEvent(new Event("pushstate")),window.dispatchEvent(new Event("locationchange")),o};const n=history.replaceState;history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event("replacestate")),window.dispatchEvent(new Event("locationchange")),o},window.addEventListener("popstate",function(){window.dispatchEvent(new Event("locationchange"))});const r=()=>this.debounce(()=>this.screenView(),100);this.options.trackHashChanges?window.addEventListener("hashchange",r):window.addEventListener("locationchange",r)}trackAttributes(){this.isServer()||document.addEventListener("click",a=>{const n=a.target,r=n.closest("button"),i=n.closest("a"),o=r!=null&&r.getAttribute("data-track")?r:i!=null&&i.getAttribute("data-track")?i:null;if(o){const l={};for(const h of o.attributes)h.name.startsWith("data-")&&h.name!=="data-track"&&(l[s=h.name.replace(/^data-/,""),s.replace(/([-_][a-z])/gi,d=>d.toUpperCase().replace("-","").replace("_",""))]=h.value);const c=o.getAttribute("data-track");c&&super.track(c,l)}var s})}startRecording(){if(this.isServer())return;const{apiUrl:a}=this.options;if(!a)throw new Error("API URL is required");this.agent.start({endpoint:a,sendEvents:this.recordEventsToServer.bind(this)})}screenView(a,n){return M(this,null,function*(){if(this.isServer())return;let r,i;if(typeof a=="string"?(r=a,i=n):(r=window.location.href,i=a),this.lastPath===r)return;this.lastPath=r;const o=Me(de({},i!=null?i:{}),{__path:r,__title:document.title});if(this.options.enableRecording){const s=yield function(l){return M(this,null,function*(){try{yield Jr(l);const c=document.body.cloneNode(!0);return Hr(c),yield Vr(c)}catch(c){console.error("An error occurred:",c)}})}();o.__screenshot=s}it(e.prototype,this,"track").call(this,"screen_view",o)})}recordEventsToServer(a){return M(this,null,function*(){this.record(a,n=>{this.sessionManager.updateSession(n.sessionId,{onSessionChanged:()=>{this.agent.takeFullSnapshot()}})})})}},exports.VERSION=Bt;
30
30
  //# sourceMappingURL=index.cjs.js.map
Binary file