@brainfish-ai/web-tracker 0.0.6-alpha.1 → 0.0.6-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -26,5 +26,5 @@ PERFORMANCE OF THIS SOFTWARE.
26
26
  `),n=[];for(let r=2,i=t.length;r<i;r+=2){const o=e.exec(t[r]);o&&n.push(new _e({fileName:o[2],lineNumber:parseFloat(o[1])}))}return n},parseOpera10:function(a){const e=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,t=a.stacktrace.split(`
27
27
  `),n=[];for(let r=0,i=t.length;r<i;r+=2){const o=e.exec(t[r]);o&&n.push(new _e({functionName:o[3]||void 0,fileName:o[2],lineNumber:parseFloat(o[1])}))}return n},parseOpera11:function(a){return a.stack.split(`
28
28
  `).filter(function(e){return!!e.match(Ii)&&!e.match(/^Error created at/)},this).map(function(e){const t=e.split("@"),n=this.extractLocation(t.pop()),r=(t.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 Si(a){if(!a||!a.outerHTML)return"";let e="";for(;a.parentElement;){let t=a.localName;if(!t)break;t=t.toLowerCase();const n=a.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()===t&&r.push(o)}r.length>1&&(t+=`:eq(${r.indexOf(a)})`),e=t+(e?">"+e:""),a=n}return e}function Vt(a){return Object.prototype.toString.call(a)==="[object Object]"}function Rn(a,e){if(e===0)return!0;const t=Object.keys(a);for(const n of t)if(Vt(a[n])&&Rn(a[n],e-1))return!0;return!1}function Tt(a,e){const t={numOfKeysLimit:50,depthOfLimit:4};Object.assign(t,e);const n=[],r=[];return JSON.stringify(a,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!!(Vt(s)&&Object.keys(s).length>t.numOfKeysLimit||typeof s=="function"||Vt(s)&&Rn(s,t.depthOfLimit))}(o))return function(s){let l=s.toString();return t.stringLengthLimit&&l.length>t.stringLengthLimit&&(l=`${l.slice(0,t.stringLengthLimit)}...`),l}(o);if(o instanceof Event){const s={};for(const l in o){const c=o[l];Array.isArray(c)?s[l]=Si(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 Fa={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 Ai(a,e,t){const n=t?Object.assign({},Fa,t):Fa,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,b=La.parse(u).map(R=>R.toString()),f=[Tt(d,n.stringifyOptions)];a({level:"error",trace:b,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 b=La.parse(new Error).map(R=>R.toString()).splice(1),f=u.map(R=>Tt(R,n.stringifyOptions));o++,o<n.lengthThreshold?a({level:h,trace:b,payload:f}):o===n.lengthThreshold&&a({level:"warn",trace:[],payload:[Tt("The number of log records reached the threshold.")]})}catch(b){d("rrweb logger error:",b,...u)}}):()=>{}}}class zi extends Array{constructor(){super()}isEmpty(){return this.length===0}isFull(){return this.length===10}flush(){return this.splice(0,this.length)}}class ji{constructor(e){N(this,"agent");N(this,"eventBuffer");this.agent=e,this.eventBuffer=new zi}start(){document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.send()})}handle(e){this.eventBuffer.push(e),this.eventBuffer.isFull()&&this.send()}send(){return O(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 Wt=(a=>(a[a.DomContentLoaded=0]="DomContentLoaded",a[a.Load=1]="Load",a[a.FullSnapshot=2]="FullSnapshot",a[a.IncrementalSnapshot=3]="IncrementalSnapshot",a[a.Meta=4]="Meta",a[a.Custom=5]="Custom",a[a.Plugin=6]="Plugin",a))(Wt||{}),Nn=(a=>(a[a.Mutation=0]="Mutation",a[a.MouseMove=1]="MouseMove",a[a.MouseInteraction=2]="MouseInteraction",a[a.Scroll=3]="Scroll",a[a.ViewportResize=4]="ViewportResize",a[a.Input=5]="Input",a[a.TouchMove=6]="TouchMove",a[a.MediaInteraction=7]="MediaInteraction",a[a.StyleSheetRule=8]="StyleSheetRule",a[a.CanvasMutation=9]="CanvasMutation",a[a.Font=10]="Font",a[a.Log=11]="Log",a[a.Drag=12]="Drag",a[a.StyleDeclaration=13]="StyleDeclaration",a[a.Selection=14]="Selection",a[a.AdoptedStyleSheet=15]="AdoptedStyleSheet",a[a.CustomElement=16]="CustomElement",a))(Nn||{}),Mn=(a=>(a[a.MouseUp=0]="MouseUp",a[a.MouseDown=1]="MouseDown",a[a.Click=2]="Click",a[a.ContextMenu=3]="ContextMenu",a[a.DblClick=4]="DblClick",a[a.Focus=5]="Focus",a[a.Blur=6]="Blur",a[a.TouchStart=7]="TouchStart",a[a.TouchMove_Departed=8]="TouchMove_Departed",a[a.TouchEnd=9]="TouchEnd",a[a.TouchCancel=10]="TouchCancel",a))(Mn||{});const Ei={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 Da{constructor(e){N(this,"options");N(this,"stop");var t;this.options=Me(de({},Ei),{emit:e,plugins:[{name:"rrweb/console@1",observer:Ai,options:t}]}),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 Ti{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,t){e.forEach(n=>n.timestamp=t)}publish(...e){e.forEach(t=>{this.recordingManager.publishEvent(t)})}}class xi{constructor(e){N(this,"agent");N(this,"recorder");N(this,"stasher");this.agent=e,this.recorder=new Da(this.handleEvent.bind(this)),this.stasher=new Ti(this)}start(){this.recorder.start()}handleEvent(e){var r;const t=new URL(window.location.href),n=t.origin+t.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 Da(this.handleEvent.bind(this)),this.recorder.start()}isClick(e){return e.type===Wt.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===Wt.Custom}}class Ri{constructor(e,t){N(this,"agent");N(this,"MAX_IDLE_TIME");N(this,"timeoutId");this.agent=e,this.MAX_IDLE_TIME=t,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 Ni{constructor(){N(this,"recordingManager");N(this,"sender");N(this,"endpoint");N(this,"MAX_IDLE_TIME");N(this,"timer");N(this,"sendEvents");this.recordingManager=new xi(this),this.sender=new ji(this)}start(n){return O(this,arguments,function*({endpoint:e,sendEvents:t}){this.endpoint=e,this.sendEvents=t,this.MAX_IDLE_TIME=6e4,this.timer=new Ri(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,t,n){var r;switch(e){case"new":this.sessionId=t;break;case"changed":this.sessionId=t,(r=n.onSessionChanged)==null||r.call(n)}}updateSession(e,t={}){const n=this.determineSessionState(e);this.handleSessionTransition(n,e,t)}getCurrentSessionId(){return this.sessionId}};N(Te,"instance");let Ut=Te;const Ba="0.0.6-alpha.1";exports.Tracker=class e extends Er{constructor(t){super(de({sdk:"web",sdkVersion:Ba},t));N(this,"lastPath","");N(this,"debounceTimer",null);N(this,"agent");N(this,"sessionManager",Ut.getInstance());this.options=t,this.agent=new Ni,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(t,n){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(t,n)}isServer(){return typeof document=="undefined"}trackOutgoingLinks(){this.isServer()||document.addEventListener("click",t=>{const n=t.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 t=history.pushState;history.pushState=function(...i){const o=t.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(),50);this.options.trackHashChanges?window.addEventListener("hashchange",r):window.addEventListener("locationchange",r)}trackAttributes(){this.isServer()||document.addEventListener("click",t=>{const n=t.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:t}=this.options;if(!t)throw new Error("API URL is required");this.agent.start({endpoint:t,sendEvents:this.recordEventsToServer.bind(this)})}screenView(t,n){return O(this,null,function*(){if(this.isServer())return;let r,i;if(typeof t=="string"?(r=t,i=n):(r=window.location.href,i=t),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(){return O(this,null,function*(){try{yield new Promise(c=>{document.readyState==="complete"?c(null):window.addEventListener("load",c)});const l=document.body.cloneNode(!0);return Hr(l),yield Ur(l)}catch(l){console.error("An error occurred:",l)}})}();o.__screenshot=s}ia(e.prototype,this,"track").call(this,"screen_view",o)})}recordEventsToServer(t){return O(this,null,function*(){this.record(t,n=>{this.sessionManager.updateSession(n.sessionId,{onSessionChanged:()=>{this.agent.takeFullSnapshot()}})})})}},exports.VERSION=Ba;
29
+ End of stack for Error object`:o.name+": "+o.message:o})}const Fa={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 Ai(a,e,t){const n=t?Object.assign({},Fa,t):Fa,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,b=La.parse(u).map(R=>R.toString()),f=[Tt(d,n.stringifyOptions)];a({level:"error",trace:b,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 b=La.parse(new Error).map(R=>R.toString()).splice(1),f=u.map(R=>Tt(R,n.stringifyOptions));o++,o<n.lengthThreshold?a({level:h,trace:b,payload:f}):o===n.lengthThreshold&&a({level:"warn",trace:[],payload:[Tt("The number of log records reached the threshold.")]})}catch(b){d("rrweb logger error:",b,...u)}}):()=>{}}}class zi extends Array{constructor(){super()}isEmpty(){return this.length===0}isFull(){return this.length===10}flush(){return this.splice(0,this.length)}}class ji{constructor(e){N(this,"agent");N(this,"eventBuffer");this.agent=e,this.eventBuffer=new zi}start(){document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.send()})}handle(e){this.eventBuffer.push(e),this.eventBuffer.isFull()&&this.send()}send(){return O(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 Wt=(a=>(a[a.DomContentLoaded=0]="DomContentLoaded",a[a.Load=1]="Load",a[a.FullSnapshot=2]="FullSnapshot",a[a.IncrementalSnapshot=3]="IncrementalSnapshot",a[a.Meta=4]="Meta",a[a.Custom=5]="Custom",a[a.Plugin=6]="Plugin",a))(Wt||{}),Nn=(a=>(a[a.Mutation=0]="Mutation",a[a.MouseMove=1]="MouseMove",a[a.MouseInteraction=2]="MouseInteraction",a[a.Scroll=3]="Scroll",a[a.ViewportResize=4]="ViewportResize",a[a.Input=5]="Input",a[a.TouchMove=6]="TouchMove",a[a.MediaInteraction=7]="MediaInteraction",a[a.StyleSheetRule=8]="StyleSheetRule",a[a.CanvasMutation=9]="CanvasMutation",a[a.Font=10]="Font",a[a.Log=11]="Log",a[a.Drag=12]="Drag",a[a.StyleDeclaration=13]="StyleDeclaration",a[a.Selection=14]="Selection",a[a.AdoptedStyleSheet=15]="AdoptedStyleSheet",a[a.CustomElement=16]="CustomElement",a))(Nn||{}),Mn=(a=>(a[a.MouseUp=0]="MouseUp",a[a.MouseDown=1]="MouseDown",a[a.Click=2]="Click",a[a.ContextMenu=3]="ContextMenu",a[a.DblClick=4]="DblClick",a[a.Focus=5]="Focus",a[a.Blur=6]="Blur",a[a.TouchStart=7]="TouchStart",a[a.TouchMove_Departed=8]="TouchMove_Departed",a[a.TouchEnd=9]="TouchEnd",a[a.TouchCancel=10]="TouchCancel",a))(Mn||{});const Ei={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 Da{constructor(e){N(this,"options");N(this,"stop");var t;this.options=Me(de({},Ei),{emit:e,plugins:[{name:"rrweb/console@1",observer:Ai,options:t}]}),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 Ti{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,t){e.forEach(n=>n.timestamp=t)}publish(...e){e.forEach(t=>{this.recordingManager.publishEvent(t)})}}class xi{constructor(e){N(this,"agent");N(this,"recorder");N(this,"stasher");this.agent=e,this.recorder=new Da(this.handleEvent.bind(this)),this.stasher=new Ti(this)}start(){this.recorder.start()}handleEvent(e){var r;const t=new URL(window.location.href),n=t.origin+t.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 Da(this.handleEvent.bind(this)),this.recorder.start()}isClick(e){return e.type===Wt.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===Wt.Custom}}class Ri{constructor(e,t){N(this,"agent");N(this,"MAX_IDLE_TIME");N(this,"timeoutId");this.agent=e,this.MAX_IDLE_TIME=t,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 Ni{constructor(){N(this,"recordingManager");N(this,"sender");N(this,"endpoint");N(this,"MAX_IDLE_TIME");N(this,"timer");N(this,"sendEvents");this.recordingManager=new xi(this),this.sender=new ji(this)}start(n){return O(this,arguments,function*({endpoint:e,sendEvents:t}){this.endpoint=e,this.sendEvents=t,this.MAX_IDLE_TIME=6e4,this.timer=new Ri(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,t,n){var r;switch(e){case"new":this.sessionId=t;break;case"changed":this.sessionId=t,(r=n.onSessionChanged)==null||r.call(n)}}updateSession(e,t={}){const n=this.determineSessionState(e);this.handleSessionTransition(n,e,t)}getCurrentSessionId(){return this.sessionId}};N(Te,"instance");let Ut=Te;const Ba="0.0.6-beta.1";exports.Tracker=class e extends Er{constructor(t){super(de({sdk:"web",sdkVersion:Ba},t));N(this,"lastPath","");N(this,"debounceTimer",null);N(this,"agent");N(this,"sessionManager",Ut.getInstance());this.options=t,this.agent=new Ni,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(t,n){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(t,n)}isServer(){return typeof document=="undefined"}trackOutgoingLinks(){this.isServer()||document.addEventListener("click",t=>{const n=t.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 t=history.pushState;history.pushState=function(...i){const o=t.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(),50);this.options.trackHashChanges?window.addEventListener("hashchange",r):window.addEventListener("locationchange",r)}trackAttributes(){this.isServer()||document.addEventListener("click",t=>{const n=t.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:t}=this.options;if(!t)throw new Error("API URL is required");this.agent.start({endpoint:t,sendEvents:this.recordEventsToServer.bind(this)})}screenView(t,n){return O(this,null,function*(){if(this.isServer())return;let r,i;if(typeof t=="string"?(r=t,i=n):(r=window.location.href,i=t),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(){return O(this,null,function*(){try{yield new Promise(c=>{document.readyState==="complete"?c(null):window.addEventListener("load",c)});const l=document.body.cloneNode(!0);return Hr(l),yield Ur(l)}catch(l){console.error("An error occurred:",l)}})}();o.__screenshot=s}ia(e.prototype,this,"track").call(this,"screen_view",o)})}recordEventsToServer(t){return O(this,null,function*(){this.record(t,n=>{this.sessionManager.updateSession(n.sessionId,{onSessionChanged:()=>{this.agent.takeFullSnapshot()}})})})}},exports.VERSION=Ba;
30
30
  //# sourceMappingURL=index.cjs.js.map
Binary file