@grainql/analytics-web 3.1.1 → 3.2.0
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/cjs/heatmap-tracking.d.ts +38 -0
- package/dist/cjs/heatmap-tracking.d.ts.map +1 -1
- package/dist/cjs/heatmap-tracking.js +266 -5
- package/dist/cjs/heatmap-tracking.js.map +1 -1
- package/dist/cjs/page-tracking.d.ts.map +1 -1
- package/dist/cjs/page-tracking.js +6 -0
- package/dist/cjs/page-tracking.js.map +1 -1
- package/dist/cjs/types/heatmap-tracking.d.ts +9 -0
- package/dist/cjs/types/heatmap-tracking.d.ts.map +1 -1
- package/dist/esm/heatmap-tracking.d.ts +38 -0
- package/dist/esm/heatmap-tracking.d.ts.map +1 -1
- package/dist/esm/heatmap-tracking.js +233 -5
- package/dist/esm/heatmap-tracking.js.map +1 -1
- package/dist/esm/page-tracking.d.ts.map +1 -1
- package/dist/esm/page-tracking.js +6 -0
- package/dist/esm/page-tracking.js.map +1 -1
- package/dist/esm/types/heatmap-tracking.d.ts +9 -0
- package/dist/esm/types/heatmap-tracking.d.ts.map +1 -1
- package/dist/heatmap-tracking.d.ts +38 -0
- package/dist/heatmap-tracking.d.ts.map +1 -1
- package/dist/heatmap-tracking.js +266 -5
- package/dist/index.global.dev.js +5805 -53
- package/dist/index.global.dev.js.map +4 -4
- package/dist/index.global.js +33 -7
- package/dist/index.global.js.map +4 -4
- package/dist/page-tracking.d.ts.map +1 -1
- package/dist/page-tracking.js +6 -0
- package/dist/types/heatmap-tracking.d.ts +9 -0
- package/dist/types/heatmap-tracking.d.ts.map +1 -1
- package/package.json +8 -2
package/dist/index.global.js
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
|
-
/* Grain Analytics Web SDK v3.
|
|
2
|
-
"use strict";var Grain=(()=>{var _=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var ue=Object.prototype.hasOwnProperty;var g=(s,e)=>()=>(s&&(e=s(s=0)),e);var A=(s,e)=>{for(var t in e)_(s,t,{get:e[t],enumerable:!0})},de=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of le(e))!ue.call(s,r)&&r!==t&&_(s,r,{get:()=>e[r],enumerable:!(i=ce(e,r))||i.enumerable});return s};var he=s=>de(_({},"__esModule",{value:!0}),s);var Ae,f,L=g(()=>{"use strict";Ae={maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4},f=class{constructor(e,t={}){this.isDestroyed=!1;this.isPageVisible=!0;this.visibilityChangeHandler=null;this.sectionStates=new Map;this.lastFilterReason=null;this.activityDetector=e,this.options={...Ae,...t,debug:t.debug??!1},this.setupPageVisibilityTracking()}setupPageVisibilityTracking(){typeof document>"u"||(this.isPageVisible=document.visibilityState==="visible",this.visibilityChangeHandler=()=>{let e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.log("Page hidden - tracking paused"):this.isPageVisible&&!e&&(this.log("Page visible - tracking resumed"),this.resetAllSections())},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}shouldTrack(){return this.isPageVisible?this.activityDetector.isActive(this.options.idleThreshold)?(this.lastFilterReason=null,!0):(this.lastFilterReason="user_idle",!1):(this.lastFilterReason="page_hidden",!1)}shouldTrackSection(e,t){if(!this.shouldTrack())return{shouldTrack:!1,reason:this.lastFilterReason||"global_policy"};let i=this.sectionStates.get(e);i||(i={sectionName:e,currentDuration:0,lastScrollPosition:t,lastResetTime:Date.now()},this.sectionStates.set(e,i));let r=Math.abs(t-i.lastScrollPosition);return r>=this.options.minScrollDistance?(this.log(`Section "${e}": Attention reset due to ${Math.round(r)}px scroll`),i.currentDuration=0,i.lastScrollPosition=t,i.lastResetTime=Date.now(),{shouldTrack:!0,resetAttention:!0}):i.currentDuration>=this.options.maxSectionDuration?{shouldTrack:!1,reason:"max_duration_reached"}:{shouldTrack:!0}}updateSectionDuration(e,t){let i=this.sectionStates.get(e);i&&(i.currentDuration+=t,i.currentDuration>=this.options.maxSectionDuration&&this.log(`Section "${e}": Max duration cap reached (${i.currentDuration}ms)`))}resetSection(e){let t=this.sectionStates.get(e);t&&(this.log(`Section "${e}": Attention reset (section exit)`),t.currentDuration=0,t.lastResetTime=Date.now())}resetAllSections(){this.log("Resetting all section attention states");for(let e of this.sectionStates.values())e.currentDuration=0,e.lastResetTime=Date.now()}getSectionState(e){return this.sectionStates.get(e)}getLastFilterReason(){return this.lastFilterReason}shouldTrackScroll(e,t){return this.shouldTrack()?Math.abs(t-e)<10?{shouldTrack:!1,reason:"scroll_too_small"}:{shouldTrack:!0}:{shouldTrack:!1,reason:this.lastFilterReason||"global_policy"}}getPolicies(){return{maxSectionDuration:this.options.maxSectionDuration,minScrollDistance:this.options.minScrollDistance,idleThreshold:this.options.idleThreshold}}getTrackingState(){return{isPageVisible:this.isPageVisible,isUserActive:this.activityDetector.isActive(this.options.idleThreshold),timeSinceLastActivity:this.activityDetector.getTimeSinceLastActivity(),activeSections:this.sectionStates.size}}log(...e){this.options.debug&&console.log("[AttentionQuality]",...e)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.visibilityChangeHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null),this.sectionStates.clear())}}});function Se(s){if(s)return s.replace(/[\u{1F300}-\u{1F9FF}]/gu,"").replace(/[\u{1F600}-\u{1F64F}]/gu,"").replace(/[\u{1F680}-\u{1F6FF}]/gu,"").replace(/[\u{2600}-\u{26FF}]/gu,"").replace(/[\u{2700}-\u{27BF}]/gu,"").replace(/[\u{1F900}-\u{1F9FF}]/gu,"").replace(/[\u{1F1E0}-\u{1F1FF}]/gu,"").replace(/[\u{200D}]/gu,"").replace(/[\u{FE0F}]/gu,"").replace(/[\u{20E3}]/gu,"").trim()}function x(s,e=100){if(!s)return;let t=Se(s);if(t)return t.substring(0,e)||void 0}var U=g(()=>{"use strict"});var Z={};A(Z,{HeatmapTrackingManager:()=>N});var Ee,N,ee=g(()=>{"use strict";L();U();Ee={scrollDebounceDelay:100,batchDelay:2e3,maxBatchSize:20,debug:!1},N=class{constructor(e,t={}){this.isDestroyed=!1;this.currentScrollState=null;this.pendingClicks=[];this.pendingScrolls=[];this.scrollDebounceTimer=null;this.batchTimer=null;this.scrollTrackingTimer=null;this.periodicScrollTimer=null;this.lastScrollPosition=0;this.lastScrollTime=Date.now();this.SPLIT_DURATION=3e3;this.tracker=e,this.options={...Ee,...t},this.attentionQuality=new f(e.getActivityDetector(),{maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4,debug:this.options.debug}),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0))}initialize(){this.isDestroyed||(this.log("Initializing heatmap tracking"),this.setupClickTracking(),this.setupScrollTracking(),this.startScrollTracking(),this.setupUnloadHandler())}setupClickTracking(){if(typeof document>"u")return;let e=t=>{this.isDestroyed||this.handleClick(t)};document.addEventListener("click",e,{passive:!0,capture:!0})}setupScrollTracking(){if(typeof window>"u")return;let e=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.handleScroll(),this.scrollDebounceTimer=null},this.options.scrollDebounceDelay)};window.addEventListener("scroll",e,{passive:!0})}startScrollTracking(){typeof window>"u"||(this.updateScrollState(),this.scrollTrackingTimer=window.setInterval(()=>{this.isDestroyed||this.updateScrollState()},500),this.startPeriodicScrollTracking())}startPeriodicScrollTracking(){typeof window>"u"||(this.periodicScrollTimer=window.setInterval(()=>{if(this.isDestroyed||!this.currentScrollState)return;if(!this.attentionQuality.shouldTrack()){this.log("Scroll tracking paused:",this.attentionQuality.getLastFilterReason());return}let e=Date.now(),t=e-this.currentScrollState.entryTime;if(t>1e3){let i=window.scrollY||window.pageYOffset,r=window.innerHeight,n=document.documentElement.scrollHeight,a=`viewport_section_${this.currentScrollState.viewportSection}`,o=this.attentionQuality.shouldTrackSection(a,i);if(o.resetAttention){this.log(`Viewport section ${this.currentScrollState.viewportSection}: Attention reset`),this.currentScrollState.entryTime=e;return}if(!o.shouldTrack){this.log(`Viewport section ${this.currentScrollState.viewportSection}: ${o.reason}`);return}let l={pageUrl:window.location.href,viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:i,durationMs:t,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:e,pageHeight:n,viewportHeight:r};this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:l.pageUrl,viewport_section:l.viewportSection,scroll_depth_px:l.scrollDepthPx,duration_ms:l.durationMs,entry_timestamp:l.entryTimestamp,exit_timestamp:l.exitTimestamp,page_height:l.pageHeight,viewport_height:l.viewportHeight,is_split:!0},{flush:!0}),this.attentionQuality.updateSectionDuration(a,t),this.currentScrollState.entryTime=e}},this.SPLIT_DURATION))}setupUnloadHandler(){if(typeof window>"u")return;let e=()=>{if(this.currentScrollState){let t=Date.now(),i=t-this.currentScrollState.entryTime;if(i>100){let r={pageUrl:window.location.href,viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:this.currentScrollState.scrollDepthPx,durationMs:i,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:t,pageHeight:document.documentElement.scrollHeight,viewportHeight:window.innerHeight};this.pendingScrolls.push(r)}}this.flushPendingEventsWithBeacon()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}handleClick(e){let t=e.target;if(!t)return;let i=window.location.href,r=this.generateXPath(t),n=Math.round(e.clientX),a=Math.round(e.clientY),o=Math.round(e.pageX),l=Math.round(e.pageY),c=t.tagName?.toLowerCase()||"unknown",d=x(t.textContent),u={pageUrl:i,xpath:r,viewportX:n,viewportY:a,pageX:o,pageY:l,elementTag:c,elementText:d||void 0,timestamp:Date.now()};t instanceof HTMLAnchorElement&&t.href?this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:u.pageUrl,xpath:u.xpath,viewport_x:u.viewportX,viewport_y:u.viewportY,page_x:u.pageX,page_y:u.pageY,element_tag:u.elementTag,element_text:u.elementText,timestamp:u.timestamp},{flush:!0}):(this.pendingClicks.push(u),this.considerBatchFlush())}handleScroll(){this.updateScrollState()}updateScrollState(){if(typeof window>"u")return;let e=Date.now(),t=window.scrollY||window.pageYOffset,i=window.innerHeight,r=document.documentElement.scrollHeight,n=Math.floor(t/i);if(this.currentScrollState&&this.currentScrollState.viewportSection!==n){let a=e-this.currentScrollState.entryTime;if(a>100){let l={pageUrl:window.location.href,viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:this.currentScrollState.scrollDepthPx,durationMs:a,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:e,pageHeight:r,viewportHeight:i};this.pendingScrolls.push(l)}let o=`viewport_section_${this.currentScrollState.viewportSection}`;this.attentionQuality.resetSection(o)}(!this.currentScrollState||this.currentScrollState.viewportSection!==n)&&(this.currentScrollState={viewportSection:n,entryTime:e,scrollDepthPx:t}),this.lastScrollPosition=t,this.lastScrollTime=e,this.considerBatchFlush()}generateXPath(e){if(!e)return"";if(e.id)return`//*[@id="${e.id}"]`;let t=[],i=e;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let r=0,n=i;for(;n;)n=n.previousElementSibling,n&&n.nodeName===i.nodeName&&r++;let a=i.nodeName.toLowerCase(),o=r>0?`[${r+1}]`:"";t.unshift(`${a}${o}`),i=i.parentElement}return t.length?`/${t.join("/")}`:""}considerBatchFlush(){let e=this.pendingClicks.length+this.pendingScrolls.length;if(e>=this.options.maxBatchSize){this.flushPendingEvents();return}this.batchTimer===null&&e>0&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents(),this.batchTimer=null},this.options.batchDelay))}flushPendingEvents(){if(!this.isDestroyed){if(this.pendingClicks.length>0){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:e.pageUrl,xpath:e.xpath,viewport_x:e.viewportX,viewport_y:e.viewportY,page_x:e.pageX,page_y:e.pageY,element_tag:e.elementTag,element_text:e.elementText,timestamp:e.timestamp});this.pendingClicks=[]}if(this.pendingScrolls.length>0){for(let e of this.pendingScrolls)this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:e.pageUrl,viewport_section:e.viewportSection,scroll_depth_px:e.scrollDepthPx,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight});this.pendingScrolls=[]}this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null)}}flushPendingEventsWithBeacon(){if(this.pendingClicks.length>0){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:e.pageUrl,xpath:e.xpath,viewport_x:e.viewportX,viewport_y:e.viewportY,page_x:e.pageX,page_y:e.pageY,element_tag:e.elementTag,element_text:e.elementText,timestamp:e.timestamp},{flush:!0});this.pendingClicks=[]}if(this.pendingScrolls.length>0){for(let e of this.pendingScrolls)this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:e.pageUrl,viewport_section:e.viewportSection,scroll_depth_px:e.scrollDepthPx,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight},{flush:!0});this.pendingScrolls=[]}}log(...e){this.options.debug&&this.tracker.log("[Heatmap Tracking]",...e)}destroy(){this.isDestroyed=!0,this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.scrollTrackingTimer!==null&&(clearInterval(this.scrollTrackingTimer),this.scrollTrackingTimer=null),this.periodicScrollTimer!==null&&(clearInterval(this.periodicScrollTimer),this.periodicScrollTimer=null),this.attentionQuality.destroy(),this.flushPendingEvents()}}});var te={};A(te,{InteractionTrackingManager:()=>H});var H,ie=g(()=>{"use strict";U();H=class{constructor(e,t,i={}){this.isDestroyed=!1;this.attachedListeners=new Map;this.xpathCache=new Map;this.mutationObserver=null;this.mutationDebounceTimer=null;this.tracker=e,this.interactions=t,this.config={debug:i.debug??!1,enableMutationObserver:i.enableMutationObserver??!0,mutationDebounceDelay:i.mutationDebounceDelay??500,tenantId:i.tenantId,apiUrl:i.apiUrl},typeof window<"u"&&typeof document<"u"&&(this.config.tenantId&&this.config.apiUrl?this.fetchAndMergeTrackers().then(()=>{this.attachAllListeners()}):document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.attachAllListeners()):setTimeout(()=>this.attachAllListeners(),0),this.config.enableMutationObserver&&this.setupMutationObserver())}async fetchAndMergeTrackers(){if(!(!this.config.tenantId||!this.config.apiUrl))try{let e=typeof window<"u"?window.location.href:"",t=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/trackers?url=${encodeURIComponent(e)}`;this.log("Fetching trackers from:",t);let i=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok){this.log("Failed to fetch trackers:",i.status);return}let r=await i.json();if(r.trackers&&Array.isArray(r.trackers)){this.log("Fetched",r.trackers.length,"trackers");let n=r.trackers.map(a=>({eventName:a.eventName,selector:a.selector,priority:5,label:a.eventName,description:`Tracker: ${a.eventName}`}));this.interactions=[...n,...this.interactions],this.log("Merged trackers, total interactions:",this.interactions.length)}}catch(e){this.log("Error fetching trackers:",e)}}attachAllListeners(){if(!this.isDestroyed){this.log("Attaching interaction listeners");for(let e of this.interactions)this.attachInteractionListener(e)}}attachInteractionListener(e){if(this.isDestroyed)return;let t=this.findElementByXPath(e.selector);if(!t){this.log("Element not found for interaction:",e.eventName,"selector:",e.selector);return}if(this.attachedListeners.has(t)){this.log("Listeners already attached for element:",t);return}let i=[],r=n=>this.handleInteractionClick(e,n);if(t.addEventListener("click",r,{passive:!0}),i.push({event:"click",handler:r}),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){let n=a=>this.handleInteractionFocus(e,a);t.addEventListener("focus",n,{passive:!0}),i.push({event:"focus",handler:n})}this.attachedListeners.set(t,i)}handleInteractionClick(e,t){if(this.isDestroyed)return;let i=t.target,r=i instanceof HTMLAnchorElement&&i.href,n={interaction_type:"click",interaction_label:e.label,interaction_description:e.description,interaction_priority:e.priority,element_tag:i.tagName?.toLowerCase(),element_text:x(i.textContent),element_id:i.id||void 0,element_class:i.className||void 0,...r&&{href:i.href},timestamp:Date.now()},a=this.tracker.track(e.eventName,n,{flush:!0});a instanceof Promise&&a.catch(o=>{this.log("Failed to track click:",o)})}handleInteractionFocus(e,t){if(this.isDestroyed)return;let i=t.target;this.tracker.track(e.eventName,{interaction_type:"focus",interaction_label:e.label,interaction_description:e.description,interaction_priority:e.priority,element_tag:i.tagName?.toLowerCase(),element_id:i.id||void 0,element_class:i.className||void 0,timestamp:Date.now()})}findElementByXPath(e){if(this.xpathCache.has(e)){let t=this.xpathCache.get(e);if(t&&document.contains(t))return t;this.xpathCache.delete(e)}try{let t=e;e.startsWith("xpath=")&&(t=e.substring(6));let r=document.evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return r&&this.xpathCache.set(e,r),r}catch(t){return this.log("Error evaluating XPath:",e,t),null}}setupMutationObserver(){if(typeof MutationObserver>"u"){this.log("MutationObserver not supported");return}this.mutationObserver=new MutationObserver(e=>{this.mutationDebounceTimer!==null&&clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=window.setTimeout(()=>{this.handleMutations(e),this.mutationDebounceTimer=null},this.config.mutationDebounceDelay)}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Mutation observer setup")}handleMutations(e){if(this.isDestroyed)return;this.xpathCache.clear();let t=new Set;for(let i of e)i.removedNodes.forEach(r=>{r instanceof Element&&(t.add(r),this.attachedListeners.forEach((n,a)=>{r.contains(a)&&t.add(a)}))});t.forEach(i=>{this.detachListeners(i)}),this.attachAllListeners()}detachListeners(e){let t=this.attachedListeners.get(e);t&&(t.forEach(({event:i,handler:r})=>{e.removeEventListener(i,r)}),this.attachedListeners.delete(e))}log(...e){this.config.debug&&console.log("[InteractionTracking]",...e)}updateInteractions(e){this.isDestroyed||(this.log("Updating interactions configuration"),this.attachedListeners.forEach((t,i)=>{this.detachListeners(i)}),this.xpathCache.clear(),this.interactions=e,this.attachAllListeners())}destroy(){this.isDestroyed||(this.log("Destroying interaction tracking manager"),this.isDestroyed=!0,this.mutationDebounceTimer!==null&&(clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.attachedListeners.forEach((e,t)=>{this.detachListeners(t)}),this.attachedListeners.clear(),this.xpathCache.clear())}}});var re={};A(re,{SectionTrackingManager:()=>O});var Te,O,ne=g(()=>{"use strict";L();Te={minDwellTime:1e3,scrollVelocityThreshold:500,intersectionThreshold:.1,debounceDelay:100,batchDelay:2e3,debug:!1},O=class{constructor(e,t,i={}){this.isDestroyed=!1;this.sectionStates=new Map;this.intersectionObserver=null;this.xpathCache=new Map;this.lastScrollPosition=0;this.lastScrollTime=Date.now();this.scrollVelocity=0;this.scrollDebounceTimer=null;this.pendingEvents=[];this.batchTimer=null;this.sectionTimers=new Map;this.SPLIT_DURATION=3e3;this.tracker=e,this.sections=t,this.options={...Te,...i},this.attentionQuality=new f(e.getActivityDetector(),{maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4,debug:this.options.debug}),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0))}initialize(){this.isDestroyed||(this.log("Initializing section tracking"),this.setupIntersectionObserver(),this.setupScrollListener(),this.initializeSections())}setupIntersectionObserver(){if(typeof IntersectionObserver>"u"){this.log("IntersectionObserver not supported");return}this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(t=>{this.handleIntersection(t)})},{threshold:[0,.1,.25,.5,.75,1],rootMargin:"0px"}),this.log("IntersectionObserver created")}setupScrollListener(){if(typeof window>"u")return;let e=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.updateScrollVelocity(),this.scrollDebounceTimer=null},this.options.debounceDelay)};window.addEventListener("scroll",e,{passive:!0}),this.log("Scroll listener attached")}initializeSections(){for(let e of this.sections){let t=this.findElementByXPath(e.selector);if(!t){this.log("Section element not found:",e.sectionName,"selector:",e.selector);continue}let i={element:t,config:e,entryTime:null,exitTime:null,isVisible:!1,lastScrollPosition:window.scrollY,lastScrollTime:Date.now(),entryScrollSpeed:0,exitScrollSpeed:0,maxVisibleArea:0};this.sectionStates.set(e.sectionName,i),this.intersectionObserver&&this.intersectionObserver.observe(t)}}handleIntersection(e){if(this.isDestroyed)return;let t=Array.from(this.sectionStates.values()).find(n=>n.element===e.target);if(!t)return;let i=e.isIntersecting&&e.intersectionRatio>=this.options.intersectionThreshold,r=e.intersectionRatio;r>t.maxVisibleArea&&(t.maxVisibleArea=r),i&&!t.isVisible?this.handleSectionEntry(t):!i&&t.isVisible&&this.handleSectionExit(t),t.isVisible=i}handleSectionEntry(e){e.entryTime=Date.now(),e.entryScrollSpeed=this.scrollVelocity,e.lastScrollPosition=window.scrollY,e.lastScrollTime=Date.now(),e.maxVisibleArea=0,this.startPeriodicTracking(e)}startPeriodicTracking(e){this.stopPeriodicTracking(e.config.sectionName);let t=window.setInterval(()=>{if(this.isDestroyed||!e.isVisible||e.entryTime===null){this.stopPeriodicTracking(e.config.sectionName);return}let i=Date.now(),r=i-e.entryTime;if(r>=this.options.minDwellTime){let n=window.scrollY,a=this.attentionQuality.shouldTrackSection(e.config.sectionName,n);if(a.resetAttention){this.log(`Section "${e.config.sectionName}": Attention reset, restarting timer`),e.entryTime=i,e.entryScrollSpeed=this.scrollVelocity;return}if(!a.shouldTrack){this.log(`Section "${e.config.sectionName}": Tracking paused - ${a.reason}`);return}let o={sectionName:e.config.sectionName,sectionType:e.config.sectionType,entryTime:e.entryTime,exitTime:i,duration:r,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollDepth:this.calculateScrollDepth(),visibleAreaPercentage:Math.round(e.maxVisibleArea*100),scrollSpeedAtEntry:e.entryScrollSpeed,scrollSpeedAtExit:this.scrollVelocity};this.shouldTrackSection(o)&&(this.tracker.trackSystemEvent("_grain_section_view",{section_name:o.sectionName,section_type:o.sectionType,duration_ms:o.duration,viewport_width:o.viewportWidth,viewport_height:o.viewportHeight,scroll_depth_percent:o.scrollDepth,visible_area_percent:o.visibleAreaPercentage,scroll_speed_entry:Math.round(o.scrollSpeedAtEntry||0),scroll_speed_exit:Math.round(o.scrollSpeedAtExit||0),entry_timestamp:o.entryTime,exit_timestamp:o.exitTime,is_split:!0}),this.attentionQuality.updateSectionDuration(e.config.sectionName,r),e.entryTime=i,e.entryScrollSpeed=this.scrollVelocity)}},this.SPLIT_DURATION);this.sectionTimers.set(e.config.sectionName,t)}stopPeriodicTracking(e){let t=this.sectionTimers.get(e);t!==void 0&&(clearInterval(t),this.sectionTimers.delete(e))}handleSectionExit(e){if(this.stopPeriodicTracking(e.config.sectionName),this.attentionQuality.resetSection(e.config.sectionName),e.entryTime===null)return;e.exitTime=Date.now(),e.exitScrollSpeed=this.scrollVelocity;let t=e.exitTime-e.entryTime,i={sectionName:e.config.sectionName,sectionType:e.config.sectionType,entryTime:e.entryTime,exitTime:e.exitTime,duration:t,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollDepth:this.calculateScrollDepth(),visibleAreaPercentage:Math.round(e.maxVisibleArea*100),scrollSpeedAtEntry:e.entryScrollSpeed,scrollSpeedAtExit:e.exitScrollSpeed};this.shouldTrackSection(i)?this.queueSectionView(i):this.log("Section view filtered out:",e.config.sectionName,"duration:",t),e.entryTime=null}updateScrollVelocity(){let e=Date.now(),t=window.scrollY,i=e-this.lastScrollTime,r=Math.abs(t-this.lastScrollPosition);i>0&&(this.scrollVelocity=r/i*1e3),this.lastScrollPosition=t,this.lastScrollTime=e}calculateScrollDepth(){if(typeof window>"u"||typeof document>"u")return 0;let e=window.innerHeight,t=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),i=window.scrollY,r=t-e;return r<=0?100:Math.round(i/r*100)}shouldTrackSection(e){return!(e.duration<this.options.minDwellTime||(e.scrollSpeedAtEntry+e.scrollSpeedAtExit)/2>this.options.scrollVelocityThreshold*2||e.visibleAreaPercentage<10)}queueSectionView(e){this.pendingEvents.push(e),this.batchTimer===null&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents()},this.options.batchDelay))}flushPendingEvents(){if(!(this.isDestroyed||this.pendingEvents.length===0)){for(let e of this.pendingEvents)this.tracker.trackSystemEvent("_grain_section_view",{section_name:e.sectionName,section_type:e.sectionType,duration_ms:e.duration,viewport_width:e.viewportWidth,viewport_height:e.viewportHeight,scroll_depth_percent:e.scrollDepth,visible_area_percent:e.visibleAreaPercentage,scroll_speed_entry:Math.round(e.scrollSpeedAtEntry||0),scroll_speed_exit:Math.round(e.scrollSpeedAtExit||0),entry_timestamp:e.entryTime,exit_timestamp:e.exitTime});this.pendingEvents=[],this.batchTimer=null}}findElementByXPath(e){if(this.xpathCache.has(e)){let t=this.xpathCache.get(e);if(t&&document.contains(t))return t;this.xpathCache.delete(e)}try{let t=e;e.startsWith("xpath=")&&(t=e.substring(6));let r=document.evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return r&&this.xpathCache.set(e,r),r}catch(t){return this.log("Error evaluating XPath:",e,t),null}}log(...e){this.options.debug&&console.log("[SectionTracking]",...e)}updateSections(e){this.isDestroyed||(this.log("Updating sections configuration"),this.intersectionObserver&&this.intersectionObserver.disconnect(),this.sectionStates.clear(),this.xpathCache.clear(),this.sections=e,this.setupIntersectionObserver(),this.initializeSections())}destroy(){this.isDestroyed||(this.log("Destroying section tracking manager"),this.isDestroyed=!0,this.sectionTimers.forEach(e=>{clearInterval(e)}),this.sectionTimers.clear(),this.flushPendingEvents(),this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.attentionQuality.destroy(),this.sectionStates.clear(),this.xpathCache.clear(),this.pendingEvents=[])}}});var ae={};A(ae,{DebugAgent:()=>G});var G,oe=g(()=>{"use strict";G=class{constructor(e,t,i,r,n={}){this.isDestroyed=!1;this.isInspectMode=!1;this.showTrackers=!1;this.selectedElement=null;this.toolbarElement=null;this.panelElement=null;this.highlightElement=null;this.existingTrackers=[];this.trackerHighlights=[];this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.toolbarStartX=0;this.toolbarStartY=0;this.mouseMoveListener=null;this.clickListener=null;this.dragMoveListener=null;this.dragEndListener=null;this.handleEscapeKey=e=>{e.key==="Escape"&&this.isInspectMode&&this.disableInspectMode()};this.tracker=e,this.sessionId=t,this.tenantId=i,this.apiUrl=r,this.config={debug:n.debug??!1},typeof window<"u"&&typeof document<"u"&&this.initialize()}async initialize(){this.log("Initializing debug agent"),await this.loadExistingTrackers(),this.showToolbar(),this.createHighlightElement(),this.showTrackers=!0,this.showTrackerHighlights(),this.showTrackersList()}async loadExistingTrackers(){try{let e=`${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/trackers`,t=await fetch(e);t.ok&&(this.existingTrackers=await t.json(),this.log("Loaded trackers:",this.existingTrackers))}catch(e){this.log("Failed to load trackers:",e),this.existingTrackers=[]}}showToolbar(){if(this.toolbarElement)return;let e=document.createElement("div");e.id="grain-debug-toolbar",e.innerHTML=`
|
|
1
|
+
/* Grain Analytics Web SDK v3.2.0 | MIT License */
|
|
2
|
+
"use strict";var Grain=(()=>{var Ze=Object.defineProperty;var Ur=Object.getOwnPropertyDescriptor;var $r=Object.getOwnPropertyNames;var Hr=Object.prototype.hasOwnProperty;var $=(n,e)=>()=>(n&&(e=n(n=0)),e);var z=(n,e)=>{for(var t in e)Ze(n,t,{get:e[t],enumerable:!0})},Br=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $r(e))!Hr.call(n,r)&&r!==t&&Ze(n,r,{get:()=>e[r],enumerable:!(i=Ur(e,r))||i.enumerable});return n};var Fr=n=>Br(Ze({},"__esModule",{value:!0}),n);var Yr,W,it=$(()=>{"use strict";Yr={maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4},W=class{constructor(e,t={}){this.isDestroyed=!1;this.isPageVisible=!0;this.visibilityChangeHandler=null;this.sectionStates=new Map;this.lastFilterReason=null;this.activityDetector=e,this.options={...Yr,...t,debug:t.debug??!1},this.setupPageVisibilityTracking()}setupPageVisibilityTracking(){typeof document>"u"||(this.isPageVisible=document.visibilityState==="visible",this.visibilityChangeHandler=()=>{let e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.log("Page hidden - tracking paused"):this.isPageVisible&&!e&&(this.log("Page visible - tracking resumed"),this.resetAllSections())},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}shouldTrack(){return this.isPageVisible?this.activityDetector.isActive(this.options.idleThreshold)?(this.lastFilterReason=null,!0):(this.lastFilterReason="user_idle",!1):(this.lastFilterReason="page_hidden",!1)}shouldTrackSection(e,t){if(!this.shouldTrack())return{shouldTrack:!1,reason:this.lastFilterReason||"global_policy"};let i=this.sectionStates.get(e);i||(i={sectionName:e,currentDuration:0,lastScrollPosition:t,lastResetTime:Date.now()},this.sectionStates.set(e,i));let r=Math.abs(t-i.lastScrollPosition);return r>=this.options.minScrollDistance?(this.log(`Section "${e}": Attention reset due to ${Math.round(r)}px scroll`),i.currentDuration=0,i.lastScrollPosition=t,i.lastResetTime=Date.now(),{shouldTrack:!0,resetAttention:!0}):i.currentDuration>=this.options.maxSectionDuration?{shouldTrack:!1,reason:"max_duration_reached"}:{shouldTrack:!0}}updateSectionDuration(e,t){let i=this.sectionStates.get(e);i&&(i.currentDuration+=t,i.currentDuration>=this.options.maxSectionDuration&&this.log(`Section "${e}": Max duration cap reached (${i.currentDuration}ms)`))}resetSection(e){let t=this.sectionStates.get(e);t&&(this.log(`Section "${e}": Attention reset (section exit)`),t.currentDuration=0,t.lastResetTime=Date.now())}resetAllSections(){this.log("Resetting all section attention states");for(let e of this.sectionStates.values())e.currentDuration=0,e.lastResetTime=Date.now()}getSectionState(e){return this.sectionStates.get(e)}getLastFilterReason(){return this.lastFilterReason}shouldTrackScroll(e,t){return this.shouldTrack()?Math.abs(t-e)<10?{shouldTrack:!1,reason:"scroll_too_small"}:{shouldTrack:!0}:{shouldTrack:!1,reason:this.lastFilterReason||"global_policy"}}getPolicies(){return{maxSectionDuration:this.options.maxSectionDuration,minScrollDistance:this.options.minScrollDistance,idleThreshold:this.options.idleThreshold}}getTrackingState(){return{isPageVisible:this.isPageVisible,isUserActive:this.activityDetector.isActive(this.options.idleThreshold),timeSinceLastActivity:this.activityDetector.getTimeSinceLastActivity(),activeSections:this.sectionStates.size}}log(...e){this.options.debug&&console.log("[AttentionQuality]",...e)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.visibilityChangeHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null),this.sectionStates.clear())}}});function Jr(n){if(n)return n.replace(/[\u{1F300}-\u{1F9FF}]/gu,"").replace(/[\u{1F600}-\u{1F64F}]/gu,"").replace(/[\u{1F680}-\u{1F6FF}]/gu,"").replace(/[\u{2600}-\u{26FF}]/gu,"").replace(/[\u{2700}-\u{27BF}]/gu,"").replace(/[\u{1F900}-\u{1F9FF}]/gu,"").replace(/[\u{1F1E0}-\u{1F1FF}]/gu,"").replace(/[\u{200D}]/gu,"").replace(/[\u{FE0F}]/gu,"").replace(/[\u{20E3}]/gu,"").trim()}function Ae(n,e=100){if(!n)return;let t=Jr(n);if(t)return t.substring(0,e)||void 0}var rt=$(()=>{"use strict"});var kr={};z(kr,{IGNORED_NODE:()=>ut,Mirror:()=>J,absolutifyURLs:()=>ae,adaptCssForReplay:()=>Ye,buildNodeWithSN:()=>Ht,classMatchesRegex:()=>$e,cleanupSnapshot:()=>Nn,createCache:()=>Ia,createMirror:()=>pn,escapeImportStatement:()=>Mi,extractFileExtension:()=>xt,fixSafariColons:()=>Ii,genId:()=>Bi,getInputType:()=>Ni,ignoreAttribute:()=>Gi,is2DCanvasBlank:()=>Li,isCSSImportRule:()=>_i,isCSSStyleRule:()=>Ri,isElement:()=>ze,isNativeShadowDom:()=>De,isNodeMetaEqual:()=>Oi,isShadowRoot:()=>xi,markCssSplits:()=>$i,maskInputValue:()=>Di,needMaskingText:()=>zi,normalizeCssString:()=>Le,rebuild:()=>Na,serializeNodeWithId:()=>Y,snapshot:()=>Ln,splitCssText:()=>Ui,stringifyRule:()=>Pi,stringifyStylesheet:()=>Ue,toLowerCase:()=>he,transformAttribute:()=>Fi,visitSnapshot:()=>On});function kt(n){if(Ee[n])return Ee[n];let e=globalThis[n],t=e.prototype,i=n in ri?ri[n]:void 0,r=!!(i&&i.every(o=>{var c,l;return!!((l=(c=Object.getOwnPropertyDescriptor(t,o))==null?void 0:c.get)!=null&&l.toString().includes("[native code]"))})),s=n in ni?ni[n]:void 0,a=!!(s&&s.every(o=>{var c;return typeof t[o]=="function"&&((c=t[o])==null?void 0:c.toString().includes("[native code]"))}));if(r&&a&&!Zr())return Ee[n]=e.prototype,e.prototype;try{let o=document.createElement("iframe");document.body.appendChild(o);let c=o.contentWindow;if(!c)return e.prototype;let l=c[n].prototype;return document.body.removeChild(o),l?Ee[n]=l:t}catch{return t}}function U(n,e,t){var i;let r=`${n}.${String(t)}`;if(nt[r])return nt[r].call(e);let s=kt(n),a=(i=Object.getOwnPropertyDescriptor(s,t))==null?void 0:i.get;return a?(nt[r]=a,a.call(e)):e[t]}function ki(n,e,t){let i=`${n}.${String(t)}`;if(st[i])return st[i].bind(e);let s=kt(n)[t];return typeof s!="function"?e[t]:(st[i]=s,s.bind(e))}function en(n){return U("Node",n,"childNodes")}function tn(n){return U("Node",n,"parentNode")}function rn(n){return U("Node",n,"parentElement")}function nn(n){return U("Node",n,"textContent")}function sn(n,e){return ki("Node",n,"contains")(e)}function an(n){return ki("Node",n,"getRootNode")()}function on(n){return!n||!("host"in n)?null:U("ShadowRoot",n,"host")}function cn(n){return n.styleSheets}function ln(n){return!n||!("shadowRoot"in n)?null:U("Element",n,"shadowRoot")}function un(n,e){return U("Element",n,"querySelector")(e)}function hn(n,e){return U("Element",n,"querySelectorAll")(e)}function dn(){return kt("MutationObserver").constructor}function ze(n){return n.nodeType===n.ELEMENT_NODE}function xi(n){let e=n&&"host"in n&&"mode"in n&&k.host(n)||null;return!!(e&&"shadowRoot"in e&&k.shadowRoot(e)===n)}function De(n){return Object.prototype.toString.call(n)==="[object ShadowRoot]"}function fn(n){return n.includes(" background-clip: text;")&&!n.includes(" -webkit-background-clip: text;")&&(n=n.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),n}function Mi(n){let{cssText:e}=n;if(e.split('"').length<3)return e;let t=["@import",`url(${JSON.stringify(n.href)})`];return n.layerName===""?t.push("layer"):n.layerName&&t.push(`layer(${n.layerName})`),n.supportsText&&t.push(`supports(${n.supportsText})`),n.media.length&&t.push(n.media.mediaText),t.join(" ")+";"}function Ue(n){try{let e=n.rules||n.cssRules;if(!e)return null;let t=n.href;!t&&n.ownerNode&&n.ownerNode.ownerDocument&&(t=n.ownerNode.ownerDocument.location.href);let i=Array.from(e,r=>Pi(r,t)).join("");return fn(i)}catch{return null}}function Pi(n,e){if(_i(n)){let t;try{t=Ue(n.styleSheet)||Mi(n)}catch{t=n.cssText}return n.styleSheet.href?ae(t,n.styleSheet.href):t}else{let t=n.cssText;return Ri(n)&&n.selectorText.includes(":")&&(t=Ii(t)),e?ae(t,e):t}}function Ii(n){let e=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return n.replace(e,"$1\\$2")}function _i(n){return"styleSheet"in n}function Ri(n){return"selectorText"in n}function pn(){return new J}function Di({element:n,maskInputOptions:e,tagName:t,type:i,value:r,maskInputFn:s}){let a=r||"",o=i&&he(i);return(e[t.toLowerCase()]||o&&e[o])&&(s?a=s(a,n):a="*".repeat(a.length)),a}function he(n){return n.toLowerCase()}function Li(n){let e=n.getContext("2d");if(!e)return!0;let t=50;for(let i=0;i<n.width;i+=t)for(let r=0;r<n.height;r+=t){let s=e.getImageData,a=si in s?s[si]:s;if(new Uint32Array(a.call(e,i,r,Math.min(t,n.width-i),Math.min(t,n.height-r)).data.buffer).some(c=>c!==0))return!1}return!0}function Oi(n,e){return!n||!e||n.type!==e.type?!1:n.type===m.Document?n.compatMode===e.compatMode:n.type===m.DocumentType?n.name===e.name&&n.publicId===e.publicId&&n.systemId===e.systemId:n.type===m.Comment||n.type===m.Text||n.type===m.CDATA?n.textContent===e.textContent:n.type===m.Element?n.tagName===e.tagName&&JSON.stringify(n.attributes)===JSON.stringify(e.attributes)&&n.isSVG===e.isSVG&&n.needBlock===e.needBlock:!1}function Ni(n){let e=n.type;return n.hasAttribute("data-rr-is-password")?"password":e?he(e):null}function xt(n,e){let t;try{t=new URL(n,e??window.location.href)}catch{return null}let i=/\.([0-9a-z]+)(?:$)/i,r=t.pathname.match(i);return r?.[1]??null}function gn(n){let e="";return n.indexOf("//")>-1?e=n.split("/").slice(0,3).join("/"):e=n.split("/")[0],e=e.split("?")[0],e}function ae(n,e){return(n||"").replace(mn,(t,i,r,s,a,o)=>{let c=r||a||o,l=i||s||"";if(!c)return t;if(yn.test(c)||vn.test(c))return`url(${l}${c}${l})`;if(bn.test(c))return`url(${l}${c}${l})`;if(c[0]==="/")return`url(${l}${gn(e)+c}${l})`;let u=e.split("/"),d=c.split("/");u.pop();for(let f of d)f!=="."&&(f===".."?u.pop():u.push(f));return`url(${l}${u.join("/")}${l})`})}function Le(n){return n.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"")}function Ui(n,e){let t=Array.from(e.childNodes),i=[];if(t.length>1&&n&&typeof n=="string"){let r=Le(n);for(let s=1;s<t.length;s++)if(t[s].textContent&&typeof t[s].textContent=="string"){let a=Le(t[s].textContent);for(let o=3;o<a.length;o++){let c=a.substring(0,o);if(r.split(c).length===2){let l=r.indexOf(c);for(let u=l;u<n.length;u++)if(Le(n.substring(0,u)).length===l){i.push(n.substring(0,u)),n=n.substring(u);break}break}}}}return i.push(n),i}function $i(n,e){return Ui(n,e).join("/* rr_split */")}function Bi(){return Hi++}function Sn(n){if(n instanceof HTMLFormElement)return"form";let e=he(n.tagName);return wn.test(e)?"div":e}function Cn(n,e){if(e.trim()==="")return e;let t=0;function i(s){let a,o=s.exec(e.substring(t));return o?(a=o[0],t+=a.length,a):""}let r=[];for(;i(En),!(t>=e.length);){let s=i(An);if(s.slice(-1)===",")s=Q(n,s.substring(0,s.length-1)),r.push(s);else{let a="";s=Q(n,s);let o=!1;for(;;){let c=e.charAt(t);if(c===""){r.push((s+a).trim());break}else if(o)c===")"&&(o=!1);else if(c===","){t+=1,r.push((s+a).trim());break}else c==="("&&(o=!0);a+=c,t+=1}}}return r.join(", ")}function Q(n,e){return!e||e.trim()===""?e:Mt(n,e)}function Tn(n){return!!(n.tagName==="svg"||n.ownerSVGElement)}function Mt(n,e){let t=oi.get(n);if(t||(t=n.createElement("a"),oi.set(n,t)),!e)e="";else if(e.startsWith("blob:")||e.startsWith("data:"))return e;return t.setAttribute("href",e),t.href}function Fi(n,e,t,i){return i&&(t==="src"||t==="href"&&!(e==="use"&&i[0]==="#")||t==="xlink:href"&&i[0]!=="#"||t==="background"&&(e==="table"||e==="td"||e==="th")?Q(n,i):t==="srcset"?Cn(n,i):t==="style"?ae(i,Mt(n)):e==="object"&&t==="data"?Q(n,i):i)}function Gi(n,e,t){return(n==="video"||n==="audio")&&e==="autoplay"}function kn(n,e,t){try{if(typeof e=="string"){if(n.classList.contains(e))return!0}else for(let i=n.classList.length;i--;){let r=n.classList[i];if(e.test(r))return!0}if(t)return n.matches(t)}catch{}return!1}function $e(n,e,t){if(!n)return!1;if(n.nodeType!==n.ELEMENT_NODE)return t?$e(k.parentNode(n),e,t):!1;for(let i=n.classList.length;i--;){let r=n.classList[i];if(e.test(r))return!0}return t?$e(k.parentNode(n),e,t):!1}function zi(n,e,t,i){let r;if(ze(n)){if(r=n,!k.childNodes(r).length)return!1}else{if(k.parentElement(n)===null)return!1;r=k.parentElement(n)}try{if(typeof e=="string"){if(i){if(r.closest(`.${e}`))return!0}else if(r.classList.contains(e))return!0}else if($e(r,e,i))return!0;if(t){if(i){if(r.closest(t))return!0}else if(r.matches(t))return!0}}catch{}return!1}function xn(n,e,t){let i=n.contentWindow;if(!i)return;let r=!1,s;try{s=i.document.readyState}catch{return}if(s!=="complete"){let o=setTimeout(()=>{r||(e(),r=!0)},t);n.addEventListener("load",()=>{clearTimeout(o),r=!0,e()});return}let a="about:blank";if(i.location.href!==a||n.src===a||n.src==="")return setTimeout(e,0),n.addEventListener("load",e);n.addEventListener("load",e)}function Mn(n,e,t){let i=!1,r;try{r=n.sheet}catch{return}if(r)return;let s=setTimeout(()=>{i||(e(),i=!0)},t);n.addEventListener("load",()=>{clearTimeout(s),i=!0,e()})}function Pn(n,e){let{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:a,inlineStylesheet:o,maskInputOptions:c={},maskTextFn:l,maskInputFn:u,dataURLOptions:d={},inlineImages:f,recordCanvas:y,keepIframeSrcFn:g,newlyAddedElement:v=!1,cssCaptured:h=!1}=e,T=In(t,i);switch(n.nodeType){case n.DOCUMENT_NODE:return n.compatMode!=="CSS1Compat"?{type:m.Document,childNodes:[],compatMode:n.compatMode}:{type:m.Document,childNodes:[]};case n.DOCUMENT_TYPE_NODE:return{type:m.DocumentType,name:n.name,publicId:n.publicId,systemId:n.systemId,rootId:T};case n.ELEMENT_NODE:return Rn(n,{doc:t,blockClass:r,blockSelector:s,inlineStylesheet:o,maskInputOptions:c,maskInputFn:u,dataURLOptions:d,inlineImages:f,recordCanvas:y,keepIframeSrcFn:g,newlyAddedElement:v,rootId:T});case n.TEXT_NODE:return _n(n,{doc:t,needsMask:a,maskTextFn:l,rootId:T,cssCaptured:h});case n.CDATA_SECTION_NODE:return{type:m.CDATA,textContent:"",rootId:T};case n.COMMENT_NODE:return{type:m.Comment,textContent:k.textContent(n)||"",rootId:T};default:return!1}}function In(n,e){if(!e.hasNode(n))return;let t=e.getId(n);return t===1?void 0:t}function _n(n,e){let{needsMask:t,maskTextFn:i,rootId:r,cssCaptured:s}=e,a=k.parentNode(n),o=a&&a.tagName,c="",l=o==="STYLE"?!0:void 0,u=o==="SCRIPT"?!0:void 0;return u?c="SCRIPT_PLACEHOLDER":s||(c=k.textContent(n),l&&c&&(c=ae(c,Mt(e.doc)))),!l&&!u&&c&&t&&(c=i?i(c,k.parentElement(n)):c.replace(/[\S]/g,"*")),{type:m.Text,textContent:c||"",rootId:r}}function Rn(n,e){let{doc:t,blockClass:i,blockSelector:r,inlineStylesheet:s,maskInputOptions:a={},maskInputFn:o,dataURLOptions:c={},inlineImages:l,recordCanvas:u,keepIframeSrcFn:d,newlyAddedElement:f=!1,rootId:y}=e,g=kn(n,i,r),v=Sn(n),h={},T=n.attributes.length;for(let p=0;p<T;p++){let b=n.attributes[p];Gi(v,b.name,b.value)||(h[b.name]=Fi(t,v,he(b.name),b.value))}if(v==="link"&&s){let p=Array.from(t.styleSheets).find(M=>M.href===n.href),b=null;p&&(b=Ue(p)),b&&(delete h.rel,delete h.href,h._cssText=b)}if(v==="style"&&n.sheet){let p=Ue(n.sheet);p&&(n.childNodes.length>1&&(p=$i(p,n)),h._cssText=p)}if(v==="input"||v==="textarea"||v==="select"){let p=n.value,b=n.checked;h.type!=="radio"&&h.type!=="checkbox"&&h.type!=="submit"&&h.type!=="button"&&p?h.value=Di({element:n,type:Ni(n),tagName:v,value:p,maskInputOptions:a,maskInputFn:o}):b&&(h.checked=b)}if(v==="option"&&(n.selected&&!a.select?h.selected=!0:delete h.selected),v==="dialog"&&n.open&&(h.rr_open_mode=n.matches("dialog:modal")?"modal":"non-modal"),v==="canvas"&&u){if(n.__context==="2d")Li(n)||(h.rr_dataURL=n.toDataURL(c.type,c.quality));else if(!("__context"in n)){let p=n.toDataURL(c.type,c.quality),b=t.createElement("canvas");b.width=n.width,b.height=n.height;let M=b.toDataURL(c.type,c.quality);p!==M&&(h.rr_dataURL=p)}}if(v==="img"&&l){j||(j=t.createElement("canvas"),ai=j.getContext("2d"));let p=n,b=p.currentSrc||p.getAttribute("src")||"<unknown-src>",M=p.crossOrigin,I=()=>{p.removeEventListener("load",I);try{j.width=p.naturalWidth,j.height=p.naturalHeight,ai.drawImage(p,0,0),h.rr_dataURL=j.toDataURL(c.type,c.quality)}catch(B){if(p.crossOrigin!=="anonymous"){p.crossOrigin="anonymous",p.complete&&p.naturalWidth!==0?I():p.addEventListener("load",I);return}else console.warn(`Cannot inline img src=${b}! Error: ${B}`)}p.crossOrigin==="anonymous"&&(M?h.crossOrigin=M:p.removeAttribute("crossorigin"))};p.complete&&p.naturalWidth!==0?I():p.addEventListener("load",I)}if(v==="audio"||v==="video"){let p=h;p.rr_mediaState=n.paused?"paused":"played",p.rr_mediaCurrentTime=n.currentTime,p.rr_mediaPlaybackRate=n.playbackRate,p.rr_mediaMuted=n.muted,p.rr_mediaLoop=n.loop,p.rr_mediaVolume=n.volume}if(f||(n.scrollLeft&&(h.rr_scrollLeft=n.scrollLeft),n.scrollTop&&(h.rr_scrollTop=n.scrollTop)),g){let{width:p,height:b}=n.getBoundingClientRect();h={class:h.class,rr_width:`${p}px`,rr_height:`${b}px`}}v==="iframe"&&!d(h.src)&&(n.contentDocument||(h.rr_src=h.src),delete h.src);let x;try{customElements.get(v)&&(x=!0)}catch{}return{type:m.Element,tagName:v,attributes:h,childNodes:[],isSVG:Tn(n)||void 0,needBlock:g,rootId:y,isCustom:x}}function A(n){return n==null?"":n.toLowerCase()}function Dn(n,e){if(e.comment&&n.type===m.Comment)return!0;if(n.type===m.Element){if(e.script&&(n.tagName==="script"||n.tagName==="link"&&(n.attributes.rel==="preload"||n.attributes.rel==="modulepreload")&&n.attributes.as==="script"||n.tagName==="link"&&n.attributes.rel==="prefetch"&&typeof n.attributes.href=="string"&&xt(n.attributes.href)==="js"))return!0;if(e.headFavicon&&(n.tagName==="link"&&n.attributes.rel==="shortcut icon"||n.tagName==="meta"&&(A(n.attributes.name).match(/^msapplication-tile(image|color)$/)||A(n.attributes.name)==="application-name"||A(n.attributes.rel)==="icon"||A(n.attributes.rel)==="apple-touch-icon"||A(n.attributes.rel)==="shortcut icon")))return!0;if(n.tagName==="meta"){if(e.headMetaDescKeywords&&A(n.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(A(n.attributes.property).match(/^(og|twitter|fb):/)||A(n.attributes.name).match(/^(og|twitter):/)||A(n.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(A(n.attributes.name)==="robots"||A(n.attributes.name)==="googlebot"||A(n.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&n.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(A(n.attributes.name)==="author"||A(n.attributes.name)==="generator"||A(n.attributes.name)==="framework"||A(n.attributes.name)==="publisher"||A(n.attributes.name)==="progid"||A(n.attributes.property).match(/^article:/)||A(n.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(A(n.attributes.name)==="google-site-verification"||A(n.attributes.name)==="yandex-verification"||A(n.attributes.name)==="csrf-token"||A(n.attributes.name)==="p:domain_verify"||A(n.attributes.name)==="verify-v1"||A(n.attributes.name)==="verification"||A(n.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Y(n,e){let{doc:t,mirror:i,blockClass:r,blockSelector:s,maskTextClass:a,maskTextSelector:o,skipChild:c=!1,inlineStylesheet:l=!0,maskInputOptions:u={},maskTextFn:d,maskInputFn:f,slimDOMOptions:y,dataURLOptions:g={},inlineImages:v=!1,recordCanvas:h=!1,onSerialize:T,onIframeLoad:x,iframeLoadTimeout:p=5e3,onStylesheetLoad:b,stylesheetLoadTimeout:M=5e3,keepIframeSrcFn:I=()=>!1,newlyAddedElement:B=!1,cssCaptured:O=!1}=e,{needsMask:_}=e,{preserveWhiteSpace:N=!0}=e;_||(_=zi(n,a,o,_===void 0));let te=Pn(n,{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:_,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:f,dataURLOptions:g,inlineImages:v,recordCanvas:h,keepIframeSrcFn:I,newlyAddedElement:B,cssCaptured:O});if(!te)return console.warn(n,"not serialized"),null;let ie;i.hasNode(n)?ie=i.getId(n):Dn(te,y)||!N&&te.type===m.Text&&!te.textContent.replace(/^\s+|\s+$/gm,"").length?ie=ut:ie=Bi();let S=Object.assign(te,{id:ie});if(i.add(n,S),ie===ut)return null;T&&T(n);let Je=!c;if(S.type===m.Element){Je=Je&&!S.needBlock,delete S.needBlock;let P=k.shadowRoot(n);P&&De(P)&&(S.isShadowHost=!0)}if((S.type===m.Document||S.type===m.Element)&&Je){y.headWhitespace&&S.type===m.Element&&S.tagName==="head"&&(N=!1);let P={doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:_,maskTextClass:a,maskTextSelector:o,skipChild:c,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:f,slimDOMOptions:y,dataURLOptions:g,inlineImages:v,recordCanvas:h,preserveWhiteSpace:N,onSerialize:T,onIframeLoad:x,iframeLoadTimeout:p,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:I,cssCaptured:!1};if(!(S.type===m.Element&&S.tagName==="textarea"&&S.attributes.value!==void 0)){S.type===m.Element&&S.attributes._cssText!==void 0&&typeof S.attributes._cssText=="string"&&(P.cssCaptured=!0);for(let Xe of Array.from(k.childNodes(n))){let G=Y(Xe,P);G&&S.childNodes.push(G)}}let F=null;if(ze(n)&&(F=k.shadowRoot(n)))for(let Xe of Array.from(k.childNodes(F))){let G=Y(Xe,P);G&&(De(F)&&(G.isShadow=!0),S.childNodes.push(G))}}let qe=k.parentNode(n);return qe&&xi(qe)&&De(qe)&&(S.isShadow=!0),S.type===m.Element&&S.tagName==="iframe"&&xn(n,()=>{let P=n.contentDocument;if(P&&x){let F=Y(P,{doc:P,mirror:i,blockClass:r,blockSelector:s,needsMask:_,maskTextClass:a,maskTextSelector:o,skipChild:!1,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:f,slimDOMOptions:y,dataURLOptions:g,inlineImages:v,recordCanvas:h,preserveWhiteSpace:N,onSerialize:T,onIframeLoad:x,iframeLoadTimeout:p,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:I});F&&x(n,F)}},p),S.type===m.Element&&S.tagName==="link"&&typeof S.attributes.rel=="string"&&(S.attributes.rel==="stylesheet"||S.attributes.rel==="preload"&&typeof S.attributes.href=="string"&&xt(S.attributes.href)==="css")&&Mn(n,()=>{if(b){let P=Y(n,{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:_,maskTextClass:a,maskTextSelector:o,skipChild:!1,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:f,slimDOMOptions:y,dataURLOptions:g,inlineImages:v,recordCanvas:h,preserveWhiteSpace:N,onSerialize:T,onIframeLoad:x,iframeLoadTimeout:p,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:I});P&&b(n,P)}},M),S}function Ln(n,e){let{mirror:t=new J,blockClass:i="rr-block",blockSelector:r=null,maskTextClass:s="rr-mask",maskTextSelector:a=null,inlineStylesheet:o=!0,inlineImages:c=!1,recordCanvas:l=!1,maskAllInputs:u=!1,maskTextFn:d,maskInputFn:f,slimDOM:y=!1,dataURLOptions:g,preserveWhiteSpace:v,onSerialize:h,onIframeLoad:T,iframeLoadTimeout:x,onStylesheetLoad:p,stylesheetLoadTimeout:b,keepIframeSrcFn:M=()=>!1}=e||{};return Y(n,{doc:n,mirror:t,blockClass:i,blockSelector:r,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:o,maskInputOptions:u===!0?{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}:u===!1?{password:!0}:u,maskTextFn:d,maskInputFn:f,slimDOMOptions:y===!0||y==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:y==="all",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:y===!1?{}:y,dataURLOptions:g,inlineImages:c,recordCanvas:l,preserveWhiteSpace:v,onSerialize:h,onIframeLoad:T,iframeLoadTimeout:x,onStylesheetLoad:p,stylesheetLoadTimeout:b,keepIframeSrcFn:M,newlyAddedElement:!1})}function On(n,e){function t(i){e(i),(i.type===m.Document||i.type===m.Element)&&i.childNodes.forEach(t)}t(n)}function Nn(){Hi=1}function Bn(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function Fn(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}),t}function Kn(n){return n[0].toUpperCase()+n.slice(1)}function ft(n,e){new Wn(e).stringify(n)}function pt(n,e){let t=new n.constructor;for(let i in n){if(!Object.prototype.hasOwnProperty.call(n,i)||i==="proxyCache")continue;let r=n[i],s=typeof r;i==="parent"&&s==="object"?e&&(t[i]=e):i==="source"?t[i]=r:Array.isArray(r)?t[i]=r.map(a=>pt(a,t)):(s==="object"&&r!==null&&(r=pt(r)),t[i]=r)}return t}function ss(n){return Buffer?Buffer.from(n,"base64").toString():window.atob(n)}function sr(n){return n.map(e=>(e.nodes&&(e.nodes=sr(e.nodes)),delete e.source,e))}function ar(n){if(n[Zi]=!1,n.proxyOf.nodes)for(let e of n.proxyOf.nodes)ar(e)}function Us(n){for(let e=n.length-1;e>=0;e--){let t=n[e],i=t[3]||t[2];if(i)return i}}function Ge(n,e){let t=new Gs(n,e),i=new Fs(t);try{i.parse()}catch(r){throw r}return i.root}function se(n){return typeof n=="object"&&typeof n.then=="function"}function yr(n){let e=!1,t=Js[n.type];return n.type==="decl"?e=n.prop.toLowerCase():n.type==="atrule"&&(e=n.name.toLowerCase()),e&&n.append?[t,t+"-"+e,X,t+"Exit",t+"Exit-"+e]:e?[t,t+"-"+e,t+"Exit",t+"Exit-"+e]:n.append?[t,X,t+"Exit"]:[t,t+"Exit"]}function Ci(n){let e;return n.type==="document"?e=["Document",X,"DocumentExit"]:n.type==="root"?e=["Root",X,"RootExit"]:e=yr(n),{eventIndex:0,events:e,iterator:0,node:n,visitorIndex:0,visitors:[]}}function Et(n){return n[D]=!1,n.nodes&&n.nodes.forEach(e=>Et(e)),n}function ue(n,e){if(Array.isArray(n))return n.map(r=>ue(r));let{inputs:t,...i}=n;if(t){e=[];for(let r of t){let s={...r,__proto__:fa.prototype};s.map&&(s.map={...s.map,__proto__:ua.prototype}),e.push(s)}}if(i.nodes&&(i.nodes=n.nodes.map(r=>ue(r,e))),i.source){let{inputId:r,...s}=i.source;i.source=s,r!=null&&(i.source.input=e[r])}if(i.type==="root")return new pa(i);if(i.type==="decl")return new la(i);if(i.type==="rule")return new ga(i);if(i.type==="comment")return new ha(i);if(i.type==="atrule")return new da(i);throw new Error("Unknown node type: "+n.type)}function w(...n){return n.length===1&&Array.isArray(n[0])&&(n=n[0]),new $t(n)}function Pa(n){let e=Ti[n.tagName]?Ti[n.tagName]:n.tagName;return e==="link"&&n.attributes._cssText&&(e="style"),e}function Ye(n,e){let t=e?.stylesWithHoverClass.get(n);if(t)return t;let r=C([$n,Hn]).process(n).css;return e?.stylesWithHoverClass.set(n,r),r}function Ia(){return{stylesWithHoverClass:new Map}}function _a(n,e,t,i){let r=[];for(let a of n.childNodes)a.type===m.Text&&r.push(a);let s=e.split("/* rr_split */");for(;s.length>1&&s.length>r.length;)s.splice(-2,2,s.slice(-2).join(""));for(let a=0;a<r.length;a++){let o=r[a],c=s[a];o&&c&&(o.textContent=t?Ye(c,i):c)}}function Ra(n,e,t,i){let{doc:r,hackCss:s,cache:a}=i;n.childNodes.length?_a(n,t,s,a):(s&&(t=Ye(t,a)),e.appendChild(r.createTextNode(t)))}function Da(n,e){var t;let{doc:i,hackCss:r,cache:s}=e;switch(n.type){case m.Document:return i.implementation.createDocument(null,"",null);case m.DocumentType:return i.implementation.createDocumentType(n.name||"html",n.publicId,n.systemId);case m.Element:{let a=Pa(n),o;n.isSVG?o=i.createElementNS("http://www.w3.org/2000/svg",a):(n.isCustom&&((t=i.defaultView)!=null&&t.customElements)&&!i.defaultView.customElements.get(n.tagName)&&i.defaultView.customElements.define(n.tagName,class extends i.defaultView.HTMLElement{}),o=i.createElement(a));let c={};for(let l in n.attributes){if(!Object.prototype.hasOwnProperty.call(n.attributes,l))continue;let u=n.attributes[l];if(!(a==="option"&&l==="selected"&&u===!1)&&u!==null){if(u===!0&&(u=""),l.startsWith("rr_")){c[l]=u;continue}if(typeof u=="string"){if(a==="style"&&l==="_cssText"){Ra(n,o,u,e);continue}else if(a==="textarea"&&l==="value"){o.appendChild(i.createTextNode(u)),n.childNodes=[];continue}}try{if(n.isSVG&&l==="xlink:href")o.setAttributeNS("http://www.w3.org/1999/xlink",l,u.toString());else if(l==="onload"||l==="onclick"||l.substring(0,7)==="onmouse")o.setAttribute("_"+l,u.toString());else if(a==="meta"&&n.attributes["http-equiv"]==="Content-Security-Policy"&&l==="content"){o.setAttribute("csp-content",u.toString());continue}else a==="link"&&(n.attributes.rel==="preload"||n.attributes.rel==="modulepreload")&&n.attributes.as==="script"||a==="link"&&n.attributes.rel==="prefetch"&&typeof n.attributes.href=="string"&&n.attributes.href.endsWith(".js")||(a==="img"&&n.attributes.srcset&&n.attributes.rr_dataURL?o.setAttribute("rrweb-original-srcset",n.attributes.srcset):o.setAttribute(l,u.toString()))}catch{}}}for(let l in c){let u=c[l];if(a==="canvas"&&l==="rr_dataURL"){let d=i.createElement("img");d.onload=()=>{let f=o.getContext("2d");f&&f.drawImage(d,0,0,d.width,d.height)},d.src=u.toString(),o.RRNodeType&&(o.rr_dataURL=u.toString())}else if(a==="img"&&l==="rr_dataURL"){let d=o;d.currentSrc.startsWith("data:")||(d.setAttribute("rrweb-original-src",n.attributes.src),d.src=u.toString())}if(l==="rr_width")o.style.setProperty("width",u.toString());else if(l==="rr_height")o.style.setProperty("height",u.toString());else if(l==="rr_mediaCurrentTime"&&typeof u=="number")o.currentTime=u;else if(l==="rr_mediaState")switch(u){case"played":o.play().catch(d=>console.warn("media playback error",d));break;case"paused":o.pause();break}else l==="rr_mediaPlaybackRate"&&typeof u=="number"?o.playbackRate=u:l==="rr_mediaMuted"&&typeof u=="boolean"?o.muted=u:l==="rr_mediaLoop"&&typeof u=="boolean"?o.loop=u:l==="rr_mediaVolume"&&typeof u=="number"?o.volume=u:l==="rr_open_mode"&&o.setAttribute("rr_open_mode",u)}if(n.isShadowHost)if(!o.shadowRoot)o.attachShadow({mode:"open"});else for(;o.shadowRoot.firstChild;)o.shadowRoot.removeChild(o.shadowRoot.firstChild);return o}case m.Text:return n.isStyle&&r?i.createTextNode(Ye(n.textContent,s)):i.createTextNode(n.textContent);case m.CDATA:return i.createCDATASection(n.textContent);case m.Comment:return i.createComment(n.textContent);default:return null}}function Ht(n,e){let{doc:t,mirror:i,skipChild:r=!1,hackCss:s=!0,afterAppend:a,cache:o}=e;if(i.has(n.id)){let l=i.getNode(n.id),u=i.getMeta(l);if(Oi(u,n))return i.getNode(n.id)}let c=Da(n,{doc:t,hackCss:s,cache:o});if(!c)return null;if(n.rootId&&i.getNode(n.rootId)!==t&&i.replace(n.rootId,t),n.type===m.Document&&(t.close(),t.open(),n.compatMode==="BackCompat"&&n.childNodes&&n.childNodes[0].type!==m.DocumentType&&(n.childNodes[0].type===m.Element&&"xmlns"in n.childNodes[0].attributes&&n.childNodes[0].attributes.xmlns==="http://www.w3.org/1999/xhtml"?t.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">'):t.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "">')),c=t),i.add(c,n),(n.type===m.Document||n.type===m.Element)&&!r)for(let l of n.childNodes){let u=Ht(l,{doc:t,mirror:i,skipChild:!1,hackCss:s,afterAppend:a,cache:o});if(!u){console.warn("Failed to rebuild",l);continue}if(l.isShadow&&ze(c)&&c.shadowRoot)c.shadowRoot.appendChild(u);else if(n.type===m.Document&&l.type==m.Element){let d=u,f=null;d.childNodes.forEach(y=>{y.nodeName==="BODY"&&(f=y)}),f?(d.removeChild(f),c.appendChild(u),d.appendChild(f)):c.appendChild(u)}else c.appendChild(u);a&&a(u,l.id)}return c}function La(n,e){function t(i){e(i)}for(let i of n.getIds())n.has(i)&&t(n.getNode(i))}function Oa(n,e){let t=e.getMeta(n);if(t?.type!==m.Element)return;let i=n;for(let r in t.attributes){if(!(Object.prototype.hasOwnProperty.call(t.attributes,r)&&r.startsWith("rr_")))continue;let s=t.attributes[r];r==="rr_scrollLeft"&&(i.scrollLeft=s),r==="rr_scrollTop"&&(i.scrollTop=s)}}function Na(n,e){let{doc:t,onVisit:i,hackCss:r=!0,afterAppend:s,cache:a,mirror:o=new J}=e,c=Ht(n,{doc:t,mirror:o,skipChild:!1,hackCss:r,afterAppend:s,cache:a});return La(o,l=>{i&&i(l),Oa(l,o)}),c}var qr,Xr,ii,m,ri,ni,Ee,Zr,nt,st,k,J,si,mn,yn,vn,bn,Hi,wn,ut,j,ai,An,En,oi,Un,ci,$n,Hn,Pt,E,Vi,Gn,zn,Vn,R,li,ui,ht,It,de,hi,dt,Wi,Wn,Ve,Ce,jn,Qn,Yn,Jn,gt,Ke,qn,mt,We,Xn,Zn,es,ts,di,fi,is,rs,at,ns,yt,ji,as,os,pi,Te,vt,bt,cs,ot,gi,ls,ct,us,mi,He,je,Qi,Oe,Ne,Yi,Ji,qi,yi,hs,ds,fs,ps,Xi,gs,wt,Qe,Zi,er,tr,ir,ms,rr,_t,Rt,nr,L,H,ys,cr,lr,oe,Dt,St,ur,vs,At,Lt,lt,vi,ke,bi,xe,ne,Me,Pe,Ie,bs,ws,Ss,As,Es,Cs,Ts,ks,xs,Ms,_e,Re,Ps,wi,Is,hr,Be,Ot,dr,fr,pr,q,fe,ce,gr,mr,_s,Fe,Nt,Rs,Ds,Ls,Os,Ns,Si,Ai,$s,Hs,Bs,Fs,Gs,Ut,D,zs,Vs,Ks,Ws,js,Ei,Qs,Ys,Js,qs,Xs,X,Ct,Z,br,Zs,ea,ta,ia,Tt,ra,na,sa,aa,oa,le,ca,la,ua,ha,da,fa,pa,ga,ma,ya,wr,va,ba,$t,wa,Sa,Sr,Aa,Ar,Er,Ea,Ca,Ta,ka,Cr,Tr,xa,Ma,C,Ti,xr=$(()=>{qr=Object.defineProperty,Xr=(n,e,t)=>e in n?qr(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ii=(n,e,t)=>Xr(n,typeof e!="symbol"?e+"":e,t),m=(n=>(n[n.Document=0]="Document",n[n.DocumentType=1]="DocumentType",n[n.Element=2]="Element",n[n.Text=3]="Text",n[n.CDATA=4]="CDATA",n[n.Comment=5]="Comment",n))(m||{}),ri={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},ni={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Ee={},Zr=()=>!!globalThis.Zone;nt={};st={};k={childNodes:en,parentNode:tn,parentElement:rn,textContent:nn,contains:sn,getRootNode:an,host:on,styleSheets:cn,shadowRoot:ln,querySelector:un,querySelectorAll:hn,mutationObserver:dn};J=class{constructor(){ii(this,"idNodeMap",new Map),ii(this,"nodeMetaMap",new WeakMap)}getId(e){var t;return e?((t=this.getMeta(e))==null?void 0:t.id)??-1:-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){let t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(i=>this.removeNodeFromMap(i))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){let i=t.id;this.idNodeMap.set(i,e),this.nodeMetaMap.set(e,t)}replace(e,t){let i=this.getNode(e);if(i){let r=this.nodeMetaMap.get(i);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}};si="__rrweb_original__";mn=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,yn=/^(?:[a-z+]+:)?\/\//i,vn=/^www\..*/i,bn=/^(data:)([^,]*),(.*)/i;Hi=1,wn=new RegExp("[^a-z0-9-_:]"),ut=-2;An=/^[^ \t\n\r\u000c]+/,En=/^[, \t\n\r\u000c]+/;oi=new WeakMap;Un=/(max|min)-device-(width|height)/,ci=new RegExp(Un.source,"g"),$n={postcssPlugin:"postcss-custom-selectors",prepare(){return{postcssPlugin:"postcss-custom-selectors",AtRule:function(n){n.params.match(ci)&&(n.params=n.params.replace(ci,"$1-$2"))}}}},Hn={postcssPlugin:"postcss-hover-classes",prepare:function(){let n=[];return{Rule:function(e){n.indexOf(e)===-1&&(n.push(e),e.selectors.forEach(function(t){t.includes(":hover")&&(e.selector+=`,
|
|
3
|
+
`+t.replace(/:hover/g,".\\:hover"))}))}}}};Pt={exports:{}},E=String,Vi=function(){return{isColorSupported:!1,reset:E,bold:E,dim:E,italic:E,underline:E,inverse:E,hidden:E,strikethrough:E,black:E,red:E,green:E,yellow:E,blue:E,magenta:E,cyan:E,white:E,gray:E,bgBlack:E,bgRed:E,bgGreen:E,bgYellow:E,bgBlue:E,bgMagenta:E,bgCyan:E,bgWhite:E}};Pt.exports=Vi();Pt.exports.createColors=Vi;Gn=Pt.exports,zn={},Vn=Object.freeze(Object.defineProperty({__proto__:null,default:zn},Symbol.toStringTag,{value:"Module"})),R=Fn(Vn),li=Gn,ui=R,ht=class Ki extends Error{constructor(e,t,i,r,s,a){super(e),this.name="CssSyntaxError",this.reason=e,s&&(this.file=s),r&&(this.source=r),a&&(this.plugin=a),typeof t<"u"&&typeof i<"u"&&(typeof t=="number"?(this.line=t,this.column=i):(this.line=t.line,this.column=t.column,this.endLine=i.line,this.endColumn=i.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,Ki)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",typeof this.line<"u"&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;e==null&&(e=li.isColorSupported),ui&&e&&(t=ui(t));let i=t.split(/\r?\n/),r=Math.max(this.line-3,0),s=Math.min(this.line+2,i.length),a=String(s).length,o,c;if(e){let{bold:l,gray:u,red:d}=li.createColors(!0);o=f=>l(d(f)),c=f=>u(f)}else o=c=l=>l;return i.slice(r,s).map((l,u)=>{let d=r+1+u,f=" "+(" "+d).slice(-a)+" | ";if(d===this.line){let y=c(f.replace(/\d/g," "))+l.slice(0,this.column-1).replace(/[^\t]/g," ");return o(">")+c(f)+l+`
|
|
4
|
+
`+y+o("^")}return" "+c(f)+l}).join(`
|
|
5
|
+
`)}toString(){let e=this.showSourceCode();return e&&(e=`
|
|
6
|
+
|
|
7
|
+
`+e+`
|
|
8
|
+
`),this.name+": "+this.message+e}},It=ht;ht.default=ht;de={};de.isClean=Symbol("isClean");de.my=Symbol("my");hi={after:`
|
|
9
|
+
`,beforeClose:`
|
|
10
|
+
`,beforeComment:`
|
|
11
|
+
`,beforeDecl:`
|
|
12
|
+
`,beforeOpen:" ",beforeRule:`
|
|
13
|
+
`,colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};dt=class{constructor(e){this.builder=e}atrule(e,t){let i="@"+e.name,r=e.params?this.rawValue(e,"params"):"";if(typeof e.raws.afterName<"u"?i+=e.raws.afterName:r&&(i+=" "),e.nodes)this.block(e,i+r);else{let s=(e.raws.between||"")+(t?";":"");this.builder(i+r+s,e)}}beforeAfter(e,t){let i;e.type==="decl"?i=this.raw(e,null,"beforeDecl"):e.type==="comment"?i=this.raw(e,null,"beforeComment"):t==="before"?i=this.raw(e,null,"beforeRule"):i=this.raw(e,null,"beforeClose");let r=e.parent,s=0;for(;r&&r.type!=="root";)s+=1,r=r.parent;if(i.includes(`
|
|
14
|
+
`)){let a=this.raw(e,null,"indent");if(a.length)for(let o=0;o<s;o++)i+=a}return i}block(e,t){let i=this.raw(e,"between","beforeOpen");this.builder(t+i+"{",e,"start");let r;e.nodes&&e.nodes.length?(this.body(e),r=this.raw(e,"after")):r=this.raw(e,"after","emptyBody"),r&&this.builder(r),this.builder("}",e,"end")}body(e){let t=e.nodes.length-1;for(;t>0&&e.nodes[t].type==="comment";)t-=1;let i=this.raw(e,"semicolon");for(let r=0;r<e.nodes.length;r++){let s=e.nodes[r],a=this.raw(s,"before");a&&this.builder(a),this.stringify(s,t!==r||i)}}comment(e){let t=this.raw(e,"left","commentLeft"),i=this.raw(e,"right","commentRight");this.builder("/*"+t+e.text+i+"*/",e)}decl(e,t){let i=this.raw(e,"between","colon"),r=e.prop+i+this.rawValue(e,"value");e.important&&(r+=e.raws.important||" !important"),t&&(r+=";"),this.builder(r,e)}document(e){this.body(e)}raw(e,t,i){let r;if(i||(i=t),t&&(r=e.raws[t],typeof r<"u"))return r;let s=e.parent;if(i==="before"&&(!s||s.type==="root"&&s.first===e||s&&s.type==="document"))return"";if(!s)return hi[i];let a=e.root();if(a.rawCache||(a.rawCache={}),typeof a.rawCache[i]<"u")return a.rawCache[i];if(i==="before"||i==="after")return this.beforeAfter(e,i);{let o="raw"+Kn(i);this[o]?r=this[o](a,e):a.walk(c=>{if(r=c.raws[t],typeof r<"u")return!1})}return typeof r>"u"&&(r=hi[i]),a.rawCache[i]=r,r}rawBeforeClose(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length>0&&typeof i.raws.after<"u")return t=i.raws.after,t.includes(`
|
|
15
|
+
`)&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let i;return e.walkComments(r=>{if(typeof r.raws.before<"u")return i=r.raws.before,i.includes(`
|
|
16
|
+
`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i>"u"?i=this.raw(t,null,"beforeDecl"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeDecl(e,t){let i;return e.walkDecls(r=>{if(typeof r.raws.before<"u")return i=r.raws.before,i.includes(`
|
|
17
|
+
`)&&(i=i.replace(/[^\n]+$/,"")),!1}),typeof i>"u"?i=this.raw(t,null,"beforeRule"):i&&(i=i.replace(/\S/g,"")),i}rawBeforeOpen(e){let t;return e.walk(i=>{if(i.type!=="decl"&&(t=i.raws.between,typeof t<"u"))return!1}),t}rawBeforeRule(e){let t;return e.walk(i=>{if(i.nodes&&(i.parent!==e||e.first!==i)&&typeof i.raws.before<"u")return t=i.raws.before,t.includes(`
|
|
18
|
+
`)&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(i=>{if(typeof i.raws.between<"u")return t=i.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length===0&&(t=i.raws.after,typeof t<"u"))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(i=>{let r=i.parent;if(r&&r!==e&&r.parent&&r.parent===e&&typeof i.raws.before<"u"){let s=i.raws.before.split(`
|
|
19
|
+
`);return t=s[s.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(i=>{if(i.nodes&&i.nodes.length&&i.last.type==="decl"&&(t=i.raws.semicolon,typeof t<"u"))return!1}),t}rawValue(e,t){let i=e[t],r=e.raws[t];return r&&r.value===i?r.raw:i}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}},Wi=dt;dt.default=dt;Wn=Wi;Ve=ft;ft.default=ft;({isClean:Ce,my:jn}=de),Qn=It,Yn=Wi,Jn=Ve;gt=class{constructor(e={}){this.raws={},this[Ce]=!1,this[jn]=!0;for(let t in e)if(t==="nodes"){this.nodes=[];for(let i of e[t])typeof i.clone=="function"?this.append(i.clone()):this.append(i)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=pt(this);for(let i in e)t[i]=e[i];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:i,start:r}=this.rangeBy(t);return this.source.input.error(e,{column:r.column,line:r.line},{column:i.column,line:i.line},t)}return new Qn(e)}getProxyProcessor(){return{get(e,t){return t==="proxyOf"?e:t==="root"?()=>e.root().toProxy():e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="prop"||t==="value"||t==="name"||t==="params"||t==="important"||t==="text")&&e.markDirty()),!0}}}markDirty(){if(this[Ce]){this[Ce]=!1;let e=this;for(;e=e.parent;)e[Ce]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let i=this.source.start;if(e.index)i=this.positionInside(e.index,t);else if(e.word){t=this.toString();let r=t.indexOf(e.word);r!==-1&&(i=this.positionInside(r,t))}return i}positionInside(e,t){let i=t||this.toString(),r=this.source.start.column,s=this.source.start.line;for(let a=0;a<e;a++)i[a]===`
|
|
20
|
+
`?(r=1,s+=1):r+=1;return{column:r,line:s}}prev(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e-1]}rangeBy(e){let t={column:this.source.start.column,line:this.source.start.line},i=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:t.column+1,line:t.line};if(e.word){let r=this.toString(),s=r.indexOf(e.word);s!==-1&&(t=this.positionInside(s,r),i=this.positionInside(s+e.word.length,r))}else e.start?t={column:e.start.column,line:e.start.line}:e.index&&(t=this.positionInside(e.index)),e.end?i={column:e.end.column,line:e.end.line}:typeof e.endIndex=="number"?i=this.positionInside(e.endIndex):e.index&&(i=this.positionInside(e.index+1));return(i.line<t.line||i.line===t.line&&i.column<=t.column)&&(i={column:t.column+1,line:t.line}),{end:i,start:t}}raw(e,t){return new Yn().raw(this,e,t)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...e){if(this.parent){let t=this,i=!1;for(let r of e)r===this?i=!0:i?(this.parent.insertAfter(t,r),t=r):this.parent.insertBefore(t,r);i||this.remove()}return this}root(){let e=this;for(;e.parent&&e.parent.type!=="document";)e=e.parent;return e}toJSON(e,t){let i={},r=t==null;t=t||new Map;let s=0;for(let a in this){if(!Object.prototype.hasOwnProperty.call(this,a)||a==="parent"||a==="proxyCache")continue;let o=this[a];if(Array.isArray(o))i[a]=o.map(c=>typeof c=="object"&&c.toJSON?c.toJSON(null,t):c);else if(typeof o=="object"&&o.toJSON)i[a]=o.toJSON(null,t);else if(a==="source"){let c=t.get(o.input);c==null&&(c=s,t.set(o.input,s),s++),i[a]={end:o.end,inputId:c,start:o.start}}else i[a]=o}return r&&(i.inputs=[...t.keys()].map(a=>a.toJSON())),i}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Jn){e.stringify&&(e=e.stringify);let t="";return e(this,i=>{t+=i}),t}warn(e,t,i){let r={node:this};for(let s in i)r[s]=i[s];return e.warn(t,r)}get proxyOf(){return this}},Ke=gt;gt.default=gt;qn=Ke,mt=class extends qn{constructor(e){e&&typeof e.value<"u"&&typeof e.value!="string"&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||this.prop[0]==="$"}},We=mt;mt.default=mt;Xn="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Zn=(n,e=21)=>(t=e)=>{let i="",r=t;for(;r--;)i+=n[Math.random()*n.length|0];return i},es=(n=21)=>{let e="",t=n;for(;t--;)e+=Xn[Math.random()*64|0];return e},ts={nanoid:es,customAlphabet:Zn},{SourceMapConsumer:di,SourceMapGenerator:fi}=R,{existsSync:is,readFileSync:rs}=R,{dirname:at,join:ns}=R;yt=class{constructor(e,t){if(t.map===!1)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let i=t.map?t.map.prev:void 0,r=this.loadMap(t.from,i);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=at(this.mapFile)),r&&(this.text=r)}consumer(){return this.consumerCache||(this.consumerCache=new di(this.text)),this.consumerCache}decodeInline(e){let t=/^data:application\/json;charset=utf-?8;base64,/,i=/^data:application\/json;base64,/,r=/^data:application\/json;charset=utf-?8,/,s=/^data:application\/json,/;if(r.test(e)||s.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(t.test(e)||i.test(e))return ss(e.substr(RegExp.lastMatch.length));let a=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+a)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return typeof e!="object"?!1:typeof e.mappings=="string"||typeof e._mappings=="string"||Array.isArray(e.sections)}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let i=e.lastIndexOf(t.pop()),r=e.indexOf("*/",i);i>-1&&r>-1&&(this.annotation=this.getAnnotationURL(e.substring(i,r)))}loadFile(e){if(this.root=at(e),is(e))return this.mapFile=e,rs(e,"utf-8").toString().trim()}loadMap(e,t){if(t===!1)return!1;if(t){if(typeof t=="string")return t;if(typeof t=="function"){let i=t(e);if(i){let r=this.loadFile(i);if(!r)throw new Error("Unable to load previous source map: "+i.toString());return r}}else{if(t instanceof di)return fi.fromSourceMap(t).toString();if(t instanceof fi)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let i=this.annotation;return e&&(i=ns(at(e),i)),this.loadFile(i)}}}startWith(e,t){return e?e.substr(0,t.length)===t:!1}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}},ji=yt;yt.default=yt;({SourceMapConsumer:as,SourceMapGenerator:os}=R),{fileURLToPath:pi,pathToFileURL:Te}=R,{isAbsolute:vt,resolve:bt}=R,{nanoid:cs}=ts,ot=R,gi=It,ls=ji,ct=Symbol("fromOffsetCache"),us=!!(as&&os),mi=!!(bt&&vt),He=class{constructor(e,t={}){if(e===null||typeof e>"u"||typeof e=="object"&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),this.css[0]==="\uFEFF"||this.css[0]==="\uFFFE"?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!mi||/^\w+:\/\//.test(t.from)||vt(t.from)?this.file=t.from:this.file=bt(t.from)),mi&&us){let i=new ls(this.css,t);if(i.text){this.map=i;let r=i.consumer().file;!this.file&&r&&(this.file=this.mapResolve(r))}}this.file||(this.id="<input css "+cs(6)+">"),this.map&&(this.map.file=this.from)}error(e,t,i,r={}){let s,a,o;if(t&&typeof t=="object"){let l=t,u=i;if(typeof l.offset=="number"){let d=this.fromOffset(l.offset);t=d.line,i=d.col}else t=l.line,i=l.column;if(typeof u.offset=="number"){let d=this.fromOffset(u.offset);a=d.line,o=d.col}else a=u.line,o=u.column}else if(!i){let l=this.fromOffset(t);t=l.line,i=l.col}let c=this.origin(t,i,a,o);return c?s=new gi(e,c.endLine===void 0?c.line:{column:c.column,line:c.line},c.endLine===void 0?c.column:{column:c.endColumn,line:c.endLine},c.source,c.file,r.plugin):s=new gi(e,a===void 0?t:{column:i,line:t},a===void 0?i:{column:o,line:a},this.css,this.file,r.plugin),s.input={column:i,endColumn:o,endLine:a,line:t,source:this.css},this.file&&(Te&&(s.input.url=Te(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,i;if(this[ct])i=this[ct];else{let s=this.css.split(`
|
|
21
|
+
`);i=new Array(s.length);let a=0;for(let o=0,c=s.length;o<c;o++)i[o]=a,a+=s[o].length+1;this[ct]=i}t=i[i.length-1];let r=0;if(e>=t)r=i.length-1;else{let s=i.length-2,a;for(;r<s;)if(a=r+(s-r>>1),e<i[a])s=a-1;else if(e>=i[a+1])r=a+1;else{r=a;break}}return{col:e-i[r]+1,line:r+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:bt(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,i,r){if(!this.map)return!1;let s=this.map.consumer(),a=s.originalPositionFor({column:t,line:e});if(!a.source)return!1;let o;typeof i=="number"&&(o=s.originalPositionFor({column:r,line:i}));let c;vt(a.source)?c=Te(a.source):c=new URL(a.source,this.map.consumer().sourceRoot||Te(this.map.mapFile));let l={column:a.column,endColumn:o&&o.column,endLine:o&&o.line,line:a.line,url:c.toString()};if(c.protocol==="file:")if(pi)l.file=pi(c);else throw new Error("file: protocol is not available in this PostCSS build");let u=s.sourceContentFor(a.source);return u&&(l.source=u),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])this[t]!=null&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}},je=He;He.default=He;ot&&ot.registerInput&&ot.registerInput(He);({SourceMapConsumer:Qi,SourceMapGenerator:Oe}=R),{dirname:Ne,relative:Yi,resolve:Ji,sep:qi}=R,{pathToFileURL:yi}=R,hs=je,ds=!!(Qi&&Oe),fs=!!(Ne&&Ji&&Yi&&qi),ps=class{constructor(e,t,i,r){this.stringify=e,this.mapOpts=i.map||{},this.root=t,this.opts=i,this.css=r,this.originalCSS=r,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;this.isInline()?e="data:application/json;base64,"+this.toBase64(this.map.toString()):typeof this.mapOpts.annotation=="string"?e=this.mapOpts.annotation:typeof this.mapOpts.annotation=="function"?e=this.mapOpts.annotation(this.opts.to,this.root):e=this.outputFile()+".map";let t=`
|
|
22
|
+
`;this.css.includes(`\r
|
|
23
|
+
`)&&(t=`\r
|
|
24
|
+
`),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t=this.toUrl(this.path(e.file)),i=e.root||Ne(e.file),r;this.mapOpts.sourcesContent===!1?(r=new Qi(e.text),r.sourcesContent&&(r.sourcesContent=null)):r=e.consumer(),this.map.applySourceMap(r,t,this.toUrl(this.path(i)))}}clearAnnotation(){if(this.mapOpts.annotation!==!1)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],e.type==="comment"&&e.text.indexOf("# sourceMappingURL=")===0&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),fs&&ds&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(this.previous().length===1){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=Oe.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Oe({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Oe({file:this.outputFile(),ignoreInvalidMapping:!0});let e=1,t=1,i="<no source>",r={generated:{column:0,line:0},original:{column:0,line:0},source:""},s,a;this.stringify(this.root,(o,c,l)=>{if(this.css+=o,c&&l!=="end"&&(r.generated.line=e,r.generated.column=t-1,c.source&&c.source.start?(r.source=this.sourcePath(c),r.original.line=c.source.start.line,r.original.column=c.source.start.column-1,this.map.addMapping(r)):(r.source=i,r.original.line=1,r.original.column=0,this.map.addMapping(r))),s=o.match(/\n/g),s?(e+=s.length,a=o.lastIndexOf(`
|
|
25
|
+
`),t=o.length-a):t+=o.length,c&&l!=="start"){let u=c.parent||{raws:{}};(!(c.type==="decl"||c.type==="atrule"&&!c.nodes)||c!==u.last||u.raws.semicolon)&&(c.source&&c.source.end?(r.source=this.sourcePath(c),r.original.line=c.source.end.line,r.original.column=c.source.end.column-1,r.generated.line=e,r.generated.column=t-2,this.map.addMapping(r)):(r.source=i,r.original.line=1,r.original.column=0,r.generated.line=e,r.generated.column=t-1,this.map.addMapping(r)))}})}isAnnotation(){return this.isInline()?!0:typeof this.mapOpts.annotation<"u"?this.mapOpts.annotation:this.previous().length?this.previous().some(e=>e.annotation):!0}isInline(){if(typeof this.mapOpts.inline<"u")return this.mapOpts.inline;let e=this.mapOpts.annotation;return typeof e<"u"&&e!==!0?!1:this.previous().length?this.previous().some(t=>t.inline):!0}isMap(){return typeof this.opts.map<"u"?!!this.opts.map:this.previous().length>0}isSourcesContent(){return typeof this.mapOpts.sourcesContent<"u"?this.mapOpts.sourcesContent:this.previous().length?this.previous().some(e=>e.withContent()):!0}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute||e.charCodeAt(0)===60||/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let i=this.opts.to?Ne(this.opts.to):".";typeof this.mapOpts.annotation=="string"&&(i=Ne(Ji(i,this.mapOpts.annotation)));let r=Yi(i,e);return this.memoizedPaths.set(e,r),r}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new hs(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let i=t.source.input.from;if(i&&!e[i]){e[i]=!0;let r=this.usesFileUrls?this.toFileUrl(i):this.toUrl(this.path(i));this.map.setSourceContent(r,t.source.input.css)}}});else if(this.css){let t=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(t,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(yi){let i=yi(e).toString();return this.memoizedFileURLs.set(e,i),i}else throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;qi==="\\"&&(e=e.replace(/\\/g,"/"));let i=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,i),i}},Xi=ps,gs=Ke,wt=class extends gs{constructor(e){super(e),this.type="comment"}},Qe=wt;wt.default=wt;({isClean:Zi,my:er}=de),tr=We,ir=Qe,ms=Ke;L=class or extends ms{append(...e){for(let t of e){let i=this.normalize(t,this.last);for(let r of i)this.proxyOf.nodes.push(r)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t=this.getIterator(),i,r;for(;this.indexes[t]<this.proxyOf.nodes.length&&(i=this.indexes[t],r=e(this.proxyOf.nodes[i],i),r!==!1);)this.indexes[t]+=1;return delete this.indexes[t],r}every(e){return this.nodes.every(e)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}getProxyProcessor(){return{get(e,t){return t==="proxyOf"?e:e[t]?t==="each"||typeof t=="string"&&t.startsWith("walk")?(...i)=>e[t](...i.map(r=>typeof r=="function"?(s,a)=>r(s.toProxy(),a):r)):t==="every"||t==="some"?i=>e[t]((r,...s)=>i(r.toProxy(),...s)):t==="root"?()=>e.root().toProxy():t==="nodes"?e.nodes.map(i=>i.toProxy()):t==="first"||t==="last"?e[t].toProxy():e[t]:e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="name"||t==="params"||t==="selector")&&e.markDirty()),!0}}}index(e){return typeof e=="number"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let i=this.index(e),r=this.normalize(t,this.proxyOf.nodes[i]).reverse();i=this.index(e);for(let a of r)this.proxyOf.nodes.splice(i+1,0,a);let s;for(let a in this.indexes)s=this.indexes[a],i<s&&(this.indexes[a]=s+r.length);return this.markDirty(),this}insertBefore(e,t){let i=this.index(e),r=i===0?"prepend":!1,s=this.normalize(t,this.proxyOf.nodes[i],r).reverse();i=this.index(e);for(let o of s)this.proxyOf.nodes.splice(i,0,o);let a;for(let o in this.indexes)a=this.indexes[o],i<=a&&(this.indexes[o]=a+s.length);return this.markDirty(),this}normalize(e,t){if(typeof e=="string")e=sr(rr(e).nodes);else if(typeof e>"u")e=[];else if(Array.isArray(e)){e=e.slice(0);for(let r of e)r.parent&&r.parent.removeChild(r,"ignore")}else if(e.type==="root"&&this.type!=="document"){e=e.nodes.slice(0);for(let r of e)r.parent&&r.parent.removeChild(r,"ignore")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value>"u")throw new Error("Value field is missed in node creation");typeof e.value!="string"&&(e.value=String(e.value)),e=[new tr(e)]}else if(e.selector)e=[new _t(e)];else if(e.name)e=[new Rt(e)];else if(e.text)e=[new ir(e)];else throw new Error("Unknown node type in node creation");return e.map(r=>(r[er]||or.rebuild(r),r=r.proxyOf,r.parent&&r.parent.removeChild(r),r[Zi]&&ar(r),typeof r.raws.before>"u"&&t&&typeof t.raws.before<"u"&&(r.raws.before=t.raws.before.replace(/\S/g,"")),r.parent=this.proxyOf,r))}prepend(...e){e=e.reverse();for(let t of e){let i=this.normalize(t,this.first,"prepend").reverse();for(let r of i)this.proxyOf.nodes.unshift(r);for(let r in this.indexes)this.indexes[r]=this.indexes[r]+i.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);let t;for(let i in this.indexes)t=this.indexes[i],t>=e&&(this.indexes[i]=t-1);return this.markDirty(),this}replaceValues(e,t,i){return i||(i=t,t={}),this.walkDecls(r=>{t.props&&!t.props.includes(r.prop)||t.fast&&!r.value.includes(t.fast)||(r.value=r.value.replace(e,i))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,i)=>{let r;try{r=e(t,i)}catch(s){throw t.addToError(s)}return r!==!1&&t.walk&&(r=t.walk(e)),r})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((i,r)=>{if(i.type==="atrule"&&e.test(i.name))return t(i,r)}):this.walk((i,r)=>{if(i.type==="atrule"&&i.name===e)return t(i,r)}):(t=e,this.walk((i,r)=>{if(i.type==="atrule")return t(i,r)}))}walkComments(e){return this.walk((t,i)=>{if(t.type==="comment")return e(t,i)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((i,r)=>{if(i.type==="decl"&&e.test(i.prop))return t(i,r)}):this.walk((i,r)=>{if(i.type==="decl"&&i.prop===e)return t(i,r)}):(t=e,this.walk((i,r)=>{if(i.type==="decl")return t(i,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((i,r)=>{if(i.type==="rule"&&e.test(i.selector))return t(i,r)}):this.walk((i,r)=>{if(i.type==="rule"&&i.selector===e)return t(i,r)}):(t=e,this.walk((i,r)=>{if(i.type==="rule")return t(i,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};L.registerParse=n=>{rr=n};L.registerRule=n=>{_t=n};L.registerAtRule=n=>{Rt=n};L.registerRoot=n=>{nr=n};H=L;L.default=L;L.rebuild=n=>{n.type==="atrule"?Object.setPrototypeOf(n,Rt.prototype):n.type==="rule"?Object.setPrototypeOf(n,_t.prototype):n.type==="decl"?Object.setPrototypeOf(n,tr.prototype):n.type==="comment"?Object.setPrototypeOf(n,ir.prototype):n.type==="root"&&Object.setPrototypeOf(n,nr.prototype),n[er]=!0,n.nodes&&n.nodes.forEach(e=>{L.rebuild(e)})};ys=H,oe=class extends ys{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new cr(new lr,this,e).stringify()}};oe.registerLazyResult=n=>{cr=n};oe.registerProcessor=n=>{lr=n};Dt=oe;oe.default=oe;St=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let i=t.node.rangeBy(t);this.line=i.start.line,this.column=i.start.column,this.endLine=i.end.line,this.endColumn=i.end.column}for(let i in t)this[i]=t[i]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}},ur=St;St.default=St;vs=ur,At=class{constructor(e,t,i){this.processor=e,this.messages=[],this.root=t,this.opts=i,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let i=new vs(e,t);return this.messages.push(i),i}warnings(){return this.messages.filter(e=>e.type==="warning")}get content(){return this.css}},Lt=At;At.default=At;lt=39,vi=34,ke=92,bi=47,xe=10,ne=32,Me=12,Pe=9,Ie=13,bs=91,ws=93,Ss=40,As=41,Es=123,Cs=125,Ts=59,ks=42,xs=58,Ms=64,_e=/[\t\n\f\r "#'()/;[\\\]{}]/g,Re=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Ps=/.[\r\n"'(/\\]/,wi=/[\da-f]/i,Is=function(e,t={}){let i=e.css.valueOf(),r=t.ignoreErrors,s,a,o,c,l,u,d,f,y,g,v=i.length,h=0,T=[],x=[];function p(){return h}function b(O){throw e.error("Unclosed "+O,h)}function M(){return x.length===0&&h>=v}function I(O){if(x.length)return x.pop();if(h>=v)return;let _=O?O.ignoreUnclosed:!1;switch(s=i.charCodeAt(h),s){case xe:case ne:case Pe:case Ie:case Me:{a=h;do a+=1,s=i.charCodeAt(a);while(s===ne||s===xe||s===Pe||s===Ie||s===Me);g=["space",i.slice(h,a)],h=a-1;break}case bs:case ws:case Es:case Cs:case xs:case Ts:case As:{let N=String.fromCharCode(s);g=[N,N,h];break}case Ss:{if(f=T.length?T.pop()[1]:"",y=i.charCodeAt(h+1),f==="url"&&y!==lt&&y!==vi&&y!==ne&&y!==xe&&y!==Pe&&y!==Me&&y!==Ie){a=h;do{if(u=!1,a=i.indexOf(")",a+1),a===-1)if(r||_){a=h;break}else b("bracket");for(d=a;i.charCodeAt(d-1)===ke;)d-=1,u=!u}while(u);g=["brackets",i.slice(h,a+1),h,a],h=a}else a=i.indexOf(")",h+1),c=i.slice(h,a+1),a===-1||Ps.test(c)?g=["(","(",h]:(g=["brackets",c,h,a],h=a);break}case lt:case vi:{o=s===lt?"'":'"',a=h;do{if(u=!1,a=i.indexOf(o,a+1),a===-1)if(r||_){a=h+1;break}else b("string");for(d=a;i.charCodeAt(d-1)===ke;)d-=1,u=!u}while(u);g=["string",i.slice(h,a+1),h,a],h=a;break}case Ms:{_e.lastIndex=h+1,_e.test(i),_e.lastIndex===0?a=i.length-1:a=_e.lastIndex-2,g=["at-word",i.slice(h,a+1),h,a],h=a;break}case ke:{for(a=h,l=!0;i.charCodeAt(a+1)===ke;)a+=1,l=!l;if(s=i.charCodeAt(a+1),l&&s!==bi&&s!==ne&&s!==xe&&s!==Pe&&s!==Ie&&s!==Me&&(a+=1,wi.test(i.charAt(a)))){for(;wi.test(i.charAt(a+1));)a+=1;i.charCodeAt(a+1)===ne&&(a+=1)}g=["word",i.slice(h,a+1),h,a],h=a;break}default:{s===bi&&i.charCodeAt(h+1)===ks?(a=i.indexOf("*/",h+2)+1,a===0&&(r||_?a=i.length:b("comment")),g=["comment",i.slice(h,a+1),h,a],h=a):(Re.lastIndex=h+1,Re.test(i),Re.lastIndex===0?a=i.length-1:a=Re.lastIndex-2,g=["word",i.slice(h,a+1),h,a],T.push(g),h=a);break}}return h++,g}function B(O){x.push(O)}return{back:B,endOfFile:M,nextToken:I,position:p}},hr=H,Be=class extends hr{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}},Ot=Be;Be.default=Be;hr.registerAtRule(Be);dr=H,q=class extends dr{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,i){let r=super.normalize(e);if(t){if(i==="prepend")this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let s of r)s.raws.before=t.raws.before}return r}removeChild(e,t){let i=this.index(e);return!t&&i===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[i].raws.before),super.removeChild(e)}toResult(e={}){return new fr(new pr,this,e).stringify()}};q.registerLazyResult=n=>{fr=n};q.registerProcessor=n=>{pr=n};fe=q;q.default=q;dr.registerRoot(q);ce={comma(n){return ce.split(n,[","],!0)},space(n){let e=[" ",`
|
|
26
|
+
`," "];return ce.split(n,e)},split(n,e,t){let i=[],r="",s=!1,a=0,o=!1,c="",l=!1;for(let u of n)l?l=!1:u==="\\"?l=!0:o?u===c&&(o=!1):u==='"'||u==="'"?(o=!0,c=u):u==="("?a+=1:u===")"?a>0&&(a-=1):a===0&&e.includes(u)&&(s=!0),s?(r!==""&&i.push(r.trim()),r="",s=!1):r+=u;return(t||r!=="")&&i.push(r.trim()),i}},gr=ce;ce.default=ce;mr=H,_s=gr,Fe=class extends mr{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return _s.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,i=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(i)}},Nt=Fe;Fe.default=Fe;mr.registerRule(Fe);Rs=We,Ds=Is,Ls=Qe,Os=Ot,Ns=fe,Si=Nt,Ai={empty:!0,space:!0};$s=class{constructor(e){this.input=e,this.root=new Ns,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t=new Os;t.name=e[1].slice(1),t.name===""&&this.unnamedAtrule(t,e),this.init(t,e[2]);let i,r,s,a=!1,o=!1,c=[],l=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),i=e[0],i==="("||i==="["?l.push(i==="("?")":"]"):i==="{"&&l.length>0?l.push("}"):i===l[l.length-1]&&l.pop(),l.length===0)if(i===";"){t.source.end=this.getPosition(e[2]),t.source.end.offset++,this.semicolon=!0;break}else if(i==="{"){o=!0;break}else if(i==="}"){if(c.length>0){for(s=c.length-1,r=c[s];r&&r[0]==="space";)r=c[--s];r&&(t.source.end=this.getPosition(r[3]||r[2]),t.source.end.offset++)}this.end(e);break}else c.push(e);else c.push(e);if(this.tokenizer.endOfFile()){a=!0;break}}t.raws.between=this.spacesAndCommentsFromEnd(c),c.length?(t.raws.afterName=this.spacesAndCommentsFromStart(c),this.raw(t,"params",c),a&&(e=c[c.length-1],t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++,this.spaces=t.raws.between,t.raws.between="")):(t.raws.afterName="",t.params=""),o&&(t.nodes=[],this.current=t)}checkMissedSemicolon(e){let t=this.colon(e);if(t===!1)return;let i=0,r;for(let s=t-1;s>=0&&(r=e[s],!(r[0]!=="space"&&(i+=1,i===2)));s--);throw this.input.error("Missed semicolon",r[0]==="word"?r[3]+1:r[2])}colon(e){let t=0,i,r,s;for(let[a,o]of e.entries()){if(i=o,r=i[0],r==="("&&(t+=1),r===")"&&(t-=1),t===0&&r===":")if(!s)this.doubleColon(i);else{if(s[0]==="word"&&s[1]==="progid")continue;return a}s=i}return!1}comment(e){let t=new Ls;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let i=e[1].slice(2,-2);if(/^\s*$/.test(i))t.text="",t.raws.left=i,t.raws.right="";else{let r=i.match(/^(\s*)([^]*\S)(\s*)$/);t.text=r[2],t.raws.left=r[1],t.raws.right=r[3]}}createTokenizer(){this.tokenizer=Ds(this.input)}decl(e,t){let i=new Rs;this.init(i,e[0][2]);let r=e[e.length-1];for(r[0]===";"&&(this.semicolon=!0,e.pop()),i.source.end=this.getPosition(r[3]||r[2]||Us(e)),i.source.end.offset++;e[0][0]!=="word";)e.length===1&&this.unknownWord(e),i.raws.before+=e.shift()[1];for(i.source.start=this.getPosition(e[0][2]),i.prop="";e.length;){let l=e[0][0];if(l===":"||l==="space"||l==="comment")break;i.prop+=e.shift()[1]}i.raws.between="";let s;for(;e.length;)if(s=e.shift(),s[0]===":"){i.raws.between+=s[1];break}else s[0]==="word"&&/\w/.test(s[1])&&this.unknownWord([s]),i.raws.between+=s[1];(i.prop[0]==="_"||i.prop[0]==="*")&&(i.raws.before+=i.prop[0],i.prop=i.prop.slice(1));let a=[],o;for(;e.length&&(o=e[0][0],!(o!=="space"&&o!=="comment"));)a.push(e.shift());this.precheckMissedSemicolon(e);for(let l=e.length-1;l>=0;l--){if(s=e[l],s[1].toLowerCase()==="!important"){i.important=!0;let u=this.stringFrom(e,l);u=this.spacesFromEnd(e)+u,u!==" !important"&&(i.raws.important=u);break}else if(s[1].toLowerCase()==="important"){let u=e.slice(0),d="";for(let f=l;f>0;f--){let y=u[f][0];if(d.trim().indexOf("!")===0&&y!=="space")break;d=u.pop()[1]+d}d.trim().indexOf("!")===0&&(i.important=!0,i.raws.important=d,e=u)}if(s[0]!=="space"&&s[0]!=="comment")break}e.some(l=>l[0]!=="space"&&l[0]!=="comment")&&(i.raws.between+=a.map(l=>l[1]).join(""),a=[]),this.raw(i,"value",a.concat(e),t),i.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new Si;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let t=this.current.nodes[this.current.nodes.length-1];t&&t.type==="rule"&&!t.raws.ownSemicolon&&(t.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="",e.type!=="comment"&&(this.semicolon=!1)}other(e){let t=!1,i=null,r=!1,s=null,a=[],o=e[1].startsWith("--"),c=[],l=e;for(;l;){if(i=l[0],c.push(l),i==="("||i==="[")s||(s=l),a.push(i==="("?")":"]");else if(o&&r&&i==="{")s||(s=l),a.push("}");else if(a.length===0)if(i===";")if(r){this.decl(c,o);return}else break;else if(i==="{"){this.rule(c);return}else if(i==="}"){this.tokenizer.back(c.pop()),t=!0;break}else i===":"&&(r=!0);else i===a[a.length-1]&&(a.pop(),a.length===0&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),a.length>0&&this.unclosedBracket(s),t&&r){if(!o)for(;c.length&&(l=c[c.length-1][0],!(l!=="space"&&l!=="comment"));)this.tokenizer.back(c.pop());this.decl(c,o)}else this.unknownWord(c)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e);break}this.endFile()}precheckMissedSemicolon(){}raw(e,t,i,r){let s,a,o=i.length,c="",l=!0,u,d;for(let f=0;f<o;f+=1)s=i[f],a=s[0],a==="space"&&f===o-1&&!r?l=!1:a==="comment"?(d=i[f-1]?i[f-1][0]:"empty",u=i[f+1]?i[f+1][0]:"empty",!Ai[d]&&!Ai[u]?c.slice(-1)===","?l=!1:c+=s[1]:l=!1):c+=s[1];if(!l){let f=i.reduce((y,g)=>y+g[1],"");e.raws[t]={raw:f,value:c}}e[t]=c}rule(e){e.pop();let t=new Si;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,i="";for(;e.length&&(t=e[e.length-1][0],!(t!=="space"&&t!=="comment"));)i=e.pop()[1]+i;return i}spacesAndCommentsFromStart(e){let t,i="";for(;e.length&&(t=e[0][0],!(t!=="space"&&t!=="comment"));)i+=e.shift()[1];return i}spacesFromEnd(e){let t,i="";for(;e.length&&(t=e[e.length-1][0],t==="space");)i=e.pop()[1]+i;return i}stringFrom(e,t){let i="";for(let r=t;r<e.length;r++)i+=e[r][1];return e.splice(t,e.length-t),i}unclosedBlock(){let e=this.current.source.start;throw this.input.error("Unclosed block",e.line,e.column)}unclosedBracket(e){throw this.input.error("Unclosed bracket",{offset:e[2]},{offset:e[2]+1})}unexpectedClose(e){throw this.input.error("Unexpected }",{offset:e[2]},{offset:e[2]+1})}unknownWord(e){throw this.input.error("Unknown word",{offset:e[0][2]},{offset:e[0][2]+e[0][1].length})}unnamedAtrule(e,t){throw this.input.error("At-rule without name",{offset:t[2]},{offset:t[2]+t[1].length})}},Hs=$s,Bs=H,Fs=Hs,Gs=je;Ut=Ge;Ge.default=Ge;Bs.registerParse(Ge);({isClean:D,my:zs}=de),Vs=Xi,Ks=Ve,Ws=H,js=Dt,Ei=Lt,Qs=Ut,Ys=fe,Js={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},qs={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Xs={Once:!0,postcssPlugin:!0,prepare:!0},X=0;Ct={},Z=class vr{constructor(e,t,i){this.stringified=!1,this.processed=!1;let r;if(typeof t=="object"&&t!==null&&(t.type==="root"||t.type==="document"))r=Et(t);else if(t instanceof vr||t instanceof Ei)r=Et(t.root),t.map&&(typeof i.map>"u"&&(i.map={}),i.map.inline||(i.map.inline=!1),i.map.prev=t.map);else{let s=Qs;i.syntax&&(s=i.syntax.parse),i.parser&&(s=i.parser),s.parse&&(s=s.parse);try{r=s(t,i)}catch(a){this.processed=!0,this.error=a}r&&!r[zs]&&Ws.rebuild(r)}this.result=new Ei(e,r,i),this.helpers={...Ct,postcss:Ct,result:this.result},this.plugins=this.processor.plugins.map(s=>typeof s=="object"&&s.prepare?{...s,...s.prepare(this.result)}:s)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let i=this.result.lastPlugin;try{t&&t.addToError(e),this.error=e,e.name==="CssSyntaxError"&&!e.plugin?(e.plugin=i.postcssPlugin,e.setMessage()):i.postcssVersion}catch(r){console&&console.error&&console.error(r)}return e}prepareVisitors(){this.listeners={};let e=(t,i,r)=>{this.listeners[i]||(this.listeners[i]=[]),this.listeners[i].push([t,r])};for(let t of this.plugins)if(typeof t=="object")for(let i in t){if(!qs[i]&&/^[A-Z]/.test(i))throw new Error(`Unknown event ${i} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Xs[i])if(typeof t[i]=="object")for(let r in t[i])r==="*"?e(t,i,t[i][r]):e(t,i+"-"+r.toLowerCase(),t[i][r]);else typeof t[i]=="function"&&e(t,i,t[i])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e<this.plugins.length;e++){let t=this.plugins[e],i=this.runOnRoot(t);if(se(i))try{await i}catch(r){throw this.handleError(r)}}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[D];){e[D]=!0;let t=[Ci(e)];for(;t.length>0;){let i=this.visitTick(t);if(se(i))try{await i}catch(r){let s=t[t.length-1].node;throw this.handleError(r,s)}}}if(this.listeners.OnceExit)for(let[t,i]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if(e.type==="document"){let r=e.nodes.map(s=>i(s,this.helpers));await Promise.all(r)}else await i(e,this.helpers)}catch(r){throw this.handleError(r)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if(typeof e=="object"&&e.Once){if(this.result.root.type==="document"){let t=this.result.root.nodes.map(i=>e.Once(i,this.helpers));return se(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}else if(typeof e=="function")return e(this.result.root,this.result)}catch(t){throw this.handleError(t)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=Ks;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new Vs(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){let t=this.runOnRoot(e);if(se(t))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[D];)e[D]=!0,this.walkSync(e);if(this.listeners.OnceExit)if(e.type==="document")for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[i,r]of e){this.result.lastPlugin=i;let s;try{s=r(t,this.helpers)}catch(a){throw this.handleError(a,t.proxyOf)}if(t.type!=="root"&&t.type!=="document"&&!t.parent)return!0;if(se(s))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:i,visitors:r}=t;if(i.type!=="root"&&i.type!=="document"&&!i.parent){e.pop();return}if(r.length>0&&t.visitorIndex<r.length){let[a,o]=r[t.visitorIndex];t.visitorIndex+=1,t.visitorIndex===r.length&&(t.visitors=[],t.visitorIndex=0),this.result.lastPlugin=a;try{return o(i.toProxy(),this.helpers)}catch(c){throw this.handleError(c,i)}}if(t.iterator!==0){let a=t.iterator,o;for(;o=i.nodes[i.indexes[a]];)if(i.indexes[a]+=1,!o[D]){o[D]=!0,e.push(Ci(o));return}t.iterator=0,delete i.indexes[a]}let s=t.events;for(;t.eventIndex<s.length;){let a=s[t.eventIndex];if(t.eventIndex+=1,a===X){i.nodes&&i.nodes.length&&(i[D]=!0,t.iterator=i.getIterator());return}else if(this.listeners[a]){t.visitors=this.listeners[a];return}}e.pop()}walkSync(e){e[D]=!0;let t=yr(e);for(let i of t)if(i===X)e.nodes&&e.each(r=>{r[D]||this.walkSync(r)});else{let r=this.listeners[i];if(r&&this.visitSync(r,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Z.registerPostcss=n=>{Ct=n};br=Z;Z.default=Z;Ys.registerLazyResult(Z);js.registerLazyResult(Z);Zs=Xi,ea=Ve,ta=Ut,ia=Lt,Tt=class{constructor(e,t,i){t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=i,this._map=void 0;let r,s=ea;this.result=new ia(this._processor,r,this._opts),this.result.css=t;let a=this;Object.defineProperty(this.result,"root",{get(){return a.root}});let o=new Zs(s,r,this._opts,t);if(o.isMap()){let[c,l]=o.generate();c&&(this.result.css=c),l&&(this.result.map=l)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=ta;try{e=t(this._css,this._opts)}catch(i){this.error=i}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}},ra=Tt;Tt.default=Tt;na=ra,sa=br,aa=Dt,oa=fe,le=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let i of e)if(i.postcss===!0?i=i():i.postcss&&(i=i.postcss),typeof i=="object"&&Array.isArray(i.plugins))t=t.concat(i.plugins);else if(typeof i=="object"&&i.postcssPlugin)t.push(i);else if(typeof i=="function")t.push(i);else if(!(typeof i=="object"&&(i.parse||i.stringify)))throw new Error(i+" is not a PostCSS plugin");return t}process(e,t={}){return!this.plugins.length&&!t.parser&&!t.stringifier&&!t.syntax?new na(this,e,t):new sa(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}},ca=le;le.default=le;oa.registerProcessor(le);aa.registerProcessor(le);la=We,ua=ji,ha=Qe,da=Ot,fa=je,pa=fe,ga=Nt;ma=ue;ue.default=ue;ya=It,wr=We,va=br,ba=H,$t=ca,wa=Ve,Sa=ma,Sr=Dt,Aa=ur,Ar=Qe,Er=Ot,Ea=Lt,Ca=je,Ta=Ut,ka=gr,Cr=Nt,Tr=fe,xa=Ke;w.plugin=function(e,t){let i=!1;function r(...a){console&&console.warn&&!i&&(i=!0,console.warn(e+`: postcss.plugin was deprecated. Migration guide:
|
|
27
|
+
https://evilmartians.com/chronicles/postcss-8-plugin-migration`),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+`: \u91CC\u9762 postcss.plugin \u88AB\u5F03\u7528. \u8FC1\u79FB\u6307\u5357:
|
|
28
|
+
https://www.w3ctech.com/topic/2226`));let o=t(...a);return o.postcssPlugin=e,o.postcssVersion=new $t().version,o}let s;return Object.defineProperty(r,"postcss",{get(){return s||(s=r()),s}}),r.process=function(a,o,c){return w([r(c)]).process(a,o)},r};w.stringify=wa;w.parse=Ta;w.fromJSON=Sa;w.list=ka;w.comment=n=>new Ar(n);w.atRule=n=>new Er(n);w.decl=n=>new wr(n);w.rule=n=>new Cr(n);w.root=n=>new Tr(n);w.document=n=>new Sr(n);w.CssSyntaxError=ya;w.Declaration=wr;w.Container=ba;w.Processor=$t;w.Document=Sr;w.Comment=Ar;w.Warning=Aa;w.AtRule=Er;w.Result=Ea;w.Input=Ca;w.Rule=Cr;w.Root=Tr;w.Node=xa;va.registerPostcss(w);Ma=w;w.default=w;C=Bn(Ma);C.stringify;C.fromJSON;C.plugin;C.parse;C.list;C.document;C.comment;C.atRule;C.rule;C.decl;C.root;C.CssSyntaxError;C.Declaration;C.Container;C.Processor;C.Document;C.Comment;C.Warning;C.AtRule;C.Result;C.Input;C.Rule;C.Root;C.Node;Ti={script:"noscript",altglyph:"altGlyph",altglyphdef:"altGlyphDef",altglyphitem:"altGlyphItem",animatecolor:"animateColor",animatemotion:"animateMotion",animatetransform:"animateTransform",clippath:"clipPath",feblend:"feBlend",fecolormatrix:"feColorMatrix",fecomponenttransfer:"feComponentTransfer",fecomposite:"feComposite",feconvolvematrix:"feConvolveMatrix",fediffuselighting:"feDiffuseLighting",fedisplacementmap:"feDisplacementMap",fedistantlight:"feDistantLight",fedropshadow:"feDropShadow",feflood:"feFlood",fefunca:"feFuncA",fefuncb:"feFuncB",fefuncg:"feFuncG",fefuncr:"feFuncR",fegaussianblur:"feGaussianBlur",feimage:"feImage",femerge:"feMerge",femergenode:"feMergeNode",femorphology:"feMorphology",feoffset:"feOffset",fepointlight:"fePointLight",fespecularlighting:"feSpecularLighting",fespotlight:"feSpotLight",fetile:"feTile",feturbulence:"feTurbulence",foreignobject:"foreignObject",glyphref:"glyphRef",lineargradient:"linearGradient",radialgradient:"radialGradient"}});var Mr={};z(Mr,{HeatmapTrackingManager:()=>Bt});var Ua,Bt,Pr=$(()=>{"use strict";it();rt();Ua={scrollDebounceDelay:100,batchDelay:2e3,maxBatchSize:20,debug:!1},Bt=class{constructor(e,t={}){this.isDestroyed=!1;this.currentScrollState=null;this.pendingClicks=[];this.pendingScrolls=[];this.scrollDebounceTimer=null;this.batchTimer=null;this.scrollTrackingTimer=null;this.periodicScrollTimer=null;this.lastScrollPosition=0;this.lastScrollTime=Date.now();this.SPLIT_DURATION=3e3;this.snapshotCaptured=!1;this.snapshotEnabled=!1;this.tracker=e,this.options={...Ua,...t},this.attentionQuality=new W(e.getActivityDetector(),{maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4,debug:this.options.debug}),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0))}async initialize(){this.isDestroyed||(this.log("Initializing heatmap tracking"),await this.checkSnapshotConfig(),this.setupClickTracking(),this.setupScrollTracking(),this.startScrollTracking(),this.setupUnloadHandler(),this.snapshotEnabled&&!this.snapshotCaptured&&this.captureSnapshot())}normalizeUrl(e){try{let t=new URL(e),i=t.hostname.toLowerCase();return i.startsWith("www.")&&(i=i.substring(4)),`${t.protocol}//${i}${t.pathname}`}catch{return e}}async checkSnapshotConfig(){try{let e=await this.tracker.getConfigAsync("enableHeatmapSnapshot");this.snapshotEnabled=e==="true",this.log("Heatmap snapshot capture enabled:",this.snapshotEnabled)}catch(e){this.log("Failed to check snapshot config, defaulting to disabled:",e),this.snapshotEnabled=!1}}async captureSnapshot(){if(!(this.snapshotCaptured||!this.snapshotEnabled))try{this.log("Capturing DOM snapshot...");let t=(await Promise.resolve().then(()=>(xr(),kr))).snapshot(document,{maskAllInputs:!0,maskTextFn:i=>i.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"*****")});this.snapshotCaptured=!0,this.log("DOM snapshot captured successfully"),await this.uploadSnapshot(t)}catch(e){this.log("Failed to capture DOM snapshot:",e)}}async uploadSnapshot(e){try{let t=this.tracker.getEffectiveUserId(),i=this.normalizeUrl(window.location.href);this.log("Uploading snapshot to backend - sessionId:",t);let r={sessionId:t,pageUrl:i,snapshot:e};this.log("Snapshot data prepared:",{sessionId:t,pageUrl:i,snapshotSize:JSON.stringify(e).length});let s=await this.getApiUrl(),a=await this.getTenantId(),o=await this.getAuthHeaders();if(!s||!a){this.log("Cannot upload snapshot: missing API URL or tenant ID");return}let c=await fetch(`${s}/v1/events/${encodeURIComponent(a)}/snapshot`,{method:"POST",headers:{"Content-Type":"application/json",...o},body:JSON.stringify({sessionId:t,pageUrl:i,snapshot:JSON.stringify(e),timestamp:Date.now()})});if(!c.ok)throw new Error(`Snapshot upload failed: ${c.status}`);let l=await c.json();this.log("Snapshot uploaded successfully:",l)}catch(t){this.log("Failed to upload snapshot:",t)}}async getApiUrl(){try{return this.tracker.config?.apiUrl||"https://api.grainql.com"}catch{return"https://api.grainql.com"}}async getTenantId(){try{return this.tracker.config?.tenantId}catch{return}}async getAuthHeaders(){try{return typeof this.tracker.getAuthHeaders=="function"?await this.tracker.getAuthHeaders():{}}catch{return{}}}setupClickTracking(){if(typeof document>"u")return;let e=t=>{this.isDestroyed||this.handleClick(t)};document.addEventListener("click",e,{passive:!0,capture:!0})}setupScrollTracking(){if(typeof window>"u")return;let e=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.handleScroll(),this.scrollDebounceTimer=null},this.options.scrollDebounceDelay)};window.addEventListener("scroll",e,{passive:!0})}startScrollTracking(){typeof window>"u"||(this.updateScrollState(),this.scrollTrackingTimer=window.setInterval(()=>{this.isDestroyed||this.updateScrollState()},500),this.startPeriodicScrollTracking())}startPeriodicScrollTracking(){typeof window>"u"||(this.periodicScrollTimer=window.setInterval(()=>{if(this.isDestroyed||!this.currentScrollState)return;if(!this.attentionQuality.shouldTrack()){this.log("Scroll tracking paused:",this.attentionQuality.getLastFilterReason());return}let e=Date.now(),t=e-this.currentScrollState.entryTime;if(t>1e3){let i=window.scrollY||window.pageYOffset,r=window.innerHeight,s=document.documentElement.scrollHeight,a=`viewport_section_${this.currentScrollState.viewportSection}`,o=this.attentionQuality.shouldTrackSection(a,i);if(o.resetAttention){this.log(`Viewport section ${this.currentScrollState.viewportSection}: Attention reset`),this.currentScrollState.entryTime=e;return}if(!o.shouldTrack){this.log(`Viewport section ${this.currentScrollState.viewportSection}: ${o.reason}`);return}let c={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:i,durationMs:t,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:e,pageHeight:s,viewportHeight:r};this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:c.pageUrl,viewport_section:c.viewportSection,scroll_depth_px:c.scrollDepthPx,duration_ms:c.durationMs,entry_timestamp:c.entryTimestamp,exit_timestamp:c.exitTimestamp,page_height:c.pageHeight,viewport_height:c.viewportHeight,is_split:!0},{flush:!0}),this.attentionQuality.updateSectionDuration(a,t),this.currentScrollState.entryTime=e}},this.SPLIT_DURATION))}setupUnloadHandler(){if(typeof window>"u")return;let e=()=>{if(this.currentScrollState){let t=Date.now(),i=t-this.currentScrollState.entryTime;if(i>100){let r={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:this.currentScrollState.scrollDepthPx,durationMs:i,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:t,pageHeight:document.documentElement.scrollHeight,viewportHeight:window.innerHeight};this.pendingScrolls.push(r)}}this.flushPendingEventsWithBeacon()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}handleClick(e){let t=e.target;if(!t)return;let i=this.normalizeUrl(window.location.href),r=this.generateXPath(t),s=this.generateCSSSelector(t),a,o;try{let h=t.getBoundingClientRect();h.width>0&&h.height>0&&(a=Math.max(0,Math.min(1,(e.clientX-h.left)/h.width)),o=Math.max(0,Math.min(1,(e.clientY-h.top)/h.height)))}catch(h){this.log("Failed to calculate relative coordinates:",h)}let c=Math.round(e.clientX),l=Math.round(e.clientY),u=Math.round(e.pageX),d=Math.round(e.pageY),f=t.tagName?.toLowerCase()||"unknown",y=Ae(t.textContent),g={pageUrl:i,xpath:r,selector:s,relX:a,relY:o,viewportX:c,viewportY:l,pageX:u,pageY:d,elementTag:f,elementText:y||void 0,timestamp:Date.now()};t instanceof HTMLAnchorElement&&t.href?this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:g.pageUrl,xpath:g.xpath,selector:g.selector,rel_x:g.relX,rel_y:g.relY,viewport_x:g.viewportX,viewport_y:g.viewportY,page_x:g.pageX,page_y:g.pageY,element_tag:g.elementTag,element_text:g.elementText,timestamp:g.timestamp},{flush:!0}):(this.pendingClicks.push(g),this.considerBatchFlush())}handleScroll(){this.updateScrollState()}updateScrollState(){if(typeof window>"u")return;let e=Date.now(),t=window.scrollY||window.pageYOffset,i=window.innerHeight,r=document.documentElement.scrollHeight,s=Math.floor(t/i);if(this.currentScrollState&&this.currentScrollState.viewportSection!==s){let a=e-this.currentScrollState.entryTime;if(a>100){let c={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:this.currentScrollState.scrollDepthPx,durationMs:a,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:e,pageHeight:r,viewportHeight:i};this.pendingScrolls.push(c)}let o=`viewport_section_${this.currentScrollState.viewportSection}`;this.attentionQuality.resetSection(o)}(!this.currentScrollState||this.currentScrollState.viewportSection!==s)&&(this.currentScrollState={viewportSection:s,entryTime:e,scrollDepthPx:t}),this.lastScrollPosition=t,this.lastScrollTime=e,this.considerBatchFlush()}generateCSSSelector(e){if(!e)return"";if(e.id)return`#${e.id}`;let t=Array.from(e.attributes).filter(s=>s.name.startsWith("data-"));if(t.length>0){let s=t[0];return`${e.tagName.toLowerCase()}[${s.name}="${s.value}"]`}if(e.className&&typeof e.className=="string"){let s=e.className.split(" ").filter(a=>a&&!a.match(/^(active|hover|focus)/));if(s.length>0)return`${e.tagName.toLowerCase()}.${s[0]}`}let i=[],r=e;for(;r&&r!==document.body;){let s=r.tagName.toLowerCase();if(r.parentElement){let o=Array.from(r.parentElement.children).filter(c=>c.tagName===r.tagName);if(o.length>1){let c=o.indexOf(r)+1;s+=`:nth-child(${c})`}}if(i.unshift(s),r=r.parentElement,i.length>=5)break}return i.join(" > ")}generateXPath(e){if(!e)return"";if(e.id)return`//*[@id="${e.id}"]`;let t=[],i=e;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let r=0,s=i;for(;s;)s=s.previousElementSibling,s&&s.nodeName===i.nodeName&&r++;let a=i.nodeName.toLowerCase(),o=r>0?`[${r+1}]`:"";t.unshift(`${a}${o}`),i=i.parentElement}return t.length?`/${t.join("/")}`:""}considerBatchFlush(){let e=this.pendingClicks.length+this.pendingScrolls.length;if(e>=this.options.maxBatchSize){this.flushPendingEvents();return}this.batchTimer===null&&e>0&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents(),this.batchTimer=null},this.options.batchDelay))}flushPendingEvents(){if(!this.isDestroyed){if(this.pendingClicks.length>0){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:e.pageUrl,xpath:e.xpath,selector:e.selector,rel_x:e.relX,rel_y:e.relY,viewport_x:e.viewportX,viewport_y:e.viewportY,page_x:e.pageX,page_y:e.pageY,element_tag:e.elementTag,element_text:e.elementText,timestamp:e.timestamp});this.pendingClicks=[]}if(this.pendingScrolls.length>0){for(let e of this.pendingScrolls)this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:e.pageUrl,viewport_section:e.viewportSection,scroll_depth_px:e.scrollDepthPx,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight});this.pendingScrolls=[]}this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null)}}flushPendingEventsWithBeacon(){if(this.pendingClicks.length>0){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:e.pageUrl,xpath:e.xpath,selector:e.selector,rel_x:e.relX,rel_y:e.relY,viewport_x:e.viewportX,viewport_y:e.viewportY,page_x:e.pageX,page_y:e.pageY,element_tag:e.elementTag,element_text:e.elementText,timestamp:e.timestamp},{flush:!0});this.pendingClicks=[]}if(this.pendingScrolls.length>0){for(let e of this.pendingScrolls)this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:e.pageUrl,viewport_section:e.viewportSection,scroll_depth_px:e.scrollDepthPx,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight},{flush:!0});this.pendingScrolls=[]}}log(...e){this.options.debug&&this.tracker.log("[Heatmap Tracking]",...e)}destroy(){this.isDestroyed=!0,this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.scrollTrackingTimer!==null&&(clearInterval(this.scrollTrackingTimer),this.scrollTrackingTimer=null),this.periodicScrollTimer!==null&&(clearInterval(this.periodicScrollTimer),this.periodicScrollTimer=null),this.attentionQuality.destroy(),this.flushPendingEvents()}}});var Ir={};z(Ir,{InteractionTrackingManager:()=>Ft});var Ft,_r=$(()=>{"use strict";rt();Ft=class{constructor(e,t,i={}){this.isDestroyed=!1;this.attachedListeners=new Map;this.xpathCache=new Map;this.mutationObserver=null;this.mutationDebounceTimer=null;this.tracker=e,this.interactions=t,this.config={debug:i.debug??!1,enableMutationObserver:i.enableMutationObserver??!0,mutationDebounceDelay:i.mutationDebounceDelay??500,tenantId:i.tenantId,apiUrl:i.apiUrl},typeof window<"u"&&typeof document<"u"&&(this.config.tenantId&&this.config.apiUrl?this.fetchAndMergeTrackers().then(()=>{this.attachAllListeners()}):document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.attachAllListeners()):setTimeout(()=>this.attachAllListeners(),0),this.config.enableMutationObserver&&this.setupMutationObserver())}async fetchAndMergeTrackers(){if(!(!this.config.tenantId||!this.config.apiUrl))try{let e=typeof window<"u"?window.location.href:"",t=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/trackers?url=${encodeURIComponent(e)}`;this.log("Fetching trackers from:",t);let i=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok){this.log("Failed to fetch trackers:",i.status);return}let r=await i.json();if(r.trackers&&Array.isArray(r.trackers)){this.log("Fetched",r.trackers.length,"trackers");let s=r.trackers.map(a=>({eventName:a.eventName,selector:a.selector,priority:5,label:a.eventName,description:`Tracker: ${a.eventName}`}));this.interactions=[...s,...this.interactions],this.log("Merged trackers, total interactions:",this.interactions.length)}}catch(e){this.log("Error fetching trackers:",e)}}attachAllListeners(){if(!this.isDestroyed){this.log("Attaching interaction listeners");for(let e of this.interactions)this.attachInteractionListener(e)}}attachInteractionListener(e){if(this.isDestroyed)return;let t=this.findElementByXPath(e.selector);if(!t){this.log("Element not found for interaction:",e.eventName,"selector:",e.selector);return}if(this.attachedListeners.has(t)){this.log("Listeners already attached for element:",t);return}let i=[],r=s=>this.handleInteractionClick(e,s);if(t.addEventListener("click",r,{passive:!0}),i.push({event:"click",handler:r}),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){let s=a=>this.handleInteractionFocus(e,a);t.addEventListener("focus",s,{passive:!0}),i.push({event:"focus",handler:s})}this.attachedListeners.set(t,i)}handleInteractionClick(e,t){if(this.isDestroyed)return;let i=t.target,r=i instanceof HTMLAnchorElement&&i.href,s={interaction_type:"click",interaction_label:e.label,interaction_description:e.description,interaction_priority:e.priority,element_tag:i.tagName?.toLowerCase(),element_text:Ae(i.textContent),element_id:i.id||void 0,element_class:i.className||void 0,...r&&{href:i.href},timestamp:Date.now()},a=this.tracker.track(e.eventName,s,{flush:!0});a instanceof Promise&&a.catch(o=>{this.log("Failed to track click:",o)})}handleInteractionFocus(e,t){if(this.isDestroyed)return;let i=t.target;this.tracker.track(e.eventName,{interaction_type:"focus",interaction_label:e.label,interaction_description:e.description,interaction_priority:e.priority,element_tag:i.tagName?.toLowerCase(),element_id:i.id||void 0,element_class:i.className||void 0,timestamp:Date.now()})}findElementByXPath(e){if(this.xpathCache.has(e)){let t=this.xpathCache.get(e);if(t&&document.contains(t))return t;this.xpathCache.delete(e)}try{let t=e;e.startsWith("xpath=")&&(t=e.substring(6));let r=document.evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return r&&this.xpathCache.set(e,r),r}catch(t){return this.log("Error evaluating XPath:",e,t),null}}setupMutationObserver(){if(typeof MutationObserver>"u"){this.log("MutationObserver not supported");return}this.mutationObserver=new MutationObserver(e=>{this.mutationDebounceTimer!==null&&clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=window.setTimeout(()=>{this.handleMutations(e),this.mutationDebounceTimer=null},this.config.mutationDebounceDelay)}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Mutation observer setup")}handleMutations(e){if(this.isDestroyed)return;this.xpathCache.clear();let t=new Set;for(let i of e)i.removedNodes.forEach(r=>{r instanceof Element&&(t.add(r),this.attachedListeners.forEach((s,a)=>{r.contains(a)&&t.add(a)}))});t.forEach(i=>{this.detachListeners(i)}),this.attachAllListeners()}detachListeners(e){let t=this.attachedListeners.get(e);t&&(t.forEach(({event:i,handler:r})=>{e.removeEventListener(i,r)}),this.attachedListeners.delete(e))}log(...e){this.config.debug&&console.log("[InteractionTracking]",...e)}updateInteractions(e){this.isDestroyed||(this.log("Updating interactions configuration"),this.attachedListeners.forEach((t,i)=>{this.detachListeners(i)}),this.xpathCache.clear(),this.interactions=e,this.attachAllListeners())}destroy(){this.isDestroyed||(this.log("Destroying interaction tracking manager"),this.isDestroyed=!0,this.mutationDebounceTimer!==null&&(clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.attachedListeners.forEach((e,t)=>{this.detachListeners(t)}),this.attachedListeners.clear(),this.xpathCache.clear())}}});var Rr={};z(Rr,{SectionTrackingManager:()=>Gt});var $a,Gt,Dr=$(()=>{"use strict";it();$a={minDwellTime:1e3,scrollVelocityThreshold:500,intersectionThreshold:.1,debounceDelay:100,batchDelay:2e3,debug:!1},Gt=class{constructor(e,t,i={}){this.isDestroyed=!1;this.sectionStates=new Map;this.intersectionObserver=null;this.xpathCache=new Map;this.lastScrollPosition=0;this.lastScrollTime=Date.now();this.scrollVelocity=0;this.scrollDebounceTimer=null;this.pendingEvents=[];this.batchTimer=null;this.sectionTimers=new Map;this.SPLIT_DURATION=3e3;this.tracker=e,this.sections=t,this.options={...$a,...i},this.attentionQuality=new W(e.getActivityDetector(),{maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4,debug:this.options.debug}),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0))}initialize(){this.isDestroyed||(this.log("Initializing section tracking"),this.setupIntersectionObserver(),this.setupScrollListener(),this.initializeSections())}setupIntersectionObserver(){if(typeof IntersectionObserver>"u"){this.log("IntersectionObserver not supported");return}this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(t=>{this.handleIntersection(t)})},{threshold:[0,.1,.25,.5,.75,1],rootMargin:"0px"}),this.log("IntersectionObserver created")}setupScrollListener(){if(typeof window>"u")return;let e=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.updateScrollVelocity(),this.scrollDebounceTimer=null},this.options.debounceDelay)};window.addEventListener("scroll",e,{passive:!0}),this.log("Scroll listener attached")}initializeSections(){for(let e of this.sections){let t=this.findElementByXPath(e.selector);if(!t){this.log("Section element not found:",e.sectionName,"selector:",e.selector);continue}let i={element:t,config:e,entryTime:null,exitTime:null,isVisible:!1,lastScrollPosition:window.scrollY,lastScrollTime:Date.now(),entryScrollSpeed:0,exitScrollSpeed:0,maxVisibleArea:0};this.sectionStates.set(e.sectionName,i),this.intersectionObserver&&this.intersectionObserver.observe(t)}}handleIntersection(e){if(this.isDestroyed)return;let t=Array.from(this.sectionStates.values()).find(s=>s.element===e.target);if(!t)return;let i=e.isIntersecting&&e.intersectionRatio>=this.options.intersectionThreshold,r=e.intersectionRatio;r>t.maxVisibleArea&&(t.maxVisibleArea=r),i&&!t.isVisible?this.handleSectionEntry(t):!i&&t.isVisible&&this.handleSectionExit(t),t.isVisible=i}handleSectionEntry(e){e.entryTime=Date.now(),e.entryScrollSpeed=this.scrollVelocity,e.lastScrollPosition=window.scrollY,e.lastScrollTime=Date.now(),e.maxVisibleArea=0,this.startPeriodicTracking(e)}startPeriodicTracking(e){this.stopPeriodicTracking(e.config.sectionName);let t=window.setInterval(()=>{if(this.isDestroyed||!e.isVisible||e.entryTime===null){this.stopPeriodicTracking(e.config.sectionName);return}let i=Date.now(),r=i-e.entryTime;if(r>=this.options.minDwellTime){let s=window.scrollY,a=this.attentionQuality.shouldTrackSection(e.config.sectionName,s);if(a.resetAttention){this.log(`Section "${e.config.sectionName}": Attention reset, restarting timer`),e.entryTime=i,e.entryScrollSpeed=this.scrollVelocity;return}if(!a.shouldTrack){this.log(`Section "${e.config.sectionName}": Tracking paused - ${a.reason}`);return}let o={sectionName:e.config.sectionName,sectionType:e.config.sectionType,entryTime:e.entryTime,exitTime:i,duration:r,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollDepth:this.calculateScrollDepth(),visibleAreaPercentage:Math.round(e.maxVisibleArea*100),scrollSpeedAtEntry:e.entryScrollSpeed,scrollSpeedAtExit:this.scrollVelocity};this.shouldTrackSection(o)&&(this.tracker.trackSystemEvent("_grain_section_view",{section_name:o.sectionName,section_type:o.sectionType,duration_ms:o.duration,viewport_width:o.viewportWidth,viewport_height:o.viewportHeight,scroll_depth_percent:o.scrollDepth,visible_area_percent:o.visibleAreaPercentage,scroll_speed_entry:Math.round(o.scrollSpeedAtEntry||0),scroll_speed_exit:Math.round(o.scrollSpeedAtExit||0),entry_timestamp:o.entryTime,exit_timestamp:o.exitTime,is_split:!0}),this.attentionQuality.updateSectionDuration(e.config.sectionName,r),e.entryTime=i,e.entryScrollSpeed=this.scrollVelocity)}},this.SPLIT_DURATION);this.sectionTimers.set(e.config.sectionName,t)}stopPeriodicTracking(e){let t=this.sectionTimers.get(e);t!==void 0&&(clearInterval(t),this.sectionTimers.delete(e))}handleSectionExit(e){if(this.stopPeriodicTracking(e.config.sectionName),this.attentionQuality.resetSection(e.config.sectionName),e.entryTime===null)return;e.exitTime=Date.now(),e.exitScrollSpeed=this.scrollVelocity;let t=e.exitTime-e.entryTime,i={sectionName:e.config.sectionName,sectionType:e.config.sectionType,entryTime:e.entryTime,exitTime:e.exitTime,duration:t,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollDepth:this.calculateScrollDepth(),visibleAreaPercentage:Math.round(e.maxVisibleArea*100),scrollSpeedAtEntry:e.entryScrollSpeed,scrollSpeedAtExit:e.exitScrollSpeed};this.shouldTrackSection(i)?this.queueSectionView(i):this.log("Section view filtered out:",e.config.sectionName,"duration:",t),e.entryTime=null}updateScrollVelocity(){let e=Date.now(),t=window.scrollY,i=e-this.lastScrollTime,r=Math.abs(t-this.lastScrollPosition);i>0&&(this.scrollVelocity=r/i*1e3),this.lastScrollPosition=t,this.lastScrollTime=e}calculateScrollDepth(){if(typeof window>"u"||typeof document>"u")return 0;let e=window.innerHeight,t=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),i=window.scrollY,r=t-e;return r<=0?100:Math.round(i/r*100)}shouldTrackSection(e){return!(e.duration<this.options.minDwellTime||(e.scrollSpeedAtEntry+e.scrollSpeedAtExit)/2>this.options.scrollVelocityThreshold*2||e.visibleAreaPercentage<10)}queueSectionView(e){this.pendingEvents.push(e),this.batchTimer===null&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents()},this.options.batchDelay))}flushPendingEvents(){if(!(this.isDestroyed||this.pendingEvents.length===0)){for(let e of this.pendingEvents)this.tracker.trackSystemEvent("_grain_section_view",{section_name:e.sectionName,section_type:e.sectionType,duration_ms:e.duration,viewport_width:e.viewportWidth,viewport_height:e.viewportHeight,scroll_depth_percent:e.scrollDepth,visible_area_percent:e.visibleAreaPercentage,scroll_speed_entry:Math.round(e.scrollSpeedAtEntry||0),scroll_speed_exit:Math.round(e.scrollSpeedAtExit||0),entry_timestamp:e.entryTime,exit_timestamp:e.exitTime});this.pendingEvents=[],this.batchTimer=null}}findElementByXPath(e){if(this.xpathCache.has(e)){let t=this.xpathCache.get(e);if(t&&document.contains(t))return t;this.xpathCache.delete(e)}try{let t=e;e.startsWith("xpath=")&&(t=e.substring(6));let r=document.evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return r&&this.xpathCache.set(e,r),r}catch(t){return this.log("Error evaluating XPath:",e,t),null}}log(...e){this.options.debug&&console.log("[SectionTracking]",...e)}updateSections(e){this.isDestroyed||(this.log("Updating sections configuration"),this.intersectionObserver&&this.intersectionObserver.disconnect(),this.sectionStates.clear(),this.xpathCache.clear(),this.sections=e,this.setupIntersectionObserver(),this.initializeSections())}destroy(){this.isDestroyed||(this.log("Destroying section tracking manager"),this.isDestroyed=!0,this.sectionTimers.forEach(e=>{clearInterval(e)}),this.sectionTimers.clear(),this.flushPendingEvents(),this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.attentionQuality.destroy(),this.sectionStates.clear(),this.xpathCache.clear(),this.pendingEvents=[])}}});var Lr={};z(Lr,{DebugAgent:()=>zt});var zt,Or=$(()=>{"use strict";zt=class{constructor(e,t,i,r,s={}){this.isDestroyed=!1;this.isInspectMode=!1;this.showTrackers=!1;this.selectedElement=null;this.toolbarElement=null;this.panelElement=null;this.highlightElement=null;this.existingTrackers=[];this.trackerHighlights=[];this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.toolbarStartX=0;this.toolbarStartY=0;this.mouseMoveListener=null;this.clickListener=null;this.dragMoveListener=null;this.dragEndListener=null;this.handleEscapeKey=e=>{e.key==="Escape"&&this.isInspectMode&&this.disableInspectMode()};this.tracker=e,this.sessionId=t,this.tenantId=i,this.apiUrl=r,this.config={debug:s.debug??!1},typeof window<"u"&&typeof document<"u"&&this.initialize()}async initialize(){this.log("Initializing debug agent"),await this.loadExistingTrackers(),this.showToolbar(),this.createHighlightElement(),this.showTrackers=!0,this.showTrackerHighlights(),this.showTrackersList()}async loadExistingTrackers(){try{let e=`${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/trackers`,t=await fetch(e);t.ok&&(this.existingTrackers=await t.json(),this.log("Loaded trackers:",this.existingTrackers))}catch(e){this.log("Failed to load trackers:",e),this.existingTrackers=[]}}showToolbar(){if(this.toolbarElement)return;let e=document.createElement("div");e.id="grain-debug-toolbar",e.innerHTML=`
|
|
3
29
|
<style>
|
|
4
30
|
#grain-debug-toolbar {
|
|
5
31
|
position: fixed;
|
|
@@ -269,7 +295,7 @@
|
|
|
269
295
|
</div>
|
|
270
296
|
</div>
|
|
271
297
|
<div id="grain-trackers-list-container"></div>
|
|
272
|
-
`,document.body.appendChild(e),this.toolbarElement=e;let t=e.querySelector("#grain-toolbar-handle");t&&t.addEventListener("mousedown",a=>this.startDrag(a));let i=e.querySelector("#grain-debug-inspect"),r=e.querySelector("#grain-debug-trackers"),
|
|
298
|
+
`,document.body.appendChild(e),this.toolbarElement=e;let t=e.querySelector("#grain-toolbar-handle");t&&t.addEventListener("mousedown",a=>this.startDrag(a));let i=e.querySelector("#grain-debug-inspect"),r=e.querySelector("#grain-debug-trackers"),s=e.querySelector("#grain-debug-end");i&&i.addEventListener("click",()=>this.toggleInspectMode()),r&&r.addEventListener("click",()=>this.toggleTrackerView()),s&&s.addEventListener("click",()=>this.endDebug()),this.log("Toolbar shown")}createHighlightElement(){if(this.highlightElement)return;let e=document.createElement("div");e.className="grain-debug-highlight",e.style.display="none",document.body.appendChild(e),this.highlightElement=e}startDrag(e){if(!this.toolbarElement)return;this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY;let t=this.toolbarElement.getBoundingClientRect();this.toolbarStartX=t.left,this.toolbarStartY=t.top,this.toolbarElement.classList.add("dragging"),this.dragMoveListener=i=>this.onDrag(i),this.dragEndListener=()=>this.endDrag(),document.addEventListener("mousemove",this.dragMoveListener),document.addEventListener("mouseup",this.dragEndListener)}onDrag(e){if(!this.isDragging||!this.toolbarElement)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY,r=this.toolbarStartX+t,s=this.toolbarStartY+i,a=window.innerWidth-this.toolbarElement.offsetWidth,o=window.innerHeight-this.toolbarElement.offsetHeight,c=Math.max(0,Math.min(r,a)),l=Math.max(0,Math.min(s,o));this.toolbarElement.style.left=`${c}px`,this.toolbarElement.style.top=`${l}px`,this.toolbarElement.style.right="auto",this.toolbarElement.style.bottom="auto"}endDrag(){this.isDragging&&(this.isDragging=!1,this.toolbarElement&&this.toolbarElement.classList.remove("dragging"),this.dragMoveListener&&(document.removeEventListener("mousemove",this.dragMoveListener),this.dragMoveListener=null),this.dragEndListener&&(document.removeEventListener("mouseup",this.dragEndListener),this.dragEndListener=null))}toggleTrackerView(){this.showTrackers=!this.showTrackers;let e=document.querySelector("#grain-debug-trackers");e&&(e.textContent=this.showTrackers?"Hide":"View",e.classList.toggle("active",this.showTrackers)),this.showTrackers?(this.showTrackerHighlights(),this.showTrackersList()):(this.hideTrackerHighlights(),this.hideTrackersList())}showTrackerHighlights(){this.hideTrackerHighlights();for(let e of this.existingTrackers)if(e.isEnabled)try{let t=this.findElementBySelector(e.selector);if(!t)continue;let i=t.getBoundingClientRect(),r=document.createElement("div");r.className="grain-tracker-highlight";let s=document.createElement("div");s.className="grain-tracker-label",s.textContent=e.name,r.style.top=`${i.top+window.scrollY}px`,r.style.left=`${i.left+window.scrollX}px`,r.style.width=`${i.width}px`,r.style.height=`${i.height}px`,r.appendChild(s),document.body.appendChild(r),this.trackerHighlights.push(r)}catch(t){this.log("Failed to highlight tracker:",e.name,t)}}hideTrackerHighlights(){for(let e of this.trackerHighlights)e.remove();this.trackerHighlights=[]}showTrackersList(){let e=document.querySelector(".grain-trackers-list");if(this.existingTrackers.length===0){e&&e.remove();return}e||(e=document.createElement("div"),e.className="grain-trackers-list",document.body.appendChild(e)),e.innerHTML=`
|
|
273
299
|
${this.existingTrackers.map(t=>`
|
|
274
300
|
<div class="grain-tracker-item" data-tracker-id="${t.trackerId}">
|
|
275
301
|
<div class="grain-tracker-name">${t.name}</div>
|
|
@@ -280,7 +306,7 @@
|
|
|
280
306
|
</div>
|
|
281
307
|
</div>
|
|
282
308
|
`).join("")}
|
|
283
|
-
`,e.querySelectorAll(".grain-tracker-item").forEach(t=>{t.addEventListener("click",()=>{let i=t.getAttribute("data-tracker-id"),r=this.existingTrackers.find(
|
|
309
|
+
`,e.querySelectorAll(".grain-tracker-item").forEach(t=>{t.addEventListener("click",()=>{let i=t.getAttribute("data-tracker-id"),r=this.existingTrackers.find(s=>s.trackerId===i);r&&this.scrollToTracker(r)})})}hideTrackersList(){let e=document.querySelector(".grain-trackers-list");e&&e.remove()}scrollToTracker(e){try{let t=this.findElementBySelector(e.selector);if(t){t.scrollIntoView({behavior:"smooth",block:"center"});let i=this.trackerHighlights.find(r=>{let s=t.getBoundingClientRect(),a=r.getBoundingClientRect();return Math.abs(a.top-s.top)<5});i&&(i.style.opacity="0",setTimeout(()=>{i.style.opacity="1"},100),setTimeout(()=>{i.style.opacity="0"},300),setTimeout(()=>{i.style.opacity="1"},500))}}catch(t){this.log("Failed to scroll to tracker:",t)}}findElementBySelector(e){try{return document.evaluate(e,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch(t){return this.log("Failed to find element:",t),null}}toggleInspectMode(){this.isInspectMode?this.disableInspectMode():this.enableInspectMode()}enableInspectMode(){if(this.isInspectMode)return;this.log("Enabling inspect mode"),this.isInspectMode=!0;let e=document.querySelector("#grain-debug-inspect");e&&(e.classList.add("active"),e.textContent="Click Element"),this.mouseMoveListener=t=>this.handleMouseMove(t),this.clickListener=t=>this.handleElementClick(t),document.addEventListener("mousemove",this.mouseMoveListener,!0),document.addEventListener("click",this.clickListener,!0),document.addEventListener("keydown",this.handleEscapeKey)}disableInspectMode(){if(!this.isInspectMode)return;this.log("Disabling inspect mode"),this.isInspectMode=!1;let e=document.querySelector("#grain-debug-inspect");e&&(e.classList.remove("active"),e.textContent="+ New"),this.mouseMoveListener&&(document.removeEventListener("mousemove",this.mouseMoveListener,!0),this.mouseMoveListener=null),this.clickListener&&(document.removeEventListener("click",this.clickListener,!0),this.clickListener=null),document.removeEventListener("keydown",this.handleEscapeKey),this.highlightElement&&(this.highlightElement.style.display="none")}handleMouseMove(e){if(!this.isInspectMode||!this.highlightElement)return;let t=e.target;if(t.closest("#grain-debug-toolbar")||t.closest("#grain-debug-panel")||t.closest(".grain-trackers-list")){this.highlightElement.style.display="none";return}let r=e.target.getBoundingClientRect();this.highlightElement.style.display="block",this.highlightElement.style.top=`${r.top+window.scrollY}px`,this.highlightElement.style.left=`${r.left+window.scrollX}px`,this.highlightElement.style.width=`${r.width}px`,this.highlightElement.style.height=`${r.height}px`}handleElementClick(e){if(!this.isInspectMode)return;let t=e.target;if(t.closest("#grain-debug-toolbar")||t.closest(".grain-trackers-list")){this.disableInspectMode();return}if(t.closest("#grain-debug-panel")){e.preventDefault(),e.stopPropagation();return}e.preventDefault(),e.stopPropagation(),this.selectedElement=t,this.disableInspectMode(),this.showCreationPanel(t)}showCreationPanel(e){this.panelElement&&this.panelElement.remove();let t=document.createElement("div");t.id="grain-debug-panel";let i=e.tagName.toLowerCase(),r=e.id,s=e.textContent?.trim().substring(0,50)||"",a=this.getXPathForElement(e);t.innerHTML=`
|
|
284
310
|
<style>
|
|
285
311
|
#grain-debug-panel {
|
|
286
312
|
position: fixed;
|
|
@@ -444,7 +470,7 @@
|
|
|
444
470
|
<div class="grain-panel-body">
|
|
445
471
|
<div class="element-preview">
|
|
446
472
|
<div><strong>Element:</strong> ${i}${r?`#${r}`:""}</div>
|
|
447
|
-
${
|
|
473
|
+
${s?`<div><strong>Text:</strong> ${s}</div>`:""}
|
|
448
474
|
</div>
|
|
449
475
|
<div>
|
|
450
476
|
<label>Event Name</label>
|
|
@@ -475,7 +501,7 @@
|
|
|
475
501
|
</div>
|
|
476
502
|
</div>
|
|
477
503
|
</div>
|
|
478
|
-
`,document.body.appendChild(t),this.panelElement=t;let o=t.querySelector("#grain-event-name");if(o){let y=this.generateEventName(e);o.value=y,o.select()}let
|
|
504
|
+
`,document.body.appendChild(t),this.panelElement=t;let o=t.querySelector("#grain-event-name");if(o){let y=this.generateEventName(e);o.value=y,o.select()}let c=t.querySelector("#grain-url-scope"),l=t.querySelector("#grain-url-pattern-container"),u=t.querySelector("#grain-url-pattern");c&&l&&c.addEventListener("change",()=>{c.value==="all"?l.classList.remove("visible"):(l.classList.add("visible"),u&&!u.value&&(u.value=window.location.pathname))});let d=t.querySelector("#grain-cancel"),f=t.querySelector("#grain-create");d&&d.addEventListener("click",()=>this.hideCreationPanel()),f&&f.addEventListener("click",()=>this.handleCreateTracker(a))}generateEventName(e){let t=e.tagName.toLowerCase(),i=e.id,r=e.textContent?.trim().toLowerCase().replace(/\s+/g,"_").substring(0,30)||"";return i?`${i}_click`:r?`${r}_click`:t==="button"?"button_click":t==="a"?"link_click":`${t}_click`}async handleCreateTracker(e){if(!this.panelElement)return;let t=this.panelElement.querySelector("#grain-event-name"),i=this.panelElement.querySelector("#grain-event-type"),r=this.panelElement.querySelector("#grain-url-scope"),s=this.panelElement.querySelector("#grain-url-pattern");if(!t||!i||!r)return;let a=t.value.trim(),o=i.value,c=r.value,l=s?.value.trim()||void 0;if(!a){alert("Please enter an event name");return}if(!a.match(/^[a-zA-Z0-9_-]+$/)){alert("Event name can only contain letters, numbers, underscores, and hyphens");return}if((c==="contains"||c==="equals")&&!l){alert("Please enter a URL pattern");return}try{let u=this.panelElement.querySelector("#grain-create");u&&(u.textContent="Creating...",u.disabled=!0),await this.createTracker(a,o,e,c,l),this.hideCreationPanel(),this.showSuccessMessage(`Tracker "${a}" created successfully!`),await this.loadExistingTrackers(),this.updateToolbarStats(),this.showTrackers&&(this.showTrackerHighlights(),this.showTrackersList()),this.log("Tracker created:",a)}catch(u){alert("Failed to create tracker. Please try again."),this.log("Failed to create tracker:",u);let d=this.panelElement.querySelector("#grain-create");d&&(d.textContent="Create Tracker",d.disabled=!1)}}async createTracker(e,t,i,r,s){let a=`${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/debug-sessions/${this.sessionId}/trackers`,o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,type:t,selector:i,urlScope:r,urlPattern:s})});if(!o.ok)throw new Error(`Failed to create tracker: ${o.status}`)}hideCreationPanel(){this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.selectedElement=null}showSuccessMessage(e){let t=document.createElement("div");t.style.cssText=`
|
|
479
505
|
position: fixed;
|
|
480
506
|
top: 20px;
|
|
481
507
|
left: 50%;
|
|
@@ -503,5 +529,5 @@
|
|
|
503
529
|
</style>
|
|
504
530
|
<span style="font-size: 18px;">\u2713</span>
|
|
505
531
|
<span>${e}</span>
|
|
506
|
-
`,document.body.appendChild(t),setTimeout(()=>{t.style.animation="slideDown 0.3s ease-in reverse",setTimeout(()=>{t.remove()},300)},2700)}async endDebug(){try{let t=`${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/debug-sessions/${this.sessionId}/end`;await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"}})}catch(t){this.log("Failed to end debug session:",t)}this.destroy();let e=new URL(window.location.href);e.searchParams.delete("grain_debug"),e.searchParams.delete("grain_session"),window.location.href=e.toString()}getXPathForElement(e){if(e.id)return`//*[@id="${e.id}"]`;let t=[],i=e;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let r=0,n=i;for(;n;)n.nodeType===Node.ELEMENT_NODE&&n.tagName===i.tagName&&r++,n=n.previousElementSibling;let a=i.tagName.toLowerCase(),o=r>1?`[${r}]`:"";t.unshift(`${a}${o}`),i=i.parentElement}return t.length?`/${t.join("/")}`:""}log(...e){this.config.debug&&console.log("[DebugAgent]",...e)}updateToolbarStats(){if(!this.toolbarElement)return;let e=this.toolbarElement.querySelector(".grain-stat:nth-child(1) .grain-stat-value"),t=this.toolbarElement.querySelector(".grain-stat:nth-child(2) .grain-stat-value");e&&(e.textContent=String(this.existingTrackers.length)),t&&(t.textContent=String(this.existingTrackers.filter(i=>i.isEnabled).length))}destroy(){this.isDestroyed||(this.log("Destroying debug agent"),this.isDestroyed=!0,this.disableInspectMode(),this.hideTrackerHighlights(),this.endDrag(),this.toolbarElement&&(this.toolbarElement.remove(),this.toolbarElement=null),this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.highlightElement&&(this.highlightElement.remove(),this.highlightElement=null))}}});var ke={};A(ke,{GrainAnalytics:()=>v,categorizeReferrer:()=>m,createGrainAnalytics:()=>se,default:()=>we,getCountry:()=>j,getCountryCodeFromTimezone:()=>M,getState:()=>Y,parseUTMParameters:()=>S});var F=["necessary","analytics","functional"],E="1.0.0",T=class{constructor(e,t="COOKIELESS"){this.consentState=null;this.listeners=[];this.consentMode=t,this.storageKey=`grain_consent_${e}`,this.loadConsentState()}loadConsentState(){if(!(typeof window>"u"))try{let e=localStorage.getItem(this.storageKey);if(e){let t=JSON.parse(e);this.consentState={...t,timestamp:new Date(t.timestamp)}}else this.consentMode==="GDPR_OPT_OUT"&&(this.consentState={granted:!0,categories:F,timestamp:new Date,version:E},this.saveConsentState())}catch{}}saveConsentState(){if(!(typeof window>"u"||!this.consentState))try{localStorage.setItem(this.storageKey,JSON.stringify(this.consentState))}catch{}}grantConsent(e){let t=e||F;this.consentState={granted:!0,categories:t,timestamp:new Date,version:E},this.saveConsentState(),this.notifyListeners()}revokeConsent(e){this.consentState?e?this.consentState={...this.consentState,categories:this.consentState.categories.filter(t=>!e.includes(t)),granted:this.consentState.categories.length>0,timestamp:new Date}:this.consentState={granted:!1,categories:[],timestamp:new Date,version:E}:this.consentState={granted:!1,categories:[],timestamp:new Date,version:E},this.saveConsentState(),this.notifyListeners()}getConsentState(){return this.consentState?{...this.consentState}:null}hasConsent(e){if(this.consentMode==="COOKIELESS"||this.consentMode==="GDPR_STRICT"&&!this.consentState?.granted)return!1;if(this.consentMode==="GDPR_OPT_OUT"){if(!this.consentState)return!0;if(!this.consentState.granted)return!1}return e&&this.consentState?this.consentState.categories.includes(e):this.consentState?.granted??this.consentMode==="GDPR_OPT_OUT"}shouldUsePermanentId(){return this.hasConsent()}shouldStripQueryParams(){return this.consentMode==="COOKIELESS"?!0:this.consentMode==="GDPR_STRICT"?!this.hasConsent():this.consentMode!=="GDPR_OPT_OUT"}canTrack(){return!0}shouldWaitForConsent(){return this.consentMode==="GDPR_STRICT"&&!this.consentState?.granted}addListener(e){this.listeners.push(e)}removeListener(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){this.consentState&&this.listeners.forEach(e=>{try{e(this.consentState)}catch{}})}clearConsent(){if(!(typeof window>"u"))try{localStorage.removeItem(this.storageKey),this.consentState=null}catch{}}getConsentMode(){return this.consentMode}getIdMode(){return this.shouldUsePermanentId()?"permanent":"cookieless"}};function $(s,e,t){if(typeof document>"u")return;let i=[`${encodeURIComponent(s)}=${encodeURIComponent(e)}`];t?.maxAge!==void 0&&i.push(`max-age=${t.maxAge}`),t?.domain&&i.push(`domain=${t.domain}`),t?.path?i.push(`path=${t.path}`):i.push("path=/"),t?.sameSite&&i.push(`samesite=${t.sameSite}`),t?.secure&&i.push("secure"),document.cookie=i.join("; ")}function K(s){if(typeof document>"u")return null;let e=encodeURIComponent(s)+"=",t=document.cookie.split(";");for(let i=0;i<t.length;i++){let r=t[i];for(;r.charAt(0)===" ";)r=r.substring(1);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length))}return null}var w=class{constructor(){this.activityThreshold=3e4;this.listeners=[];this.isDestroyed=!1;this.activityEvents=["mousemove","mousedown","keydown","scroll","touchstart","click"];this.lastActivityTime=Date.now(),this.boundActivityHandler=this.debounce(this.handleActivity.bind(this),500),this.setupListeners()}setupListeners(){if(!(typeof window>"u"))for(let e of this.activityEvents)window.addEventListener(e,this.boundActivityHandler,{passive:!0})}handleActivity(){this.isDestroyed||(this.lastActivityTime=Date.now(),this.notifyListeners())}debounce(e,t){let i=null;return()=>{i!==null&&clearTimeout(i),i=window.setTimeout(()=>{e(),i=null},t)}}isActive(e){let t=e??this.activityThreshold;return Date.now()-this.lastActivityTime<t}getTimeSinceLastActivity(){return Date.now()-this.lastActivityTime}getLastActivityTime(){return this.lastActivityTime}setActivityThreshold(e){this.activityThreshold=e}addListener(e){this.listeners.push(e)}removeListener(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}destroy(){if(!this.isDestroyed){if(typeof window<"u")for(let e of this.activityEvents)window.removeEventListener(e,this.boundActivityHandler);this.listeners=[],this.isDestroyed=!0}}};var k=class{constructor(e,t,i){this.heartbeatTimer=null;this.isDestroyed=!1;this.hasSentPageLoadHeartbeat=!1;this.tracker=e,this.activityDetector=t,this.config=i,this.lastHeartbeatTime=Date.now(),this.currentInterval=i.activeInterval,this.sendPageLoadHeartbeat(),this.scheduleNextHeartbeat()}sendPageLoadHeartbeat(){if(!(this.isDestroyed||this.hasSentPageLoadHeartbeat))if(typeof window<"u"&&document.readyState!=="complete"){let e=()=>{this.sendHeartbeat("page_load"),this.hasSentPageLoadHeartbeat=!0,window.removeEventListener("load",e)};window.addEventListener("load",e)}else this.sendHeartbeat("page_load"),this.hasSentPageLoadHeartbeat=!0}scheduleNextHeartbeat(){if(this.isDestroyed)return;this.heartbeatTimer!==null&&clearTimeout(this.heartbeatTimer);let e=this.activityDetector.isActive(6e4);this.currentInterval=e?this.config.activeInterval:this.config.inactiveInterval,this.heartbeatTimer=window.setTimeout(()=>{this.sendHeartbeat("periodic"),this.scheduleNextHeartbeat()},this.currentInterval),this.config.debug&&console.log(`[Heartbeat] Scheduled next heartbeat in ${this.currentInterval/1e3}s (${e?"active":"inactive"})`)}sendHeartbeat(e="periodic"){if(this.isDestroyed)return;let t=Date.now(),i=this.activityDetector.isActive(6e4),r=this.tracker.hasConsent("analytics"),n={heartbeat_type:e,status:i?"active":"inactive",timestamp:t};if(r){let a=this.tracker.getCurrentPage();a&&(n.page=a),n.session_id=this.tracker.getSessionId(),e==="periodic"&&(n.duration=t-this.lastHeartbeatTime,n.event_count=this.tracker.getEventCountSinceLastHeartbeat(),this.tracker.resetEventCountSinceLastHeartbeat())}this.tracker.trackSystemEvent("_grain_heartbeat",n),this.lastHeartbeatTime=t}destroy(){this.isDestroyed||(this.heartbeatTimer!==null&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isDestroyed=!0)}};var ge=["gclid","msclkid","fbclid","ttclid","li_fat_id","twclid","ScCid"],me=["facebook.com","twitter.com","x.com","linkedin.com","instagram.com","pinterest.com","reddit.com","tiktok.com","youtube.com","snapchat.com","t.co","fb.me","lnkd.in"],pe=["google.","bing.com","yahoo.com","duckduckgo.com","baidu.com","yandex.com","ecosia.org","ask.com"],fe=["mail.google.com","outlook.live.com","mail.yahoo.com","mail.aol.com"];function D(s){try{return new URL(s).hostname.toLowerCase()}catch{return""}}function z(s){try{let e=new URL(s);return ge.some(t=>e.searchParams.has(t))}catch{return!1}}function m(s,e=""){if(!s||s.trim()==="")return"direct";let t=D(s);if(e){let i=D(e);if(t===i)return"direct"}return z(s)||z(e)?"paid":fe.some(i=>t.includes(i))?"email":me.some(i=>t.includes(i))?"social":pe.some(i=>t.includes(i))?"organic":"referral"}function S(s){try{let e=new URL(s),t={},i=e.searchParams.get("utm_source"),r=e.searchParams.get("utm_medium"),n=e.searchParams.get("utm_campaign"),a=e.searchParams.get("utm_term"),o=e.searchParams.get("utm_content");return i&&(t.utm_source=i),r&&(t.utm_medium=r),n&&(t.utm_campaign=n),a&&(t.utm_term=a),o&&(t.utm_content=o),t}catch{return{}}}function R(s){if(typeof window>"u"||typeof localStorage>"u")return null;try{let e=`_grain_first_touch_${s}`,t=localStorage.getItem(e);if(t)return JSON.parse(t)}catch(e){console.warn("[Grain Attribution] Failed to retrieve first-touch attribution:",e)}return null}function ve(s,e){if(!(typeof window>"u"||typeof localStorage>"u"))try{let t=`_grain_first_touch_${s}`;localStorage.setItem(t,JSON.stringify(e))}catch(t){console.warn("[Grain Attribution] Failed to store first-touch attribution:",t)}}function C(s,e,t,i){let r=R(s);if(r)return r;let n=m(e,t),a=D(e),o={source:i.utm_source||a||"direct",medium:i.utm_medium||n,campaign:i.utm_campaign||"none",referrer:e||"direct",referrer_category:n,timestamp:Date.now()};return ve(s,o),o}var V=null;function p(){return V}function Q(s){V=s}var ye={AD:"Andorra",AE:"United Arab Emirates",AF:"Afghanistan",AG:"Antigua and Barbuda",AI:"Anguilla",AL:"Albania",AM:"Armenia",AO:"Angola",AQ:"Antarctica",AR:"Argentina",AS:"American Samoa",AT:"Austria",AU:"Australia",AW:"Aruba",AX:"\xC5land Islands",AZ:"Azerbaijan",BA:"Bosnia and Herzegovina",BB:"Barbados",BD:"Bangladesh",BE:"Belgium",BF:"Burkina Faso",BG:"Bulgaria",BH:"Bahrain",BI:"Burundi",BJ:"Benin",BL:"Saint Barth\xE9lemy",BM:"Bermuda",BN:"Brunei",BO:"Bolivia",BQ:"Caribbean Netherlands",BR:"Brazil",BS:"Bahamas",BT:"Bhutan",BV:"Bouvet Island",BW:"Botswana",BY:"Belarus",BZ:"Belize",CA:"Canada",CC:"Cocos Islands",CD:"Democratic Republic of the Congo",CF:"Central African Republic",CG:"Republic of the Congo",CH:"Switzerland",CI:"Ivory Coast",CK:"Cook Islands",CL:"Chile",CM:"Cameroon",CN:"China",CO:"Colombia",CR:"Costa Rica",CU:"Cuba",CV:"Cabo Verde",CW:"Cura\xE7ao",CX:"Christmas Island",CY:"Cyprus",CZ:"Czechia",DE:"Germany",DJ:"Djibouti",DK:"Denmark",DM:"Dominica",DO:"Dominican Republic",DZ:"Algeria",EC:"Ecuador",EE:"Estonia",EG:"Egypt",EH:"Western Sahara",ER:"Eritrea",ES:"Spain",ET:"Ethiopia",FI:"Finland",FJ:"Fiji",FK:"Falkland Islands",FM:"Micronesia",FO:"Faroe Islands",FR:"France",GA:"Gabon",GB:"United Kingdom",GD:"Grenada",GE:"Georgia",GF:"French Guiana",GG:"Guernsey",GH:"Ghana",GI:"Gibraltar",GL:"Greenland",GM:"Gambia",GN:"Guinea",GP:"Guadeloupe",GQ:"Equatorial Guinea",GR:"Greece",GS:"South Georgia and the South Sandwich Islands",GT:"Guatemala",GU:"Guam",GW:"Guinea-Bissau",GY:"Guyana",HK:"Hong Kong",HM:"Heard Island and McDonald Islands",HN:"Honduras",HR:"Croatia",HT:"Haiti",HU:"Hungary",ID:"Indonesia",IE:"Ireland",IL:"Israel",IM:"Isle of Man",IN:"India",IO:"British Indian Ocean Territory",IQ:"Iraq",IR:"Iran",IS:"Iceland",IT:"Italy",JE:"Jersey",JM:"Jamaica",JO:"Jordan",JP:"Japan",KE:"Kenya",KG:"Kyrgyzstan",KH:"Cambodia",KI:"Kiribati",KM:"Comoros",KN:"Saint Kitts and Nevis",KP:"North Korea",KR:"South Korea",KW:"Kuwait",KY:"Cayman Islands",KZ:"Kazakhstan",LA:"Laos",LB:"Lebanon",LC:"Saint Lucia",LI:"Liechtenstein",LK:"Sri Lanka",LR:"Liberia",LS:"Lesotho",LT:"Lithuania",LU:"Luxembourg",LV:"Latvia",LY:"Libya",MA:"Morocco",MC:"Monaco",MD:"Moldova",ME:"Montenegro",MF:"Saint Martin",MG:"Madagascar",MH:"Marshall Islands",MK:"North Macedonia",ML:"Mali",MM:"Myanmar",MN:"Mongolia",MO:"Macao",MP:"Northern Mariana Islands",MQ:"Martinique",MR:"Mauritania",MS:"Montserrat",MT:"Malta",MU:"Mauritius",MV:"Maldives",MW:"Malawi",MX:"Mexico",MY:"Malaysia",MZ:"Mozambique",NA:"Namibia",NC:"New Caledonia",NE:"Niger",NF:"Norfolk Island",NG:"Nigeria",NI:"Nicaragua",NL:"Netherlands",NO:"Norway",NP:"Nepal",NR:"Nauru",NU:"Niue",NZ:"New Zealand",OM:"Oman",PA:"Panama",PE:"Peru",PF:"French Polynesia",PG:"Papua New Guinea",PH:"Philippines",PK:"Pakistan",PL:"Poland",PM:"Saint Pierre and Miquelon",PN:"Pitcairn",PR:"Puerto Rico",PS:"Palestine",PT:"Portugal",PW:"Palau",PY:"Paraguay",QA:"Qatar",RE:"R\xE9union",RO:"Romania",RS:"Serbia",RU:"Russia",RW:"Rwanda",SA:"Saudi Arabia",SB:"Solomon Islands",SC:"Seychelles",SD:"Sudan",SE:"Sweden",SG:"Singapore",SH:"Saint Helena, Ascension and Tristan da Cunha",SI:"Slovenia",SJ:"Svalbard and Jan Mayen",SK:"Slovakia",SL:"Sierra Leone",SM:"San Marino",SN:"Senegal",SO:"Somalia",SR:"Suriname",SS:"South Sudan",ST:"Sao Tome and Principe",SV:"El Salvador",SX:"Sint Maarten",SY:"Syria",SZ:"Eswatini",TC:"Turks and Caicos Islands",TD:"Chad",TF:"French Southern Territories",TG:"Togo",TH:"Thailand",TJ:"Tajikistan",TK:"Tokelau",TL:"Timor-Leste",TM:"Turkmenistan",TN:"Tunisia",TO:"Tonga",TR:"Turkey",TT:"Trinidad and Tobago",TV:"Tuvalu",TW:"Taiwan",TZ:"Tanzania",UA:"Ukraine",UG:"Uganda",UM:"United States Minor Outlying Islands",US:"United States of America",UY:"Uruguay",UZ:"Uzbekistan",VA:"Holy See",VC:"Saint Vincent and the Grenadines",VE:"Venezuela",VG:"Virgin Islands (UK)",VI:"Virgin Islands (US)",VN:"Vietnam",VU:"Vanuatu",WF:"Wallis and Futuna",WS:"Samoa",YE:"Yemen",YT:"Mayotte",ZA:"South Africa",ZM:"Zambia",ZW:"Zimbabwe"},W={"Africa/Abidjan":{u:0,c:["CI","BF","GH","GM","GN","ML","MR","SH","SL","SN","TG"]},"Africa/Accra":{a:"Africa/Abidjan",c:["GH"],r:1},"Africa/Addis_Ababa":{a:"Africa/Nairobi",c:["ET"],r:1},"Africa/Algiers":{u:60,c:["DZ"]},"Africa/Asmara":{a:"Africa/Nairobi",c:["ER"],r:1},"Africa/Asmera":{a:"Africa/Nairobi",c:["ER"],r:1},"Africa/Bamako":{a:"Africa/Abidjan",c:["ML"],r:1},"Africa/Bangui":{a:"Africa/Lagos",c:["CF"],r:1},"Africa/Banjul":{a:"Africa/Abidjan",c:["GM"],r:1},"Africa/Bissau":{u:0,c:["GW"]},"Africa/Blantyre":{a:"Africa/Maputo",c:["MW"],r:1},"Africa/Brazzaville":{a:"Africa/Lagos",c:["CG"],r:1},"Africa/Bujumbura":{a:"Africa/Maputo",c:["BI"],r:1},"Africa/Cairo":{u:120,c:["EG"]},"Africa/Casablanca":{u:60,d:0,c:["MA"]},"Africa/Ceuta":{u:60,d:120,c:["ES"]},"Africa/Conakry":{a:"Africa/Abidjan",c:["GN"],r:1},"Africa/Dakar":{a:"Africa/Abidjan",c:["SN"],r:1},"Africa/Dar_es_Salaam":{a:"Africa/Nairobi",c:["TZ"],r:1},"Africa/Djibouti":{a:"Africa/Nairobi",c:["DJ"],r:1},"Africa/Douala":{a:"Africa/Lagos",c:["CM"],r:1},"Africa/El_Aaiun":{u:60,d:0,c:["EH"]},"Africa/Freetown":{a:"Africa/Abidjan",c:["SL"],r:1},"Africa/Gaborone":{a:"Africa/Maputo",c:["BW"],r:1},"Africa/Harare":{a:"Africa/Maputo",c:["ZW"],r:1},"Africa/Johannesburg":{u:120,c:["ZA","LS","SZ"]},"Africa/Juba":{u:120,c:["SS"]},"Africa/Kampala":{a:"Africa/Nairobi",c:["UG"],r:1},"Africa/Khartoum":{u:120,c:["SD"]},"Africa/Kigali":{a:"Africa/Maputo",c:["RW"],r:1},"Africa/Kinshasa":{a:"Africa/Lagos",c:["CD"],r:1},"Africa/Lagos":{u:60,c:["NG","AO","BJ","CD","CF","CG","CM","GA","GQ","NE"]},"Africa/Libreville":{a:"Africa/Lagos",c:["GA"],r:1},"Africa/Lome":{a:"Africa/Abidjan",c:["TG"],r:1},"Africa/Luanda":{a:"Africa/Lagos",c:["AO"],r:1},"Africa/Lubumbashi":{a:"Africa/Maputo",c:["CD"],r:1},"Africa/Lusaka":{a:"Africa/Maputo",c:["ZM"],r:1},"Africa/Malabo":{a:"Africa/Lagos",c:["GQ"],r:1},"Africa/Maputo":{u:120,c:["MZ","BI","BW","CD","MW","RW","ZM","ZW"]},"Africa/Maseru":{a:"Africa/Johannesburg",c:["LS"],r:1},"Africa/Mbabane":{a:"Africa/Johannesburg",c:["SZ"],r:1},"Africa/Mogadishu":{a:"Africa/Nairobi",c:["SO"],r:1},"Africa/Monrovia":{u:0,c:["LR"]},"Africa/Nairobi":{u:180,c:["KE","DJ","ER","ET","KM","MG","SO","TZ","UG","YT"]},"Africa/Ndjamena":{u:60,c:["TD"]},"Africa/Niamey":{a:"Africa/Lagos",c:["NE"],r:1},"Africa/Nouakchott":{a:"Africa/Abidjan",c:["MR"],r:1},"Africa/Ouagadougou":{a:"Africa/Abidjan",c:["BF"],r:1},"Africa/Porto-Novo":{a:"Africa/Lagos",c:["BJ"],r:1},"Africa/Sao_Tome":{u:0,c:["ST"]},"Africa/Timbuktu":{a:"Africa/Abidjan",c:["ML"],r:1},"Africa/Tripoli":{u:120,c:["LY"]},"Africa/Tunis":{u:60,c:["TN"]},"Africa/Windhoek":{u:120,c:["NA"]},"America/Adak":{u:-600,d:-540,c:["US"]},"America/Anchorage":{u:-540,d:-480,c:["US"]},"America/Anguilla":{a:"America/Puerto_Rico",c:["AI"],r:1},"America/Antigua":{a:"America/Puerto_Rico",c:["AG"],r:1},"America/Araguaina":{u:-180,c:["BR"]},"America/Argentina/Buenos_Aires":{u:-180,c:["AR"]},"America/Argentina/Catamarca":{u:-180,c:["AR"]},"America/Argentina/ComodRivadavia":{a:"America/Argentina/Catamarca",r:1},"America/Argentina/Cordoba":{u:-180,c:["AR"]},"America/Argentina/Jujuy":{u:-180,c:["AR"]},"America/Argentina/La_Rioja":{u:-180,c:["AR"]},"America/Argentina/Mendoza":{u:-180,c:["AR"]},"America/Argentina/Rio_Gallegos":{u:-180,c:["AR"]},"America/Argentina/Salta":{u:-180,c:["AR"]},"America/Argentina/San_Juan":{u:-180,c:["AR"]},"America/Argentina/San_Luis":{u:-180,c:["AR"]},"America/Argentina/Tucuman":{u:-180,c:["AR"]},"America/Argentina/Ushuaia":{u:-180,c:["AR"]},"America/Aruba":{a:"America/Puerto_Rico",c:["AW"],r:1},"America/Asuncion":{u:-240,d:-180,c:["PY"]},"America/Atikokan":{a:"America/Panama",c:["CA"],r:1},"America/Atka":{a:"America/Adak",r:1},"America/Bahia":{u:-180,c:["BR"]},"America/Bahia_Banderas":{u:-360,d:-300,c:["MX"]},"America/Barbados":{u:-240,c:["BB"]},"America/Belem":{u:-180,c:["BR"]},"America/Belize":{u:-360,c:["BZ"]},"America/Blanc-Sablon":{a:"America/Puerto_Rico",c:["CA"],r:1},"America/Boa_Vista":{u:-240,c:["BR"]},"America/Bogota":{u:-300,c:["CO"]},"America/Boise":{u:-420,d:-360,c:["US"]},"America/Buenos_Aires":{a:"America/Argentina/Buenos_Aires",r:1},"America/Cambridge_Bay":{u:-420,d:-360,c:["CA"]},"America/Campo_Grande":{u:-240,c:["BR"]},"America/Cancun":{u:-300,c:["MX"]},"America/Caracas":{u:-240,c:["VE"]},"America/Catamarca":{a:"America/Argentina/Catamarca",r:1},"America/Cayenne":{u:-180,c:["GF"]},"America/Cayman":{a:"America/Panama",c:["KY"],r:1},"America/Chicago":{u:-360,d:-300,c:["US"]},"America/Chihuahua":{u:-420,d:-360,c:["MX"]},"America/Coral_Harbour":{a:"America/Panama",c:["CA"],r:1},"America/Cordoba":{a:"America/Argentina/Cordoba",r:1},"America/Costa_Rica":{u:-360,c:["CR"]},"America/Creston":{a:"America/Phoenix",c:["CA"],r:1},"America/Cuiaba":{u:-240,c:["BR"]},"America/Curacao":{a:"America/Puerto_Rico",c:["CW"],r:1},"America/Danmarkshavn":{u:0,c:["GL"]},"America/Dawson":{u:-420,c:["CA"]},"America/Dawson_Creek":{u:-420,c:["CA"]},"America/Denver":{u:-420,d:-360,c:["US"]},"America/Detroit":{u:-300,d:-240,c:["US"]},"America/Dominica":{a:"America/Puerto_Rico",c:["DM"],r:1},"America/Edmonton":{u:-420,d:-360,c:["CA"]},"America/Eirunepe":{u:-300,c:["BR"]},"America/El_Salvador":{u:-360,c:["SV"]},"America/Ensenada":{a:"America/Tijuana",r:1},"America/Fort_Nelson":{u:-420,c:["CA"]},"America/Fort_Wayne":{a:"America/Indiana/Indianapolis",r:1},"America/Fortaleza":{u:-180,c:["BR"]},"America/Glace_Bay":{u:-240,d:-180,c:["CA"]},"America/Godthab":{a:"America/Nuuk",r:1},"America/Goose_Bay":{u:-240,d:-180,c:["CA"]},"America/Grand_Turk":{u:-300,d:-240,c:["TC"]},"America/Grenada":{a:"America/Puerto_Rico",c:["GD"],r:1},"America/Guadeloupe":{a:"America/Puerto_Rico",c:["GP"],r:1},"America/Guatemala":{u:-360,c:["GT"]},"America/Guayaquil":{u:-300,c:["EC"]},"America/Guyana":{u:-240,c:["GY"]},"America/Halifax":{u:-240,d:-180,c:["CA"]},"America/Havana":{u:-300,d:-240,c:["CU"]},"America/Hermosillo":{u:-420,c:["MX"]},"America/Indiana/Indianapolis":{u:-300,d:-240,c:["US"]},"America/Indiana/Knox":{u:-360,d:-300,c:["US"]},"America/Indiana/Marengo":{u:-300,d:-240,c:["US"]},"America/Indiana/Petersburg":{u:-300,d:-240,c:["US"]},"America/Indiana/Tell_City":{u:-360,d:-300,c:["US"]},"America/Indiana/Vevay":{u:-300,d:-240,c:["US"]},"America/Indiana/Vincennes":{u:-300,d:-240,c:["US"]},"America/Indiana/Winamac":{u:-300,d:-240,c:["US"]},"America/Indianapolis":{a:"America/Indiana/Indianapolis",r:1},"America/Inuvik":{u:-420,d:-360,c:["CA"]},"America/Iqaluit":{u:-300,d:-240,c:["CA"]},"America/Jamaica":{u:-300,c:["JM"]},"America/Jujuy":{a:"America/Argentina/Jujuy",r:1},"America/Juneau":{u:-540,d:-480,c:["US"]},"America/Kentucky/Louisville":{u:-300,d:-240,c:["US"]},"America/Kentucky/Monticello":{u:-300,d:-240,c:["US"]},"America/Knox_IN":{a:"America/Indiana/Knox",r:1},"America/Kralendijk":{a:"America/Puerto_Rico",c:["BQ"],r:1},"America/La_Paz":{u:-240,c:["BO"]},"America/Lima":{u:-300,c:["PE"]},"America/Los_Angeles":{u:-480,d:-420,c:["US"]},"America/Louisville":{a:"America/Kentucky/Louisville",r:1},"America/Lower_Princes":{a:"America/Puerto_Rico",c:["SX"],r:1},"America/Maceio":{u:-180,c:["BR"]},"America/Managua":{u:-360,c:["NI"]},"America/Manaus":{u:-240,c:["BR"]},"America/Marigot":{a:"America/Puerto_Rico",c:["MF"],r:1},"America/Martinique":{u:-240,c:["MQ"]},"America/Matamoros":{u:-360,d:-300,c:["MX"]},"America/Mazatlan":{u:-420,d:-360,c:["MX"]},"America/Mendoza":{a:"America/Argentina/Mendoza",r:1},"America/Menominee":{u:-360,d:-300,c:["US"]},"America/Merida":{u:-360,d:-300,c:["MX"]},"America/Metlakatla":{u:-540,d:-480,c:["US"]},"America/Mexico_City":{u:-360,d:-300,c:["MX"]},"America/Miquelon":{u:-180,d:-120,c:["PM"]},"America/Moncton":{u:-240,d:-180,c:["CA"]},"America/Monterrey":{u:-360,d:-300,c:["MX"]},"America/Montevideo":{u:-180,c:["UY"]},"America/Montreal":{a:"America/Toronto",c:["CA"],r:1},"America/Montserrat":{a:"America/Puerto_Rico",c:["MS"],r:1},"America/Nassau":{a:"America/Toronto",c:["BS"],r:1},"America/New_York":{u:-300,d:-240,c:["US"]},"America/Nipigon":{u:-300,d:-240,c:["CA"]},"America/Nome":{u:-540,d:-480,c:["US"]},"America/Noronha":{u:-120,c:["BR"]},"America/North_Dakota/Beulah":{u:-360,d:-300,c:["US"]},"America/North_Dakota/Center":{u:-360,d:-300,c:["US"]},"America/North_Dakota/New_Salem":{u:-360,d:-300,c:["US"]},"America/Nuuk":{u:-180,d:-120,c:["GL"]},"America/Ojinaga":{u:-420,d:-360,c:["MX"]},"America/Panama":{u:-300,c:["PA","CA","KY"]},"America/Pangnirtung":{u:-300,d:-240,c:["CA"]},"America/Paramaribo":{u:-180,c:["SR"]},"America/Phoenix":{u:-420,c:["US","CA"]},"America/Port-au-Prince":{u:-300,d:-240,c:["HT"]},"America/Port_of_Spain":{a:"America/Puerto_Rico",c:["TT"],r:1},"America/Porto_Acre":{a:"America/Rio_Branco",r:1},"America/Porto_Velho":{u:-240,c:["BR"]},"America/Puerto_Rico":{u:-240,c:["PR","AG","CA","AI","AW","BL","BQ","CW","DM","GD","GP","KN","LC","MF","MS","SX","TT","VC","VG","VI"]},"America/Punta_Arenas":{u:-180,c:["CL"]},"America/Rainy_River":{u:-360,d:-300,c:["CA"]},"America/Rankin_Inlet":{u:-360,d:-300,c:["CA"]},"America/Recife":{u:-180,c:["BR"]},"America/Regina":{u:-360,c:["CA"]},"America/Resolute":{u:-360,d:-300,c:["CA"]},"America/Rio_Branco":{u:-300,c:["BR"]},"America/Rosario":{a:"America/Argentina/Cordoba",r:1},"America/Santa_Isabel":{a:"America/Tijuana",r:1},"America/Santarem":{u:-180,c:["BR"]},"America/Santiago":{u:-240,d:-180,c:["CL"]},"America/Santo_Domingo":{u:-240,c:["DO"]},"America/Sao_Paulo":{u:-180,c:["BR"]},"America/Scoresbysund":{u:-60,d:0,c:["GL"]},"America/Shiprock":{a:"America/Denver",r:1},"America/Sitka":{u:-540,d:-480,c:["US"]},"America/St_Barthelemy":{a:"America/Puerto_Rico",c:["BL"],r:1},"America/St_Johns":{u:-150,d:-90,c:["CA"]},"America/St_Kitts":{a:"America/Puerto_Rico",c:["KN"],r:1},"America/St_Lucia":{a:"America/Puerto_Rico",c:["LC"],r:1},"America/St_Thomas":{a:"America/Puerto_Rico",c:["VI"],r:1},"America/St_Vincent":{a:"America/Puerto_Rico",c:["VC"],r:1},"America/Swift_Current":{u:-360,c:["CA"]},"America/Tegucigalpa":{u:-360,c:["HN"]},"America/Thule":{u:-240,d:-180,c:["GL"]},"America/Thunder_Bay":{u:-300,d:-240,c:["CA"]},"America/Tijuana":{u:-480,d:-420,c:["MX"]},"America/Toronto":{u:-300,d:-240,c:["CA","BS"]},"America/Tortola":{a:"America/Puerto_Rico",c:["VG"],r:1},"America/Vancouver":{u:-480,d:-420,c:["CA"]},"America/Virgin":{a:"America/Puerto_Rico",c:["VI"],r:1},"America/Whitehorse":{u:-420,c:["CA"]},"America/Winnipeg":{u:-360,d:-300,c:["CA"]},"America/Yakutat":{u:-540,d:-480,c:["US"]},"America/Yellowknife":{u:-420,d:-360,c:["CA"]},"Antarctica/Casey":{u:660,c:["AQ"]},"Antarctica/Davis":{u:420,c:["AQ"]},"Antarctica/DumontDUrville":{a:"Pacific/Port_Moresby",c:["AQ"],r:1},"Antarctica/Macquarie":{u:600,d:660,c:["AU"]},"Antarctica/Mawson":{u:300,c:["AQ"]},"Antarctica/McMurdo":{a:"Pacific/Auckland",c:["AQ"],r:1},"Antarctica/Palmer":{u:-180,c:["AQ"]},"Antarctica/Rothera":{u:-180,c:["AQ"]},"Antarctica/South_Pole":{a:"Pacific/Auckland",c:["AQ"],r:1},"Antarctica/Syowa":{a:"Asia/Riyadh",c:["AQ"],r:1},"Antarctica/Troll":{u:0,d:120,c:["AQ"]},"Antarctica/Vostok":{u:360,c:["AQ"]},"Arctic/Longyearbyen":{a:"Europe/Oslo",c:["SJ"],r:1},"Asia/Aden":{a:"Asia/Riyadh",c:["YE"],r:1},"Asia/Almaty":{u:360,c:["KZ"]},"Asia/Amman":{u:120,d:180,c:["JO"]},"Asia/Anadyr":{u:720,c:["RU"]},"Asia/Aqtau":{u:300,c:["KZ"]},"Asia/Aqtobe":{u:300,c:["KZ"]},"Asia/Ashgabat":{u:300,c:["TM"]},"Asia/Ashkhabad":{a:"Asia/Ashgabat",r:1},"Asia/Atyrau":{u:300,c:["KZ"]},"Asia/Baghdad":{u:180,c:["IQ"]},"Asia/Bahrain":{a:"Asia/Qatar",c:["BH"],r:1},"Asia/Baku":{u:240,c:["AZ"]},"Asia/Bangkok":{u:420,c:["TH","KH","LA","VN"]},"Asia/Barnaul":{u:420,c:["RU"]},"Asia/Beirut":{u:120,d:180,c:["LB"]},"Asia/Bishkek":{u:360,c:["KG"]},"Asia/Brunei":{u:480,c:["BN"]},"Asia/Calcutta":{a:"Asia/Kolkata",r:1},"Asia/Chita":{u:540,c:["RU"]},"Asia/Choibalsan":{u:480,c:["MN"]},"Asia/Chongqing":{a:"Asia/Shanghai",r:1},"Asia/Chungking":{a:"Asia/Shanghai",r:1},"Asia/Colombo":{u:330,c:["LK"]},"Asia/Dacca":{a:"Asia/Dhaka",r:1},"Asia/Damascus":{u:120,d:180,c:["SY"]},"Asia/Dhaka":{u:360,c:["BD"]},"Asia/Dili":{u:540,c:["TL"]},"Asia/Dubai":{u:240,c:["AE","OM"]},"Asia/Dushanbe":{u:300,c:["TJ"]},"Asia/Famagusta":{u:120,d:180,c:["CY"]},"Asia/Gaza":{u:120,d:180,c:["PS"]},"Asia/Harbin":{a:"Asia/Shanghai",r:1},"Asia/Hebron":{u:120,d:180,c:["PS"]},"Asia/Ho_Chi_Minh":{u:420,c:["VN"]},"Asia/Hong_Kong":{u:480,c:["HK"]},"Asia/Hovd":{u:420,c:["MN"]},"Asia/Irkutsk":{u:480,c:["RU"]},"Asia/Istanbul":{a:"Europe/Istanbul",r:1},"Asia/Jakarta":{u:420,c:["ID"]},"Asia/Jayapura":{u:540,c:["ID"]},"Asia/Jerusalem":{u:120,d:180,c:["IL"]},"Asia/Kabul":{u:270,c:["AF"]},"Asia/Kamchatka":{u:720,c:["RU"]},"Asia/Karachi":{u:300,c:["PK"]},"Asia/Kashgar":{a:"Asia/Urumqi",r:1},"Asia/Kathmandu":{u:345,c:["NP"]},"Asia/Katmandu":{a:"Asia/Kathmandu",r:1},"Asia/Khandyga":{u:540,c:["RU"]},"Asia/Kolkata":{u:330,c:["IN"]},"Asia/Krasnoyarsk":{u:420,c:["RU"]},"Asia/Kuala_Lumpur":{u:480,c:["MY"]},"Asia/Kuching":{u:480,c:["MY"]},"Asia/Kuwait":{a:"Asia/Riyadh",c:["KW"],r:1},"Asia/Macao":{a:"Asia/Macau",r:1},"Asia/Macau":{u:480,c:["MO"]},"Asia/Magadan":{u:660,c:["RU"]},"Asia/Makassar":{u:480,c:["ID"]},"Asia/Manila":{u:480,c:["PH"]},"Asia/Muscat":{a:"Asia/Dubai",c:["OM"],r:1},"Asia/Nicosia":{u:120,d:180,c:["CY"]},"Asia/Novokuznetsk":{u:420,c:["RU"]},"Asia/Novosibirsk":{u:420,c:["RU"]},"Asia/Omsk":{u:360,c:["RU"]},"Asia/Oral":{u:300,c:["KZ"]},"Asia/Phnom_Penh":{a:"Asia/Bangkok",c:["KH"],r:1},"Asia/Pontianak":{u:420,c:["ID"]},"Asia/Pyongyang":{u:540,c:["KP"]},"Asia/Qatar":{u:180,c:["QA","BH"]},"Asia/Qostanay":{u:360,c:["KZ"]},"Asia/Qyzylorda":{u:300,c:["KZ"]},"Asia/Rangoon":{a:"Asia/Yangon",r:1},"Asia/Riyadh":{u:180,c:["SA","AQ","KW","YE"]},"Asia/Saigon":{a:"Asia/Ho_Chi_Minh",r:1},"Asia/Sakhalin":{u:660,c:["RU"]},"Asia/Samarkand":{u:300,c:["UZ"]},"Asia/Seoul":{u:540,c:["KR"]},"Asia/Shanghai":{u:480,c:["CN"]},"Asia/Singapore":{u:480,c:["SG","MY"]},"Asia/Srednekolymsk":{u:660,c:["RU"]},"Asia/Taipei":{u:480,c:["TW"]},"Asia/Tashkent":{u:300,c:["UZ"]},"Asia/Tbilisi":{u:240,c:["GE"]},"Asia/Tehran":{u:210,d:270,c:["IR"]},"Asia/Tel_Aviv":{a:"Asia/Jerusalem",r:1},"Asia/Thimbu":{a:"Asia/Thimphu",r:1},"Asia/Thimphu":{u:360,c:["BT"]},"Asia/Tokyo":{u:540,c:["JP"]},"Asia/Tomsk":{u:420,c:["RU"]},"Asia/Ujung_Pandang":{a:"Asia/Makassar",r:1},"Asia/Ulaanbaatar":{u:480,c:["MN"]},"Asia/Ulan_Bator":{a:"Asia/Ulaanbaatar",r:1},"Asia/Urumqi":{u:360,c:["CN"]},"Asia/Ust-Nera":{u:600,c:["RU"]},"Asia/Vientiane":{a:"Asia/Bangkok",c:["LA"],r:1},"Asia/Vladivostok":{u:600,c:["RU"]},"Asia/Yakutsk":{u:540,c:["RU"]},"Asia/Yangon":{u:390,c:["MM"]},"Asia/Yekaterinburg":{u:300,c:["RU"]},"Asia/Yerevan":{u:240,c:["AM"]},"Atlantic/Azores":{u:-60,d:0,c:["PT"]},"Atlantic/Bermuda":{u:-240,d:-180,c:["BM"]},"Atlantic/Canary":{u:0,d:60,c:["ES"]},"Atlantic/Cape_Verde":{u:-60,c:["CV"]},"Atlantic/Faeroe":{a:"Atlantic/Faroe",r:1},"Atlantic/Faroe":{u:0,d:60,c:["FO"]},"Atlantic/Jan_Mayen":{a:"Europe/Oslo",c:["SJ"],r:1},"Atlantic/Madeira":{u:0,d:60,c:["PT"]},"Atlantic/Reykjavik":{u:0,c:["IS"]},"Atlantic/South_Georgia":{u:-120,c:["GS"]},"Atlantic/St_Helena":{a:"Africa/Abidjan",c:["SH"],r:1},"Atlantic/Stanley":{u:-180,c:["FK"]},"Australia/ACT":{a:"Australia/Sydney",r:1},"Australia/Adelaide":{u:570,d:630,c:["AU"]},"Australia/Brisbane":{u:600,c:["AU"]},"Australia/Broken_Hill":{u:570,d:630,c:["AU"]},"Australia/Canberra":{a:"Australia/Sydney",r:1},"Australia/Currie":{a:"Australia/Hobart",r:1},"Australia/Darwin":{u:570,c:["AU"]},"Australia/Eucla":{u:525,c:["AU"]},"Australia/Hobart":{u:600,d:660,c:["AU"]},"Australia/LHI":{a:"Australia/Lord_Howe",r:1},"Australia/Lindeman":{u:600,c:["AU"]},"Australia/Lord_Howe":{u:630,d:660,c:["AU"]},"Australia/Melbourne":{u:600,d:660,c:["AU"]},"Australia/NSW":{a:"Australia/Sydney",r:1},"Australia/North":{a:"Australia/Darwin",r:1},"Australia/Perth":{u:480,c:["AU"]},"Australia/Queensland":{a:"Australia/Brisbane",r:1},"Australia/South":{a:"Australia/Adelaide",r:1},"Australia/Sydney":{u:600,d:660,c:["AU"]},"Australia/Tasmania":{a:"Australia/Hobart",r:1},"Australia/Victoria":{a:"Australia/Melbourne",r:1},"Australia/West":{a:"Australia/Perth",r:1},"Australia/Yancowinna":{a:"Australia/Broken_Hill",r:1},"Brazil/Acre":{a:"America/Rio_Branco",r:1},"Brazil/DeNoronha":{a:"America/Noronha",r:1},"Brazil/East":{a:"America/Sao_Paulo",r:1},"Brazil/West":{a:"America/Manaus",r:1},CET:{u:60,d:120},CST6CDT:{u:-360,d:-300},"Canada/Atlantic":{a:"America/Halifax",r:1},"Canada/Central":{a:"America/Winnipeg",r:1},"Canada/Eastern":{a:"America/Toronto",c:["CA"],r:1},"Canada/Mountain":{a:"America/Edmonton",r:1},"Canada/Newfoundland":{a:"America/St_Johns",r:1},"Canada/Pacific":{a:"America/Vancouver",r:1},"Canada/Saskatchewan":{a:"America/Regina",r:1},"Canada/Yukon":{a:"America/Whitehorse",r:1},"Chile/Continental":{a:"America/Santiago",r:1},"Chile/EasterIsland":{a:"Pacific/Easter",r:1},Cuba:{a:"America/Havana",r:1},EET:{u:120,d:180},EST:{u:-300},EST5EDT:{u:-300,d:-240},Egypt:{a:"Africa/Cairo",r:1},Eire:{a:"Europe/Dublin",r:1},"Etc/GMT":{u:0},"Etc/GMT+0":{a:"Etc/GMT",r:1},"Etc/GMT+1":{u:-60},"Etc/GMT+10":{u:-600},"Etc/GMT+11":{u:-660},"Etc/GMT+12":{u:-720},"Etc/GMT+2":{u:-120},"Etc/GMT+3":{u:-180},"Etc/GMT+4":{u:-240},"Etc/GMT+5":{u:-300},"Etc/GMT+6":{u:-360},"Etc/GMT+7":{u:-420},"Etc/GMT+8":{u:-480},"Etc/GMT+9":{u:-540},"Etc/GMT-0":{a:"Etc/GMT",r:1},"Etc/GMT-1":{u:60},"Etc/GMT-10":{u:600},"Etc/GMT-11":{u:660},"Etc/GMT-12":{u:720},"Etc/GMT-13":{u:780},"Etc/GMT-14":{u:840},"Etc/GMT-2":{u:120},"Etc/GMT-3":{u:180},"Etc/GMT-4":{u:240},"Etc/GMT-5":{u:300},"Etc/GMT-6":{u:360},"Etc/GMT-7":{u:420},"Etc/GMT-8":{u:480},"Etc/GMT-9":{u:540},"Etc/GMT0":{a:"Etc/GMT",r:1},"Etc/Greenwich":{a:"Etc/GMT",r:1},"Etc/UCT":{a:"Etc/UTC",r:1},"Etc/UTC":{u:0},"Etc/Universal":{a:"Etc/UTC",r:1},"Etc/Zulu":{a:"Etc/UTC",r:1},"Europe/Amsterdam":{u:60,d:120,c:["NL"]},"Europe/Andorra":{u:60,d:120,c:["AD"]},"Europe/Astrakhan":{u:240,c:["RU"]},"Europe/Athens":{u:120,d:180,c:["GR"]},"Europe/Belfast":{a:"Europe/London",c:["GB"],r:1},"Europe/Belgrade":{u:60,d:120,c:["RS","BA","HR","ME","MK","SI"]},"Europe/Berlin":{u:60,d:120,c:["DE"]},"Europe/Bratislava":{a:"Europe/Prague",c:["SK"],r:1},"Europe/Brussels":{u:60,d:120,c:["BE"]},"Europe/Bucharest":{u:120,d:180,c:["RO"]},"Europe/Budapest":{u:60,d:120,c:["HU"]},"Europe/Busingen":{a:"Europe/Zurich",c:["DE"],r:1},"Europe/Chisinau":{u:120,d:180,c:["MD"]},"Europe/Copenhagen":{u:60,d:120,c:["DK"]},"Europe/Dublin":{u:60,d:0,c:["IE"]},"Europe/Gibraltar":{u:60,d:120,c:["GI"]},"Europe/Guernsey":{a:"Europe/London",c:["GG"],r:1},"Europe/Helsinki":{u:120,d:180,c:["FI","AX"]},"Europe/Isle_of_Man":{a:"Europe/London",c:["IM"],r:1},"Europe/Istanbul":{u:180,c:["TR"]},"Europe/Jersey":{a:"Europe/London",c:["JE"],r:1},"Europe/Kaliningrad":{u:120,c:["RU"]},"Europe/Kiev":{u:120,d:180,c:["UA"]},"Europe/Kirov":{u:180,c:["RU"]},"Europe/Lisbon":{u:0,d:60,c:["PT"]},"Europe/Ljubljana":{a:"Europe/Belgrade",c:["SI"],r:1},"Europe/London":{u:0,d:60,c:["GB","GG","IM","JE"]},"Europe/Luxembourg":{u:60,d:120,c:["LU"]},"Europe/Madrid":{u:60,d:120,c:["ES"]},"Europe/Malta":{u:60,d:120,c:["MT"]},"Europe/Mariehamn":{a:"Europe/Helsinki",c:["AX"],r:1},"Europe/Minsk":{u:180,c:["BY"]},"Europe/Monaco":{u:60,d:120,c:["MC"]},"Europe/Moscow":{u:180,c:["RU"]},"Europe/Nicosia":{a:"Asia/Nicosia",r:1},"Europe/Oslo":{u:60,d:120,c:["NO","SJ","BV"]},"Europe/Paris":{u:60,d:120,c:["FR"]},"Europe/Podgorica":{a:"Europe/Belgrade",c:["ME"],r:1},"Europe/Prague":{u:60,d:120,c:["CZ","SK"]},"Europe/Riga":{u:120,d:180,c:["LV"]},"Europe/Rome":{u:60,d:120,c:["IT","SM","VA"]},"Europe/Samara":{u:240,c:["RU"]},"Europe/San_Marino":{a:"Europe/Rome",c:["SM"],r:1},"Europe/Sarajevo":{a:"Europe/Belgrade",c:["BA"],r:1},"Europe/Saratov":{u:240,c:["RU"]},"Europe/Simferopol":{u:180,c:["RU","UA"]},"Europe/Skopje":{a:"Europe/Belgrade",c:["MK"],r:1},"Europe/Sofia":{u:120,d:180,c:["BG"]},"Europe/Stockholm":{u:60,d:120,c:["SE"]},"Europe/Tallinn":{u:120,d:180,c:["EE"]},"Europe/Tirane":{u:60,d:120,c:["AL"]},"Europe/Tiraspol":{a:"Europe/Chisinau",r:1},"Europe/Ulyanovsk":{u:240,c:["RU"]},"Europe/Uzhgorod":{u:120,d:180,c:["UA"]},"Europe/Vaduz":{a:"Europe/Zurich",c:["LI"],r:1},"Europe/Vatican":{a:"Europe/Rome",c:["VA"],r:1},"Europe/Vienna":{u:60,d:120,c:["AT"]},"Europe/Vilnius":{u:120,d:180,c:["LT"]},"Europe/Volgograd":{u:180,c:["RU"]},"Europe/Warsaw":{u:60,d:120,c:["PL"]},"Europe/Zagreb":{a:"Europe/Belgrade",c:["HR"],r:1},"Europe/Zaporozhye":{u:120,d:180,c:["UA"]},"Europe/Zurich":{u:60,d:120,c:["CH","DE","LI"]},Factory:{u:0},GB:{a:"Europe/London",c:["GB"],r:1},"GB-Eire":{a:"Europe/London",c:["GB"],r:1},GMT:{a:"Etc/GMT",r:1},"GMT+0":{a:"Etc/GMT",r:1},"GMT-0":{a:"Etc/GMT",r:1},GMT0:{a:"Etc/GMT",r:1},Greenwich:{a:"Etc/GMT",r:1},HST:{u:-600},Hongkong:{a:"Asia/Hong_Kong",r:1},Iceland:{a:"Atlantic/Reykjavik",r:1},"Indian/Antananarivo":{a:"Africa/Nairobi",c:["MG"],r:1},"Indian/Chagos":{u:360,c:["IO"]},"Indian/Christmas":{u:420,c:["CX"]},"Indian/Cocos":{u:390,c:["CC"]},"Indian/Comoro":{a:"Africa/Nairobi",c:["KM"],r:1},"Indian/Kerguelen":{u:300,c:["TF","HM"]},"Indian/Mahe":{u:240,c:["SC"]},"Indian/Maldives":{u:300,c:["MV"]},"Indian/Mauritius":{u:240,c:["MU"]},"Indian/Mayotte":{a:"Africa/Nairobi",c:["YT"],r:1},"Indian/Reunion":{u:240,c:["RE","TF"]},Iran:{a:"Asia/Tehran",r:1},Israel:{a:"Asia/Jerusalem",r:1},Jamaica:{a:"America/Jamaica",r:1},Japan:{a:"Asia/Tokyo",r:1},Kwajalein:{a:"Pacific/Kwajalein",r:1},Libya:{a:"Africa/Tripoli",r:1},MET:{u:60,d:120},MST:{u:-420},MST7MDT:{u:-420,d:-360},"Mexico/BajaNorte":{a:"America/Tijuana",r:1},"Mexico/BajaSur":{a:"America/Mazatlan",r:1},"Mexico/General":{a:"America/Mexico_City",r:1},NZ:{a:"Pacific/Auckland",c:["NZ"],r:1},"NZ-CHAT":{a:"Pacific/Chatham",r:1},Navajo:{a:"America/Denver",r:1},PRC:{a:"Asia/Shanghai",r:1},PST8PDT:{u:-480,d:-420},"Pacific/Apia":{u:780,c:["WS"]},"Pacific/Auckland":{u:720,d:780,c:["NZ","AQ"]},"Pacific/Bougainville":{u:660,c:["PG"]},"Pacific/Chatham":{u:765,d:825,c:["NZ"]},"Pacific/Chuuk":{u:600,c:["FM"]},"Pacific/Easter":{u:-360,d:-300,c:["CL"]},"Pacific/Efate":{u:660,c:["VU"]},"Pacific/Enderbury":{a:"Pacific/Kanton",r:1},"Pacific/Fakaofo":{u:780,c:["TK"]},"Pacific/Fiji":{u:720,d:780,c:["FJ"]},"Pacific/Funafuti":{u:720,c:["TV"]},"Pacific/Galapagos":{u:-360,c:["EC"]},"Pacific/Gambier":{u:-540,c:["PF"]},"Pacific/Guadalcanal":{u:660,c:["SB"]},"Pacific/Guam":{u:600,c:["GU","MP"]},"Pacific/Honolulu":{u:-600,c:["US","UM"]},"Pacific/Johnston":{a:"Pacific/Honolulu",c:["UM"],r:1},"Pacific/Kanton":{u:780,c:["KI"]},"Pacific/Kiritimati":{u:840,c:["KI"]},"Pacific/Kosrae":{u:660,c:["FM"]},"Pacific/Kwajalein":{u:720,c:["MH"]},"Pacific/Majuro":{u:720,c:["MH"]},"Pacific/Marquesas":{u:-510,c:["PF"]},"Pacific/Midway":{a:"Pacific/Pago_Pago",c:["UM"],r:1},"Pacific/Nauru":{u:720,c:["NR"]},"Pacific/Niue":{u:-660,c:["NU"]},"Pacific/Norfolk":{u:660,d:720,c:["NF"]},"Pacific/Noumea":{u:660,c:["NC"]},"Pacific/Pago_Pago":{u:-660,c:["AS","UM"]},"Pacific/Palau":{u:540,c:["PW"]},"Pacific/Pitcairn":{u:-480,c:["PN"]},"Pacific/Pohnpei":{u:660,c:["FM"]},"Pacific/Ponape":{a:"Pacific/Pohnpei",r:1},"Pacific/Port_Moresby":{u:600,c:["PG","AQ"]},"Pacific/Rarotonga":{u:-600,c:["CK"]},"Pacific/Saipan":{a:"Pacific/Guam",c:["MP"],r:1},"Pacific/Samoa":{a:"Pacific/Pago_Pago",c:["WS"],r:1},"Pacific/Tahiti":{u:-600,c:["PF"]},"Pacific/Tarawa":{u:720,c:["KI"]},"Pacific/Tongatapu":{u:780,c:["TO"]},"Pacific/Truk":{a:"Pacific/Chuuk",r:1},"Pacific/Wake":{u:720,c:["UM"]},"Pacific/Wallis":{u:720,c:["WF"]},"Pacific/Yap":{a:"Pacific/Chuuk",r:1},Poland:{a:"Europe/Warsaw",r:1},Portugal:{a:"Europe/Lisbon",r:1},ROC:{a:"Asia/Taipei",r:1},ROK:{a:"Asia/Seoul",r:1},Singapore:{a:"Asia/Singapore",c:["SG"],r:1},Turkey:{a:"Europe/Istanbul",r:1},UCT:{a:"Etc/UTC",r:1},"US/Alaska":{a:"America/Anchorage",r:1},"US/Aleutian":{a:"America/Adak",r:1},"US/Arizona":{a:"America/Phoenix",c:["US"],r:1},"US/Central":{a:"America/Chicago",r:1},"US/East-Indiana":{a:"America/Indiana/Indianapolis",r:1},"US/Eastern":{a:"America/New_York",r:1},"US/Hawaii":{a:"Pacific/Honolulu",c:["US"],r:1},"US/Indiana-Starke":{a:"America/Indiana/Knox",r:1},"US/Michigan":{a:"America/Detroit",r:1},"US/Mountain":{a:"America/Denver",r:1},"US/Pacific":{a:"America/Los_Angeles",r:1},"US/Samoa":{a:"Pacific/Pago_Pago",c:["WS"],r:1},UTC:{a:"Etc/UTC",r:1},Universal:{a:"Etc/UTC",r:1},"W-SU":{a:"Europe/Moscow",r:1},WET:{u:0,d:60},Zulu:{a:"Etc/UTC",r:1}};function j(){let s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s===""||!s)return null;try{let e=W[s]?.c?.[0];return e&&ye[e]||null}catch{return null}}function M(){let s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s===""||!s)return"Unknown";try{return W[s]?.c?.[0]||"Unknown"}catch{return"Unknown"}}function Y(){let s=Intl.DateTimeFormat().resolvedOptions().timeZone;return s===""||!s?null:s.split("/")[1]?.replace("_"," ")||null}var P=class{constructor(e,t){this.isDestroyed=!1;this.currentPath=null;this.originalPushState=null;this.originalReplaceState=null;this.previousPage=null;this.landingPage=null;this.pageViewCount=0;this.handlePopState=()=>{this.isDestroyed||this.trackCurrentPage()};this.handleHashChange=()=>{this.isDestroyed||this.trackCurrentPage()};this.tracker=e,this.config=t,this.trackCurrentPage(!0),this.setupHistoryListeners(),this.setupHashChangeListener()}setupHistoryListeners(){typeof window>"u"||typeof history>"u"||(this.originalPushState=history.pushState,history.pushState=(e,t,i)=>{this.originalPushState?.call(history,e,t,i),this.trackCurrentPage()},this.originalReplaceState=history.replaceState,history.replaceState=(e,t,i)=>{this.originalReplaceState?.call(history,e,t,i),this.trackCurrentPage()},window.addEventListener("popstate",this.handlePopState))}setupHashChangeListener(){typeof window>"u"||window.addEventListener("hashchange",this.handleHashChange)}trackCurrentPage(e=!1){if(this.isDestroyed||typeof window>"u")return;let t=this.extractPath(window.location.href);if(!e&&t===this.currentPath)return;this.currentPath&&(this.previousPage=this.currentPath),this.currentPath=t,this.pageViewCount++,e&&(this.landingPage=t);let i=this.tracker.hasConsent("analytics"),r=window.location.href,n=document.referrer||"",a=S(r);Object.keys(a).length>0&&(!p()||e)&&Q(a);let o=p()||{},l=C(this.config.tenantId,n,r,o),c={page:t,timestamp:Date.now()};if(i){c.title=document.title||"",c.full_url=this.cleanUrl(r),c.session_id=this.tracker.getSessionId(),n&&(c.referrer=n,c.referrer_domain=this.extractDomain(n),c.referrer_category=m(n,r)),this.landingPage&&!e&&(c.landing_page=this.landingPage),this.previousPage&&(c.previous_page=this.previousPage),o.utm_source&&(c.utm_source=o.utm_source),o.utm_medium&&(c.utm_medium=o.utm_medium),o.utm_campaign&&(c.utm_campaign=o.utm_campaign),o.utm_term&&(c.utm_term=o.utm_term),o.utm_content&&(c.utm_content=o.utm_content),c.first_touch_source=l.source,c.first_touch_medium=l.medium,c.first_touch_campaign=l.campaign,c.first_touch_referrer_category=l.referrer_category,c.device=this.getDeviceType(),c.browser=this.getBrowser(),c.os=this.getOS(),c.language=navigator.language||"";let d=Intl.DateTimeFormat().resolvedOptions().timeZone;c.timezone=d,c.country=M(),c.screen_resolution=`${screen.width}x${screen.height}`,c.viewport=`${window.innerWidth}x${window.innerHeight}`}this.tracker.trackSystemEvent("page_view",c)}extractDomain(e){try{return new URL(e).hostname}catch{return""}}getBrowser(){let e=navigator.userAgent;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")&&!e.includes("Chrome/")?"Safari":e.includes("Opera/")||e.includes("OPR/")?"Opera":"Unknown"}getOS(){let e=navigator.userAgent;return e.includes("Win")?"Windows":e.includes("Mac")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown"}getDeviceType(){let e=navigator.userAgent,t=window.innerWidth;return e.includes("iPad")||e.includes("Android")&&!e.includes("Mobile")?"Tablet":e.includes("Mobile")||e.includes("iPhone")||e.includes("Android")||t<768?"Mobile":t>=768&&t<1024?"Tablet":"Desktop"}extractPath(e){try{let t=new URL(e),i=t.pathname;return!this.config.stripQueryParams&&t.search&&(i+=t.search),!this.config.stripHash&&t.hash&&(i+=t.hash),i}catch(t){return this.config.debug&&console.warn("[Page Tracking] Failed to parse URL:",e,t),e}}cleanUrl(e){if(!this.config.stripQueryParams)return e;try{let t=new URL(e);return`${t.origin}${t.pathname}${this.config.stripHash?"":t.hash}`}catch{return e}}getCurrentPage(){return this.currentPath}trackPage(e,t){if(this.isDestroyed)return;let i=this.tracker.hasConsent("analytics"),r={page:e,timestamp:Date.now(),...t};i&&typeof document<"u"&&typeof window<"u"&&(r.referrer||(r.referrer=document.referrer||""),r.title||(r.title=document.title||""),r.full_url||(r.full_url=window.location.href),r.session_id||(r.session_id=this.tracker.getSessionId()),r.browser||(r.browser=this.getBrowser()),r.os||(r.os=this.getOS())),this.tracker.trackSystemEvent("page_view",r)}getPageViewCount(){return this.pageViewCount}destroy(){this.isDestroyed||(typeof history<"u"&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState)),typeof window<"u"&&(window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("hashchange",this.handleHashChange)),this.isDestroyed=!0)}};function X(s){let e=0;for(let t=0;t<s.length;t++){let i=s.charCodeAt(t);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}function J(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function be(){if(typeof window>"u")return"server";let s=[screen.width?.toString()||"",screen.height?.toString()||"",navigator.language||"",Intl.DateTimeFormat().resolvedOptions().timeZone||""];return X(s.join("|"))}function q(){let s=new Date,e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),i=String(s.getDate()).padStart(2,"0");return`${e}-${t}-${i}`}var I=class{constructor(e){this.cachedDailyId=null;this.dailyIdDate=null;this.dailyRandomSeed=null;this.permanentId=null;this.config=e,e.mode==="permanent"&&e.useLocalStorage&&this.loadPermanentId(),e.mode==="cookieless"&&this.loadDailySeed()}generateDailyRotatingId(){let e=q();if(this.cachedDailyId&&this.dailyIdDate===e&&this.dailyRandomSeed)return this.cachedDailyId;let t=this.loadDailySeed();this.dailyIdDate!==e&&(this.dailyRandomSeed=null,this.clearDailySeed()),this.dailyRandomSeed||(this.dailyRandomSeed=t||J(),this.saveDailySeed(this.dailyRandomSeed,e));let i=be(),r=`${this.config.tenantId}|${e}|${i}|${this.dailyRandomSeed}`,n=`daily_${X(r)}`;return this.cachedDailyId=n,this.dailyIdDate=e,n}generatePermanentId(){if(this.permanentId)return this.permanentId;if(this.config.useLocalStorage){let t=this.loadPermanentId();if(t)return t}let e=J();return this.permanentId=e,this.config.useLocalStorage&&this.savePermanentId(e),e}getCurrentUserId(){return this.config.mode==="cookieless"?this.generateDailyRotatingId():this.generatePermanentId()}setMode(e){this.config.mode=e,e==="permanent"&&(this.cachedDailyId=null,this.dailyIdDate=null,this.dailyRandomSeed=null,this.clearDailySeed()),e==="cookieless"&&(this.permanentId=null,this.config.useLocalStorage&&this.clearPermanentId(),this.loadDailySeed())}loadPermanentId(){if(typeof window>"u")return null;try{let e=`grain_anonymous_user_id_${this.config.tenantId}`,t=localStorage.getItem(e);if(t)return this.permanentId=t,t}catch{}return null}savePermanentId(e){if(!(typeof window>"u"))try{let t=`grain_anonymous_user_id_${this.config.tenantId}`;localStorage.setItem(t,e)}catch{}}clearPermanentId(){if(!(typeof window>"u"))try{let e=`grain_anonymous_user_id_${this.config.tenantId}`;localStorage.removeItem(e)}catch{}}loadDailySeed(){if(typeof window>"u")return null;try{let e=`grain_daily_seed_${this.config.tenantId}`,t=sessionStorage.getItem(e);if(t){let i=JSON.parse(t),r=q();if(i.date===r&&i.seed)return this.dailyRandomSeed=i.seed,this.dailyIdDate=i.date,i.seed;this.clearDailySeed()}}catch{}return null}saveDailySeed(e,t){if(!(typeof window>"u"))try{let i=`grain_daily_seed_${this.config.tenantId}`,r={seed:e,date:t};sessionStorage.setItem(i,JSON.stringify(r))}catch{}}clearDailySeed(){if(!(typeof window>"u"))try{let e=`grain_daily_seed_${this.config.tenantId}`;sessionStorage.removeItem(e)}catch{}}getIdInfo(){let e=this.getCurrentUserId();return{mode:this.config.mode,id:e,isDailyRotating:e.startsWith("daily_")}}};var v=class{constructor(e){this.eventQueue=[];this.waitingForConsentQueue=[];this.flushTimer=null;this.isDestroyed=!1;this.globalUserId=null;this.persistentAnonymousUserId=null;this.configCache=null;this.configRefreshTimer=null;this.configChangeListeners=[];this.configFetchPromise=null;this.cookiesEnabled=!1;this.activityDetector=null;this.heartbeatManager=null;this.pageTrackingManager=null;this.ephemeralSessionId=null;this.eventCountSinceLastHeartbeat=0;this.interactionTrackingManager=null;this.sectionTrackingManager=null;this.heatmapTrackingManager=null;this.sessionStartTime=Date.now();this.sessionEventCount=0;this.debugAgent=null;this.isDebugMode=!1;this.config={apiUrl:"https://api.grainql.com",authStrategy:"NONE",batchSize:50,flushInterval:5e3,retryAttempts:3,retryDelay:1e3,maxEventsPerRequest:160,debug:!1,defaultConfigurations:{},configCacheKey:"grain_config",configRefreshInterval:3e5,enableConfigCache:!0,consentMode:"COOKIELESS",waitForConsent:!1,disableAutoProperties:!1,enableHeartbeat:!0,heartbeatActiveInterval:12e4,heartbeatInactiveInterval:3e5,enableAutoPageView:!0,stripQueryParams:!0,stripHash:!1,enableHeatmapTracking:!0,...e,tenantId:e.tenantId},this.consentManager=new T(this.config.tenantId,this.config.consentMode);let t=this.consentManager.getIdMode();this.idManager=new I({mode:t,tenantId:this.config.tenantId,useLocalStorage:!0}),e.userId&&(this.globalUserId=e.userId),this.validateConfig(),this.setupBeforeUnload(),this.startFlushTimer(),this.initializeConfigCache(),this.ephemeralSessionId=this.generateUUID(),typeof window<"u"&&(this.checkAndInitializeDebugMode(),this.initializeAutomaticTracking(),this.trackSessionStart(),this.config.enableHeatmapTracking&&this.initializeHeatmapTracking()),this.consentManager.addListener(i=>{let r=this.consentManager.getIdMode();this.idManager.setMode(r),i.granted&&this.handleConsentGranted()})}validateConfig(){if(!this.config.tenantId)throw new Error("Grain Analytics: tenantId is required");if(this.config.authStrategy==="SERVER_SIDE"&&!this.config.secretKey)throw new Error("Grain Analytics: secretKey is required for SERVER_SIDE auth strategy");if(this.config.authStrategy==="JWT"&&!this.config.authProvider)throw new Error("Grain Analytics: authProvider is required for JWT auth strategy")}generateUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}shouldAllowPersistentStorage(){let e=this.consentManager.hasConsent("analytics"),t=this.config.consentMode==="COOKIELESS",i=!!this.globalUserId,r=this.config.authStrategy==="JWT";return t?!1:e||i||r}generateAnonymousUserId(){return this.generateUUID()}initializePersistentAnonymousUserId(){if(typeof window>"u")return;if(!this.shouldAllowPersistentStorage()){this.log("Opt-in mode without consent: skipping persistent ID initialization (GDPR compliance)");return}let e=`grain_anonymous_user_id_${this.config.tenantId}`,t="_grain_uid";try{if(this.cookiesEnabled){let r=K(t);if(r){this.persistentAnonymousUserId=r,this.log("Loaded persistent anonymous user ID from cookie:",this.persistentAnonymousUserId);return}}let i=localStorage.getItem(e);i?(this.persistentAnonymousUserId=i,this.log("Loaded persistent anonymous user ID from localStorage:",this.persistentAnonymousUserId),this.cookiesEnabled&&this.savePersistentAnonymousUserId(i)):(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId),this.log("Generated new persistent anonymous user ID:",this.persistentAnonymousUserId))}catch(i){this.log("Failed to initialize persistent anonymous user ID:",i),this.persistentAnonymousUserId=this.generateAnonymousUserId()}}savePersistentAnonymousUserId(e){if(typeof window>"u")return;if(!this.shouldAllowPersistentStorage()){this.log("Opt-in mode without consent: skipping persistent ID save (GDPR compliance)");return}let t=`grain_anonymous_user_id_${this.config.tenantId}`,i="_grain_uid";try{if(this.cookiesEnabled){let r={maxAge:31536e3,sameSite:"lax",secure:typeof window<"u"&&window.location.protocol==="https:",...this.config.cookieOptions};$(i,e,r)}localStorage.setItem(t,e)}catch(r){this.log("Failed to save persistent anonymous user ID:",r)}}getEffectiveUserIdInternal(){return this.globalUserId?this.globalUserId:this.idManager.getCurrentUserId()}log(...e){this.config.debug&&console.log("[Grain Analytics]",...e)}createErrorDigest(e){let t=[...new Set(e.map(a=>a.eventName))],i=[...new Set(e.map(a=>a.userId))],r=0,n=0;return e.forEach(a=>{let o=a.properties||{};r+=Object.keys(o).length,n+=JSON.stringify(a).length}),{eventCount:e.length,totalProperties:r,totalSize:n,eventNames:t,userIds:i}}formatError(e,t,i){let r=i?this.createErrorDigest(i):{eventCount:0,totalProperties:0,totalSize:0,eventNames:[],userIds:[]},n="UNKNOWN_ERROR",a="An unknown error occurred";if(e instanceof Error)a=e.message,a.includes("fetch failed")||a.includes("network error")?n="NETWORK_ERROR":a.includes("timeout")?n="TIMEOUT_ERROR":a.includes("HTTP 4")?n="CLIENT_ERROR":a.includes("HTTP 5")?n="SERVER_ERROR":a.includes("JSON")?n="PARSE_ERROR":a.includes("auth")||a.includes("unauthorized")?n="AUTH_ERROR":a.includes("rate limit")||a.includes("429")?n="RATE_LIMIT_ERROR":n="GENERAL_ERROR";else if(typeof e=="string")a=e,n="STRING_ERROR";else if(e&&typeof e=="object"&&"status"in e){let o=e.status;n=`HTTP_${o}`,a=`HTTP ${o} error`}return{code:n,message:a,digest:r,timestamp:new Date().toISOString(),context:t,originalError:e}}logError(e){if(!this.config.debug)return;let{code:t,message:i,digest:r,timestamp:n,context:a}=e,o={"\u{1F6A8} Grain Analytics Error":{"Error Code":t,Message:i,Context:a,Timestamp:n,"Event Digest":{Events:r.eventCount,Properties:r.totalProperties,"Size (bytes)":r.totalSize,"Event Names":r.eventNames.length>0?r.eventNames.join(", "):"None","User IDs":r.userIds.length>0?r.userIds.slice(0,3).join(", ")+(r.userIds.length>3?"...":""):"None"}}};console.error("\u{1F6A8} Grain Analytics Error:",o),console.error(`[Grain Analytics] ${t}: ${i} (${a}) - Events: ${r.eventCount}, Props: ${r.totalProperties}, Size: ${r.totalSize}B`)}async safeExecute(e,t,i){try{return await e()}catch(r){let n=this.formatError(r,t,i);return this.logError(n),null}}formatEvent(e){let t=e.properties||{};if(!this.config.disableAutoProperties&&typeof window<"u"){let i=this.consentManager.hasConsent("analytics");if(!e.eventName.startsWith("_grain_")&&i){let n=p();n&&(n.utm_source&&(t.utm_source=n.utm_source),n.utm_medium&&(t.utm_medium=n.utm_medium),n.utm_campaign&&(t.utm_campaign=n.utm_campaign),n.utm_term&&(t.utm_term=n.utm_term),n.utm_content&&(t.utm_content=n.utm_content));let a=R(this.config.tenantId);a&&(t.first_touch_source=a.source,t.first_touch_medium=a.medium,t.first_touch_campaign=a.campaign,t.first_touch_referrer_category=a.referrer_category),t.session_id||(t.session_id=this.getSessionId())}}return{eventName:e.eventName,userId:e.userId||this.getEffectiveUserIdInternal(),properties:t}}async getAuthHeaders(){let e={"Content-Type":"application/json"};switch(this.config.authStrategy){case"NONE":break;case"SERVER_SIDE":e.Authorization=`Chase ${this.config.secretKey}`;break;case"JWT":if(this.config.authProvider){let t=await this.config.authProvider.getToken();e.Authorization=`Bearer ${t}`}break}return e}async delay(e){return new Promise(t=>setTimeout(t,e))}isRetriableError(e){if(e instanceof Error){let t=e.message.toLowerCase();if(t.includes("fetch failed")||t==="network error"||t.includes("timeout")||t.includes("connection"))return!0}if(typeof e=="object"&&e!==null&&"status"in e){let t=e.status;return t>=500||t===429}return!1}async sendEvents(e){if(e.length===0)return;let t;for(let i=0;i<=this.config.retryAttempts;i++)try{let r=await this.getAuthHeaders(),n=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`,a=await fetch(n,{method:"POST",headers:r,body:JSON.stringify(e)});if(!a.ok){let o=`HTTP ${a.status}`;try{let c=await a.json();c?.message&&(o=c.message)}catch{let c=await a.text();c&&(o=c)}let l=new Error(`Failed to send events: ${o}`);throw l.status=a.status,l}this.log(`Successfully sent ${e.length} events`);return}catch(r){if(t=r,i===this.config.retryAttempts){let a=this.formatError(r,`sendEvents (attempt ${i+1}/${this.config.retryAttempts+1})`,e);this.logError(a);return}if(!this.isRetriableError(r)){let a=this.formatError(r,"sendEvents (non-retriable error)",e);this.logError(a);return}let n=this.config.retryDelay*Math.pow(2,i);this.log(`Retrying in ${n}ms after error:`,r),await this.delay(n)}}async sendEventsWithBeacon(e){if(e.length!==0)try{let t=await this.getAuthHeaders(),i=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`,r=JSON.stringify(e);if(!(this.config.authStrategy!=="NONE")&&typeof navigator<"u"&&"sendBeacon"in navigator){let a=new Blob([r],{type:"application/json"});if(navigator.sendBeacon(i,a)){this.log(`Successfully sent ${e.length} events via beacon`);return}}await fetch(i,{method:"POST",headers:t,body:r,keepalive:!0})}catch(t){let i=this.formatError(t,"sendEventsWithBeacon",e);this.logError(i)}}startFlushTimer(){typeof window>"u"||(this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=window.setInterval(()=>{this.eventQueue.length>0&&this.flush().catch(e=>{let t=this.formatError(e,"auto-flush");this.logError(t)})},this.config.flushInterval))}setupBeforeUnload(){if(typeof window>"u")return;let e=()=>{if(this.trackSessionEnd(),this.eventQueue.length>0){let t=[...this.eventQueue];this.eventQueue=[];let i=this.chunkEvents(t,this.config.maxEventsPerRequest);i.length>0&&this.sendEventsWithBeacon(i[0]).catch(()=>{})}};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden"&&this.eventQueue.length>0){let t=[...this.eventQueue];this.eventQueue=[];let i=this.chunkEvents(t,this.config.maxEventsPerRequest);i.length>0&&this.sendEventsWithBeacon(i[0]).catch(()=>{})}})}initializeAutomaticTracking(){if(this.config.enableHeartbeat)try{this.activityDetector=new w,this.heartbeatManager=new k(this,this.activityDetector,{activeInterval:this.config.heartbeatActiveInterval,inactiveInterval:this.config.heartbeatInactiveInterval,debug:this.config.debug})}catch(e){this.log("Failed to initialize heartbeat tracking:",e)}if(this.config.enableAutoPageView)try{this.pageTrackingManager=new P(this,{stripQueryParams:this.config.stripQueryParams,stripHash:this.config.stripHash,debug:this.config.debug,tenantId:this.config.tenantId})}catch(e){this.log("Failed to initialize page view tracking:",e)}this.initializeAutoTracking()}initializeHeatmapTracking(){if(!(typeof window>"u"))try{this.log("Initializing heatmap tracking"),Promise.resolve().then(()=>(ee(),Z)).then(({HeatmapTrackingManager:e})=>{try{this.heatmapTrackingManager=new e(this,{scrollDebounceDelay:100,batchDelay:2e3,maxBatchSize:20,debug:this.config.debug}),this.log("Heatmap tracking initialized")}catch(t){this.log("Failed to initialize heatmap tracking:",t)}}).catch(e=>{this.log("Failed to load heatmap tracking module:",e)})}catch(e){this.log("Failed to initialize heatmap tracking:",e)}}async initializeAutoTracking(){try{this.log("Initializing auto-tracking");let e=this.globalUserId||this.persistentAnonymousUserId||this.generateUUID(),t=typeof window<"u"?window.location.href:"",i={userId:e,immediateKeys:[],properties:{},currentUrl:t},r=await this.getAuthHeaders(),n=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`,a=await fetch(n,{method:"POST",headers:r,body:JSON.stringify(i)});if(!a.ok){this.log("Failed to fetch auto-tracking config:",a.status);return}let o=await a.json();o.autoTrackingConfig&&(this.log("Auto-tracking config loaded"),this.setupAutoTrackingManagers(o.autoTrackingConfig))}catch(e){this.log("Failed to initialize auto-tracking:",e)}}setupAutoTrackingManagers(e){this.log("Setting up auto-tracking managers"),e.interactions&&e.interactions.length>0&&(this.log("Loading interaction tracking:",e.interactions.length,"interactions"),Promise.resolve().then(()=>(ie(),te)).then(({InteractionTrackingManager:t})=>{try{this.interactionTrackingManager=new t(this,e.interactions,{debug:this.config.debug,enableMutationObserver:!0,mutationDebounceDelay:500,tenantId:this.config.tenantId,apiUrl:this.config.apiUrl}),this.log("Interaction tracking initialized")}catch(i){this.log("Failed to initialize interaction tracking:",i)}}).catch(t=>{this.log("Failed to load interaction tracking module:",t)})),e.sections&&e.sections.length>0&&(this.log("Loading section tracking:",e.sections.length,"sections"),Promise.resolve().then(()=>(ne(),re)).then(({SectionTrackingManager:t})=>{try{this.sectionTrackingManager=new t(this,e.sections,{minDwellTime:1e3,scrollVelocityThreshold:500,intersectionThreshold:.1,debounceDelay:100,batchDelay:2e3,debug:this.config.debug}),this.log("Section tracking initialized")}catch(i){this.log("Failed to initialize section tracking:",i)}}).catch(t=>{this.log("Failed to load section tracking module:",t)}))}trackSessionStart(){if(typeof window>"u")return;let e=this.consentManager.hasConsent("analytics"),t={session_id:this.getSessionId(),timestamp:this.sessionStartTime};if(e){let i=document.referrer||"",r=window.location.href,n=S(r),a=p()||n,o=C(this.config.tenantId,i,r,a);t.landing_page=window.location.pathname,i?(t.referrer=i,t.referrer_domain=new URL(i).hostname,t.referrer_category=m(i,r)):t.referrer_category="direct",a.utm_source&&(t.utm_source=a.utm_source),a.utm_medium&&(t.utm_medium=a.utm_medium),a.utm_campaign&&(t.utm_campaign=a.utm_campaign),a.utm_term&&(t.utm_term=a.utm_term),a.utm_content&&(t.utm_content=a.utm_content),t.first_touch_source=o.source,t.first_touch_medium=o.medium,t.first_touch_campaign=o.campaign,t.first_touch_referrer_category=o.referrer_category,t.device=this.getDeviceType(),t.screen_resolution=`${screen.width}x${screen.height}`,t.viewport=`${window.innerWidth}x${window.innerHeight}`,t.browser=this.getBrowser(),t.os=this.getOS(),t.language=navigator.language||"",t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}this.trackSystemEvent("_grain_session_start",t),this.log("Session started")}trackSessionEnd(){if(typeof window>"u")return;let e=this.consentManager.hasConsent("analytics"),t=Date.now()-this.sessionStartTime,i={session_id:this.getSessionId(),session_duration:Math.floor(t/1e3),duration:t,event_count:this.sessionEventCount,timestamp:Date.now()};if(e&&this.pageTrackingManager){let r=this.pageTrackingManager.getPageViewCount();i.pages_per_session=r,i.page_count=r}this.trackSystemEvent("_grain_session_end",i),this.log("Session ended")}getBrowser(){if(typeof navigator>"u")return"Unknown";let e=navigator.userAgent;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")&&!e.includes("Chrome/")?"Safari":e.includes("Opera/")||e.includes("OPR/")?"Opera":"Unknown"}getOS(){if(typeof navigator>"u")return"Unknown";let e=navigator.userAgent;return e.includes("Win")?"Windows":e.includes("Mac")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown"}getDeviceType(){if(typeof window>"u"||typeof navigator>"u")return"Unknown";let e=navigator.userAgent,t=window.innerWidth;return e.includes("iPad")||e.includes("Android")&&!e.includes("Mobile")?"Tablet":e.includes("Mobile")||e.includes("iPhone")||e.includes("Android")||t<768?"Mobile":t>=768&&t<1024?"Tablet":"Desktop"}handleConsentGranted(){this.flushWaitingForConsentQueue(),this.persistentAnonymousUserId||(this.initializePersistentAnonymousUserId(),this.log("Initialized persistent ID after consent grant")),this.ephemeralSessionId&&this.trackSystemEvent("_grain_consent_granted",{previous_session_id:this.ephemeralSessionId,new_user_id:this.getEffectiveUserId(),timestamp:Date.now()})}trackSystemEvent(e,t){if(this.isDestroyed)return;let i=this.consentManager.hasConsent("analytics"),r={eventName:e,userId:this.getEffectiveUserId(),properties:{...t,_minimal:!i,_consent_status:i?"granted":"pending"}};this.eventQueue.push(r),this.eventCountSinceLastHeartbeat++,this.log(`Queued system event: ${e}`),this.eventQueue.length>=this.config.batchSize&&this.flush().catch(n=>{let a=this.formatError(n,"flush system event");this.logError(a)})}getEphemeralSessionId(){return this.ephemeralSessionId||(this.ephemeralSessionId=this.generateUUID()),this.ephemeralSessionId}getCurrentPage(){return this.pageTrackingManager?.getCurrentPage()||null}getEventCountSinceLastHeartbeat(){return this.eventCountSinceLastHeartbeat}resetEventCountSinceLastHeartbeat(){this.eventCountSinceLastHeartbeat=0}getActivityDetector(){if(!this.activityDetector)throw new Error("Activity detector not initialized");return this.activityDetector}getEffectiveUserId(){return this.getEffectiveUserIdInternal()}getSessionId(){return this.consentManager.hasConsent("analytics")?this.getEffectiveUserId():this.getEphemeralSessionId()}async track(e,t,i){try{if(this.isDestroyed){let l=new Error("Grain Analytics: Client has been destroyed"),c=this.formatError(l,"track (client destroyed)");this.logError(c);return}let r,n={};if(typeof e=="string"?(r={eventName:e,properties:t},n=i||{}):(r=e,n=t||{}),this.config.allowedProperties&&r.properties){let l={};for(let c of this.config.allowedProperties)c in r.properties&&(l[c]=r.properties[c]);r.properties=l}let a=this.formatEvent(r);if(this.consentManager.shouldWaitForConsent()&&this.config.waitForConsent){this.waitingForConsentQueue.push(a),this.log(`Event waiting for consent: ${r.eventName}`,r.properties);return}let o=this.consentManager.hasConsent("analytics");a.properties={...a.properties,_minimal:!o,_consent_status:o?"granted":"pending"},this.eventQueue.push(a),this.eventCountSinceLastHeartbeat++,this.sessionEventCount++,this.log(`Queued event: ${r.eventName}`),(n.flush||this.eventQueue.length>=this.config.batchSize)&&await this.flush()}catch(r){let n=this.formatError(r,"track");this.logError(n)}}flushWaitingForConsentQueue(){this.waitingForConsentQueue.length!==0&&(this.log(`Flushing ${this.waitingForConsentQueue.length} events waiting for consent`),this.eventQueue.push(...this.waitingForConsentQueue),this.waitingForConsentQueue=[],this.flush().catch(e=>{let t=this.formatError(e,"flush waiting for consent queue");this.logError(t)}))}identify(e){this.log(`Identified user: ${e}`),this.globalUserId=e,this.persistentAnonymousUserId=null}setUserId(e){this.log(`Set global user ID: ${e}`),this.globalUserId=e,e?this.persistentAnonymousUserId=null:this.persistentAnonymousUserId||(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId))}getUserId(){return this.globalUserId}getEffectiveUserIdPublic(){return this.getEffectiveUserIdInternal()}login(e){try{if(this.isDestroyed){let t=new Error("Grain Analytics: Client has been destroyed"),i=this.formatError(t,"login (client destroyed)");this.logError(i);return}e.userId&&(this.log(`Login: Setting user ID to ${e.userId}`),this.globalUserId=e.userId,this.persistentAnonymousUserId=null),e.authToken&&(this.log("Login: Setting auth token"),this.config.authStrategy==="NONE"&&(this.config.authStrategy="JWT"),this.config.authProvider={getToken:()=>e.authToken}),e.authStrategy&&(this.log(`Login: Setting auth strategy to ${e.authStrategy}`),this.config.authStrategy=e.authStrategy),this.log(`Login successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`)}catch(t){let i=this.formatError(t,"login");this.logError(i)}}logout(){try{if(this.isDestroyed){let e=new Error("Grain Analytics: Client has been destroyed"),t=this.formatError(e,"logout (client destroyed)");this.logError(t);return}if(this.log("Logout: Clearing user session"),this.globalUserId=null,this.config.authStrategy="NONE",this.config.authProvider=void 0,!this.persistentAnonymousUserId&&(this.persistentAnonymousUserId=this.generateAnonymousUserId(),typeof window<"u"))try{let e=`grain_anonymous_user_id_${this.config.tenantId}`;localStorage.setItem(e,this.persistentAnonymousUserId)}catch(e){this.log("Failed to persist new anonymous user ID after logout:",e)}this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`)}catch(e){let t=this.formatError(e,"logout");this.logError(t)}}async setProperty(e,t){try{if(this.isDestroyed){let o=new Error("Grain Analytics: Client has been destroyed"),l=this.formatError(o,"setProperty (client destroyed)");this.logError(l);return}let i=t?.userId||this.getEffectiveUserIdInternal(),r=Object.keys(e);if(r.length>4){let o=new Error("Grain Analytics: Maximum 4 properties allowed per request"),l=this.formatError(o,"setProperty (validation)");this.logError(l);return}if(r.length===0){let o=new Error("Grain Analytics: At least one property is required"),l=this.formatError(o,"setProperty (validation)");this.logError(l);return}let n={};for(let[o,l]of Object.entries(e))l==null?n[o]="":typeof l=="string"?n[o]=l:n[o]=JSON.stringify(l);let a={userId:i,...n};await this.sendProperties(a)}catch(i){let r=this.formatError(i,"setProperty");this.logError(r)}}async sendProperties(e){let t;for(let i=0;i<=this.config.retryAttempts;i++)try{let r=await this.getAuthHeaders(),n=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/properties`,a=await fetch(n,{method:"POST",headers:r,body:JSON.stringify(e)});if(!a.ok){let o=`HTTP ${a.status}`;try{let c=await a.json();c?.message&&(o=c.message)}catch{let c=await a.text();c&&(o=c)}let l=new Error(`Failed to set properties: ${o}`);throw l.status=a.status,l}this.log(`Successfully set properties for user ${e.userId}`);return}catch(r){if(t=r,i===this.config.retryAttempts){let a=this.formatError(r,`sendProperties (attempt ${i+1}/${this.config.retryAttempts+1})`);this.logError(a);return}if(!this.isRetriableError(r)){let a=this.formatError(r,"sendProperties (non-retriable error)");this.logError(a);return}let n=this.config.retryDelay*Math.pow(2,i);this.log(`Retrying in ${n}ms after error:`,r),await this.delay(n)}}async trackLogin(e,t){try{return await this.track("login",e,t)}catch(i){let r=this.formatError(i,"trackLogin");this.logError(r)}}async trackSignup(e,t){try{return await this.track("signup",e,t)}catch(i){let r=this.formatError(i,"trackSignup");this.logError(r)}}async trackCheckout(e,t){try{return await this.track("checkout",e,t)}catch(i){let r=this.formatError(i,"trackCheckout");this.logError(r)}}async trackPageView(e,t){try{return await this.track("page_view",e,t)}catch(i){let r=this.formatError(i,"trackPageView");this.logError(r)}}async trackPurchase(e,t){try{return await this.track("purchase",e,t)}catch(i){let r=this.formatError(i,"trackPurchase");this.logError(r)}}async trackSearch(e,t){try{return await this.track("search",e,t)}catch(i){let r=this.formatError(i,"trackSearch");this.logError(r)}}async trackAddToCart(e,t){try{return await this.track("add_to_cart",e,t)}catch(i){let r=this.formatError(i,"trackAddToCart");this.logError(r)}}async trackRemoveFromCart(e,t){try{return await this.track("remove_from_cart",e,t)}catch(i){let r=this.formatError(i,"trackRemoveFromCart");this.logError(r)}}async flush(){try{if(this.eventQueue.length===0)return;let e=[...this.eventQueue];this.eventQueue=[];let t=this.chunkEvents(e,this.config.maxEventsPerRequest);for(let i of t)await this.sendEvents(i)}catch(e){let t=this.formatError(e,"flush");this.logError(t)}}initializeConfigCache(){if(!(!this.config.enableConfigCache||typeof window>"u"))try{let e=localStorage.getItem(this.config.configCacheKey);e&&(this.configCache=JSON.parse(e),this.log("Loaded configuration from cache:",this.configCache))}catch(e){this.log("Failed to load configuration cache:",e)}}saveConfigCache(e){if(!(!this.config.enableConfigCache||typeof window>"u"))try{localStorage.setItem(this.config.configCacheKey,JSON.stringify(e)),this.log("Saved configuration to cache:",e)}catch(t){this.log("Failed to save configuration cache:",t)}}getConfig(e){if(this.configCache?.configurations?.[e])return this.configCache.configurations[e];if(this.config.defaultConfigurations?.[e])return this.config.defaultConfigurations[e]}getAllConfigs(){let e={...this.config.defaultConfigurations};return this.configCache?.configurations&&Object.assign(e,this.configCache.configurations),e}async fetchConfig(e={}){try{if(this.isDestroyed){let l=new Error("Grain Analytics: Client has been destroyed"),c=this.formatError(l,"fetchConfig (client destroyed)");return this.logError(c),null}let t=e.userId||this.getEffectiveUserIdInternal(),i=e.immediateKeys||[],r=e.properties||{},n=e.currentUrl??(typeof window<"u"?window.location.href:void 0);if(n)try{let l=new URL(n);n=`${l.protocol}//${l.host}${l.pathname}`}catch{}let a={userId:t,immediateKeys:i,properties:r,currentUrl:n},o;for(let l=0;l<=this.config.retryAttempts;l++)try{let c=await this.getAuthHeaders(),d=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`,u=await fetch(d,{method:"POST",headers:c,body:JSON.stringify(a)});if(!u.ok){let y=`HTTP ${u.status}`;try{let b=await u.json();b?.message&&(y=b.message)}catch{let b=await u.text();b&&(y=b)}let B=new Error(`Failed to fetch configurations: ${y}`);throw B.status=u.status,B}let h=await u.json();return h.configurations&&this.updateConfigCache(h,t),this.log("Successfully fetched configurations"),h}catch(c){if(o=c,l===this.config.retryAttempts){let u=this.formatError(c,`fetchConfig (attempt ${l+1}/${this.config.retryAttempts+1})`);return this.logError(u),null}if(!this.isRetriableError(c)){let u=this.formatError(c,"fetchConfig (non-retriable error)");return this.logError(u),null}let d=this.config.retryDelay*Math.pow(2,l);this.log(`Retrying config fetch in ${d}ms after error:`,c),await this.delay(d)}return null}catch(t){let i=this.formatError(t,"fetchConfig");return this.logError(i),null}}async getConfigAsync(e,t={}){try{if(!t.forceRefresh&&this.configCache?.configurations?.[e])return this.configCache.configurations[e];if(!t.forceRefresh&&this.config.defaultConfigurations?.[e])return this.config.defaultConfigurations[e];let i=await this.fetchConfig(t);return i?i.configurations[e]:this.config.defaultConfigurations?.[e]}catch(i){let r=this.formatError(i,"getConfigAsync");return this.logError(r),this.config.defaultConfigurations?.[e]}}async getAllConfigsAsync(e={}){try{if(!e.forceRefresh&&this.configCache?.configurations)return{...this.config.defaultConfigurations,...this.configCache.configurations};let t=await this.fetchConfig(e);return t?{...this.config.defaultConfigurations,...t.configurations}:{...this.config.defaultConfigurations}}catch(t){let i=this.formatError(t,"getAllConfigsAsync");return this.logError(i),{...this.config.defaultConfigurations}}}updateConfigCache(e,t){let i={configurations:e.configurations,snapshotId:e.snapshotId,timestamp:e.timestamp,userId:t},r=this.configCache?.configurations||{};this.configCache=i,this.saveConfigCache(i),JSON.stringify(r)!==JSON.stringify(e.configurations)&&this.notifyConfigChangeListeners(e.configurations)}addConfigChangeListener(e){this.configChangeListeners.push(e)}removeConfigChangeListener(e){let t=this.configChangeListeners.indexOf(e);t>-1&&this.configChangeListeners.splice(t,1)}notifyConfigChangeListeners(e){this.configChangeListeners.forEach(t=>{try{t(e)}catch(i){console.error("[Grain Analytics] Config change listener error:",i)}})}startConfigRefreshTimer(){typeof window>"u"||(this.configRefreshTimer&&clearInterval(this.configRefreshTimer),this.configRefreshTimer=window.setInterval(()=>{this.isDestroyed||this.fetchConfig().catch(e=>{let t=this.formatError(e,"auto-config refresh");this.logError(t)})},this.config.configRefreshInterval))}stopConfigRefreshTimer(){this.configRefreshTimer&&(clearInterval(this.configRefreshTimer),this.configRefreshTimer=null)}async preloadConfig(e=[],t){try{let i=this.getEffectiveUserIdInternal();this.log(`Preloading config for user: ${i}`),await this.fetchConfig({immediateKeys:e,properties:t})&&this.startConfigRefreshTimer()}catch(i){let r=this.formatError(i,"preloadConfig");this.logError(r)}}chunkEvents(e,t){let i=[];for(let r=0;r<e.length;r+=t)i.push(e.slice(r,r+t));return i}grantConsent(e){try{this.consentManager.grantConsent(e);let t=this.consentManager.getIdMode();this.idManager.setMode(t),this.log("Consent granted, switched to permanent IDs",e),this.waitingForConsentQueue.length>0&&(this.log(`Processing ${this.waitingForConsentQueue.length} queued events`),this.eventQueue.push(...this.waitingForConsentQueue),this.waitingForConsentQueue=[],this.flush())}catch(t){let i=this.formatError(t,"grantConsent");this.logError(i)}}revokeConsent(e){try{this.consentManager.revokeConsent(e);let t=this.consentManager.getIdMode();this.idManager.setMode(t),this.log("Consent revoked, switched to cookieless mode",e),this.consentManager.hasConsent()||(this.eventQueue=[],this.waitingForConsentQueue=[])}catch(t){let i=this.formatError(t,"revokeConsent");this.logError(i)}}getConsentState(){return this.consentManager.getConsentState()}hasConsent(e){return this.consentManager.hasConsent(e)}onConsentChange(e){this.consentManager.addListener(e)}offConsentChange(e){this.consentManager.removeListener(e)}checkAndInitializeDebugMode(){if(!(typeof window>"u"))try{let e=new URLSearchParams(window.location.search),t=e.get("grain_debug")==="1",i=e.get("grain_session");if(!t||!i)return;this.log("Debug mode detected, verifying session:",i),this.verifyDebugSession(i,window.location.hostname).then(r=>{r?(this.log("Debug session verified, initializing debug agent"),this.isDebugMode=!0,this.initializeDebugAgent(i)):this.log("Debug session verification failed")}).catch(r=>{this.log("Failed to verify debug session:",r)})}catch(e){this.log("Error checking debug mode:",e)}}async verifyDebugSession(e,t){try{let i=`${this.config.apiUrl}/v1/tenant/${encodeURIComponent(this.config.tenantId)}/debug-sessions/verify`,r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,domain:t})});return r.ok?(await r.json()).valid===!0:!1}catch(i){return this.log("Debug session verification error:",i),!1}}initializeDebugAgent(e){if(!(typeof window>"u"))try{this.log("Loading debug agent module"),Promise.resolve().then(()=>(oe(),ae)).then(({DebugAgent:t})=>{try{this.debugAgent=new t(this,e,this.config.tenantId,this.config.apiUrl,{debug:this.config.debug}),this.log("Debug agent initialized")}catch(i){this.log("Failed to initialize debug agent:",i)}}).catch(t=>{this.log("Failed to load debug agent module:",t)})}catch(t){this.log("Error initializing debug agent:",t)}}destroy(){if(this.isDestroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.stopConfigRefreshTimer(),this.configChangeListeners=[],this.heartbeatManager&&(this.heartbeatManager.destroy(),this.heartbeatManager=null),this.pageTrackingManager&&(this.pageTrackingManager.destroy(),this.pageTrackingManager=null),this.activityDetector&&(this.activityDetector.destroy(),this.activityDetector=null),this.interactionTrackingManager&&(this.interactionTrackingManager.destroy(),this.interactionTrackingManager=null),this.sectionTrackingManager&&(this.sectionTrackingManager.destroy(),this.sectionTrackingManager=null),this.heatmapTrackingManager&&(this.heatmapTrackingManager.destroy(),this.heatmapTrackingManager=null),this.debugAgent&&(this.debugAgent.destroy(),this.debugAgent=null),this.eventQueue.length>0){let e=[...this.eventQueue];this.eventQueue=[];let t=this.chunkEvents(e,this.config.maxEventsPerRequest);if(t.length>0){this.sendEventsWithBeacon(t[0]).catch(()=>{});for(let i=1;i<t.length;i++)this.sendEventsWithBeacon(t[i]).catch(()=>{})}}}};function se(s){return new v(s)}var we=v;typeof window<"u"&&(window.Grain={GrainAnalytics:v,createGrainAnalytics:se});return he(ke);})();
|
|
532
|
+
`,document.body.appendChild(t),setTimeout(()=>{t.style.animation="slideDown 0.3s ease-in reverse",setTimeout(()=>{t.remove()},300)},2700)}async endDebug(){try{let t=`${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/debug-sessions/${this.sessionId}/end`;await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"}})}catch(t){this.log("Failed to end debug session:",t)}this.destroy();let e=new URL(window.location.href);e.searchParams.delete("grain_debug"),e.searchParams.delete("grain_session"),window.location.href=e.toString()}getXPathForElement(e){if(e.id)return`//*[@id="${e.id}"]`;let t=[],i=e;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let r=0,s=i;for(;s;)s.nodeType===Node.ELEMENT_NODE&&s.tagName===i.tagName&&r++,s=s.previousElementSibling;let a=i.tagName.toLowerCase(),o=r>1?`[${r}]`:"";t.unshift(`${a}${o}`),i=i.parentElement}return t.length?`/${t.join("/")}`:""}log(...e){this.config.debug&&console.log("[DebugAgent]",...e)}updateToolbarStats(){if(!this.toolbarElement)return;let e=this.toolbarElement.querySelector(".grain-stat:nth-child(1) .grain-stat-value"),t=this.toolbarElement.querySelector(".grain-stat:nth-child(2) .grain-stat-value");e&&(e.textContent=String(this.existingTrackers.length)),t&&(t.textContent=String(this.existingTrackers.filter(i=>i.isEnabled).length))}destroy(){this.isDestroyed||(this.log("Destroying debug agent"),this.isDestroyed=!0,this.disableInspectMode(),this.hideTrackerHighlights(),this.endDrag(),this.toolbarElement&&(this.toolbarElement.remove(),this.toolbarElement=null),this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.highlightElement&&(this.highlightElement.remove(),this.highlightElement=null))}}});var Ba={};z(Ba,{GrainAnalytics:()=>ee,categorizeReferrer:()=>V,createGrainAnalytics:()=>Nr,default:()=>Ha,getCountry:()=>qt,getCountryCodeFromTimezone:()=>be,getState:()=>Xt,parseUTMParameters:()=>re});var Vt=["necessary","analytics","functional"],pe="1.0.0",ge=class{constructor(e,t="COOKIELESS"){this.consentState=null;this.listeners=[];this.consentMode=t,this.storageKey=`grain_consent_${e}`,this.loadConsentState()}loadConsentState(){if(!(typeof window>"u"))try{let e=localStorage.getItem(this.storageKey);if(e){let t=JSON.parse(e);this.consentState={...t,timestamp:new Date(t.timestamp)}}else this.consentMode==="GDPR_OPT_OUT"&&(this.consentState={granted:!0,categories:Vt,timestamp:new Date,version:pe},this.saveConsentState())}catch{}}saveConsentState(){if(!(typeof window>"u"||!this.consentState))try{localStorage.setItem(this.storageKey,JSON.stringify(this.consentState))}catch{}}grantConsent(e){let t=e||Vt;this.consentState={granted:!0,categories:t,timestamp:new Date,version:pe},this.saveConsentState(),this.notifyListeners()}revokeConsent(e){this.consentState?e?this.consentState={...this.consentState,categories:this.consentState.categories.filter(t=>!e.includes(t)),granted:this.consentState.categories.length>0,timestamp:new Date}:this.consentState={granted:!1,categories:[],timestamp:new Date,version:pe}:this.consentState={granted:!1,categories:[],timestamp:new Date,version:pe},this.saveConsentState(),this.notifyListeners()}getConsentState(){return this.consentState?{...this.consentState}:null}hasConsent(e){if(this.consentMode==="COOKIELESS"||this.consentMode==="GDPR_STRICT"&&!this.consentState?.granted)return!1;if(this.consentMode==="GDPR_OPT_OUT"){if(!this.consentState)return!0;if(!this.consentState.granted)return!1}return e&&this.consentState?this.consentState.categories.includes(e):this.consentState?.granted??this.consentMode==="GDPR_OPT_OUT"}shouldUsePermanentId(){return this.hasConsent()}shouldStripQueryParams(){return this.consentMode==="COOKIELESS"?!0:this.consentMode==="GDPR_STRICT"?!this.hasConsent():this.consentMode!=="GDPR_OPT_OUT"}canTrack(){return!0}shouldWaitForConsent(){return this.consentMode==="GDPR_STRICT"&&!this.consentState?.granted}addListener(e){this.listeners.push(e)}removeListener(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){this.consentState&&this.listeners.forEach(e=>{try{e(this.consentState)}catch{}})}clearConsent(){if(!(typeof window>"u"))try{localStorage.removeItem(this.storageKey),this.consentState=null}catch{}}getConsentMode(){return this.consentMode}getIdMode(){return this.shouldUsePermanentId()?"permanent":"cookieless"}};function Kt(n,e,t){if(typeof document>"u")return;let i=[`${encodeURIComponent(n)}=${encodeURIComponent(e)}`];t?.maxAge!==void 0&&i.push(`max-age=${t.maxAge}`),t?.domain&&i.push(`domain=${t.domain}`),t?.path?i.push(`path=${t.path}`):i.push("path=/"),t?.sameSite&&i.push(`samesite=${t.sameSite}`),t?.secure&&i.push("secure"),document.cookie=i.join("; ")}function Wt(n){if(typeof document>"u")return null;let e=encodeURIComponent(n)+"=",t=document.cookie.split(";");for(let i=0;i<t.length;i++){let r=t[i];for(;r.charAt(0)===" ";)r=r.substring(1);if(r.indexOf(e)===0)return decodeURIComponent(r.substring(e.length))}return null}var me=class{constructor(){this.activityThreshold=3e4;this.listeners=[];this.isDestroyed=!1;this.activityEvents=["mousemove","mousedown","keydown","scroll","touchstart","click"];this.lastActivityTime=Date.now(),this.boundActivityHandler=this.debounce(this.handleActivity.bind(this),500),this.setupListeners()}setupListeners(){if(!(typeof window>"u"))for(let e of this.activityEvents)window.addEventListener(e,this.boundActivityHandler,{passive:!0})}handleActivity(){this.isDestroyed||(this.lastActivityTime=Date.now(),this.notifyListeners())}debounce(e,t){let i=null;return()=>{i!==null&&clearTimeout(i),i=window.setTimeout(()=>{e(),i=null},t)}}isActive(e){let t=e??this.activityThreshold;return Date.now()-this.lastActivityTime<t}getTimeSinceLastActivity(){return Date.now()-this.lastActivityTime}getLastActivityTime(){return this.lastActivityTime}setActivityThreshold(e){this.activityThreshold=e}addListener(e){this.listeners.push(e)}removeListener(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}destroy(){if(!this.isDestroyed){if(typeof window<"u")for(let e of this.activityEvents)window.removeEventListener(e,this.boundActivityHandler);this.listeners=[],this.isDestroyed=!0}}};var ye=class{constructor(e,t,i){this.heartbeatTimer=null;this.isDestroyed=!1;this.hasSentPageLoadHeartbeat=!1;this.tracker=e,this.activityDetector=t,this.config=i,this.lastHeartbeatTime=Date.now(),this.currentInterval=i.activeInterval,this.sendPageLoadHeartbeat(),this.scheduleNextHeartbeat()}sendPageLoadHeartbeat(){if(!(this.isDestroyed||this.hasSentPageLoadHeartbeat))if(typeof window<"u"&&document.readyState!=="complete"){let e=()=>{this.sendHeartbeat("page_load"),this.hasSentPageLoadHeartbeat=!0,window.removeEventListener("load",e)};window.addEventListener("load",e)}else this.sendHeartbeat("page_load"),this.hasSentPageLoadHeartbeat=!0}scheduleNextHeartbeat(){if(this.isDestroyed)return;this.heartbeatTimer!==null&&clearTimeout(this.heartbeatTimer);let e=this.activityDetector.isActive(6e4);this.currentInterval=e?this.config.activeInterval:this.config.inactiveInterval,this.heartbeatTimer=window.setTimeout(()=>{this.sendHeartbeat("periodic"),this.scheduleNextHeartbeat()},this.currentInterval),this.config.debug&&console.log(`[Heartbeat] Scheduled next heartbeat in ${this.currentInterval/1e3}s (${e?"active":"inactive"})`)}sendHeartbeat(e="periodic"){if(this.isDestroyed)return;let t=Date.now(),i=this.activityDetector.isActive(6e4),r=this.tracker.hasConsent("analytics"),s={heartbeat_type:e,status:i?"active":"inactive",timestamp:t};if(r){let a=this.tracker.getCurrentPage();a&&(s.page=a),s.session_id=this.tracker.getSessionId(),e==="periodic"&&(s.duration=t-this.lastHeartbeatTime,s.event_count=this.tracker.getEventCountSinceLastHeartbeat(),this.tracker.resetEventCountSinceLastHeartbeat())}this.tracker.trackSystemEvent("_grain_heartbeat",s),this.lastHeartbeatTime=t}destroy(){this.isDestroyed||(this.heartbeatTimer!==null&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isDestroyed=!0)}};var Gr=["gclid","msclkid","fbclid","ttclid","li_fat_id","twclid","ScCid"],zr=["facebook.com","twitter.com","x.com","linkedin.com","instagram.com","pinterest.com","reddit.com","tiktok.com","youtube.com","snapchat.com","t.co","fb.me","lnkd.in"],Vr=["google.","bing.com","yahoo.com","duckduckgo.com","baidu.com","yandex.com","ecosia.org","ask.com"],Kr=["mail.google.com","outlook.live.com","mail.yahoo.com","mail.aol.com"];function et(n){try{return new URL(n).hostname.toLowerCase()}catch{return""}}function jt(n){try{let e=new URL(n);return Gr.some(t=>e.searchParams.has(t))}catch{return!1}}function V(n,e=""){if(!n||n.trim()==="")return"direct";let t=et(n);if(e){let i=et(e);if(t===i)return"direct"}return jt(n)||jt(e)?"paid":Kr.some(i=>t.includes(i))?"email":zr.some(i=>t.includes(i))?"social":Vr.some(i=>t.includes(i))?"organic":"referral"}function re(n){try{let e=new URL(n),t={},i=e.searchParams.get("utm_source"),r=e.searchParams.get("utm_medium"),s=e.searchParams.get("utm_campaign"),a=e.searchParams.get("utm_term"),o=e.searchParams.get("utm_content");return i&&(t.utm_source=i),r&&(t.utm_medium=r),s&&(t.utm_campaign=s),a&&(t.utm_term=a),o&&(t.utm_content=o),t}catch{return{}}}function tt(n){if(typeof window>"u"||typeof localStorage>"u")return null;try{let e=`_grain_first_touch_${n}`,t=localStorage.getItem(e);if(t)return JSON.parse(t)}catch(e){console.warn("[Grain Attribution] Failed to retrieve first-touch attribution:",e)}return null}function Wr(n,e){if(!(typeof window>"u"||typeof localStorage>"u"))try{let t=`_grain_first_touch_${n}`;localStorage.setItem(t,JSON.stringify(e))}catch(t){console.warn("[Grain Attribution] Failed to store first-touch attribution:",t)}}function ve(n,e,t,i){let r=tt(n);if(r)return r;let s=V(e,t),a=et(e),o={source:i.utm_source||a||"direct",medium:i.utm_medium||s,campaign:i.utm_campaign||"none",referrer:e||"direct",referrer_category:s,timestamp:Date.now()};return Wr(n,o),o}var Qt=null;function K(){return Qt}function Yt(n){Qt=n}var jr={AD:"Andorra",AE:"United Arab Emirates",AF:"Afghanistan",AG:"Antigua and Barbuda",AI:"Anguilla",AL:"Albania",AM:"Armenia",AO:"Angola",AQ:"Antarctica",AR:"Argentina",AS:"American Samoa",AT:"Austria",AU:"Australia",AW:"Aruba",AX:"\xC5land Islands",AZ:"Azerbaijan",BA:"Bosnia and Herzegovina",BB:"Barbados",BD:"Bangladesh",BE:"Belgium",BF:"Burkina Faso",BG:"Bulgaria",BH:"Bahrain",BI:"Burundi",BJ:"Benin",BL:"Saint Barth\xE9lemy",BM:"Bermuda",BN:"Brunei",BO:"Bolivia",BQ:"Caribbean Netherlands",BR:"Brazil",BS:"Bahamas",BT:"Bhutan",BV:"Bouvet Island",BW:"Botswana",BY:"Belarus",BZ:"Belize",CA:"Canada",CC:"Cocos Islands",CD:"Democratic Republic of the Congo",CF:"Central African Republic",CG:"Republic of the Congo",CH:"Switzerland",CI:"Ivory Coast",CK:"Cook Islands",CL:"Chile",CM:"Cameroon",CN:"China",CO:"Colombia",CR:"Costa Rica",CU:"Cuba",CV:"Cabo Verde",CW:"Cura\xE7ao",CX:"Christmas Island",CY:"Cyprus",CZ:"Czechia",DE:"Germany",DJ:"Djibouti",DK:"Denmark",DM:"Dominica",DO:"Dominican Republic",DZ:"Algeria",EC:"Ecuador",EE:"Estonia",EG:"Egypt",EH:"Western Sahara",ER:"Eritrea",ES:"Spain",ET:"Ethiopia",FI:"Finland",FJ:"Fiji",FK:"Falkland Islands",FM:"Micronesia",FO:"Faroe Islands",FR:"France",GA:"Gabon",GB:"United Kingdom",GD:"Grenada",GE:"Georgia",GF:"French Guiana",GG:"Guernsey",GH:"Ghana",GI:"Gibraltar",GL:"Greenland",GM:"Gambia",GN:"Guinea",GP:"Guadeloupe",GQ:"Equatorial Guinea",GR:"Greece",GS:"South Georgia and the South Sandwich Islands",GT:"Guatemala",GU:"Guam",GW:"Guinea-Bissau",GY:"Guyana",HK:"Hong Kong",HM:"Heard Island and McDonald Islands",HN:"Honduras",HR:"Croatia",HT:"Haiti",HU:"Hungary",ID:"Indonesia",IE:"Ireland",IL:"Israel",IM:"Isle of Man",IN:"India",IO:"British Indian Ocean Territory",IQ:"Iraq",IR:"Iran",IS:"Iceland",IT:"Italy",JE:"Jersey",JM:"Jamaica",JO:"Jordan",JP:"Japan",KE:"Kenya",KG:"Kyrgyzstan",KH:"Cambodia",KI:"Kiribati",KM:"Comoros",KN:"Saint Kitts and Nevis",KP:"North Korea",KR:"South Korea",KW:"Kuwait",KY:"Cayman Islands",KZ:"Kazakhstan",LA:"Laos",LB:"Lebanon",LC:"Saint Lucia",LI:"Liechtenstein",LK:"Sri Lanka",LR:"Liberia",LS:"Lesotho",LT:"Lithuania",LU:"Luxembourg",LV:"Latvia",LY:"Libya",MA:"Morocco",MC:"Monaco",MD:"Moldova",ME:"Montenegro",MF:"Saint Martin",MG:"Madagascar",MH:"Marshall Islands",MK:"North Macedonia",ML:"Mali",MM:"Myanmar",MN:"Mongolia",MO:"Macao",MP:"Northern Mariana Islands",MQ:"Martinique",MR:"Mauritania",MS:"Montserrat",MT:"Malta",MU:"Mauritius",MV:"Maldives",MW:"Malawi",MX:"Mexico",MY:"Malaysia",MZ:"Mozambique",NA:"Namibia",NC:"New Caledonia",NE:"Niger",NF:"Norfolk Island",NG:"Nigeria",NI:"Nicaragua",NL:"Netherlands",NO:"Norway",NP:"Nepal",NR:"Nauru",NU:"Niue",NZ:"New Zealand",OM:"Oman",PA:"Panama",PE:"Peru",PF:"French Polynesia",PG:"Papua New Guinea",PH:"Philippines",PK:"Pakistan",PL:"Poland",PM:"Saint Pierre and Miquelon",PN:"Pitcairn",PR:"Puerto Rico",PS:"Palestine",PT:"Portugal",PW:"Palau",PY:"Paraguay",QA:"Qatar",RE:"R\xE9union",RO:"Romania",RS:"Serbia",RU:"Russia",RW:"Rwanda",SA:"Saudi Arabia",SB:"Solomon Islands",SC:"Seychelles",SD:"Sudan",SE:"Sweden",SG:"Singapore",SH:"Saint Helena, Ascension and Tristan da Cunha",SI:"Slovenia",SJ:"Svalbard and Jan Mayen",SK:"Slovakia",SL:"Sierra Leone",SM:"San Marino",SN:"Senegal",SO:"Somalia",SR:"Suriname",SS:"South Sudan",ST:"Sao Tome and Principe",SV:"El Salvador",SX:"Sint Maarten",SY:"Syria",SZ:"Eswatini",TC:"Turks and Caicos Islands",TD:"Chad",TF:"French Southern Territories",TG:"Togo",TH:"Thailand",TJ:"Tajikistan",TK:"Tokelau",TL:"Timor-Leste",TM:"Turkmenistan",TN:"Tunisia",TO:"Tonga",TR:"Turkey",TT:"Trinidad and Tobago",TV:"Tuvalu",TW:"Taiwan",TZ:"Tanzania",UA:"Ukraine",UG:"Uganda",UM:"United States Minor Outlying Islands",US:"United States of America",UY:"Uruguay",UZ:"Uzbekistan",VA:"Holy See",VC:"Saint Vincent and the Grenadines",VE:"Venezuela",VG:"Virgin Islands (UK)",VI:"Virgin Islands (US)",VN:"Vietnam",VU:"Vanuatu",WF:"Wallis and Futuna",WS:"Samoa",YE:"Yemen",YT:"Mayotte",ZA:"South Africa",ZM:"Zambia",ZW:"Zimbabwe"},Jt={"Africa/Abidjan":{u:0,c:["CI","BF","GH","GM","GN","ML","MR","SH","SL","SN","TG"]},"Africa/Accra":{a:"Africa/Abidjan",c:["GH"],r:1},"Africa/Addis_Ababa":{a:"Africa/Nairobi",c:["ET"],r:1},"Africa/Algiers":{u:60,c:["DZ"]},"Africa/Asmara":{a:"Africa/Nairobi",c:["ER"],r:1},"Africa/Asmera":{a:"Africa/Nairobi",c:["ER"],r:1},"Africa/Bamako":{a:"Africa/Abidjan",c:["ML"],r:1},"Africa/Bangui":{a:"Africa/Lagos",c:["CF"],r:1},"Africa/Banjul":{a:"Africa/Abidjan",c:["GM"],r:1},"Africa/Bissau":{u:0,c:["GW"]},"Africa/Blantyre":{a:"Africa/Maputo",c:["MW"],r:1},"Africa/Brazzaville":{a:"Africa/Lagos",c:["CG"],r:1},"Africa/Bujumbura":{a:"Africa/Maputo",c:["BI"],r:1},"Africa/Cairo":{u:120,c:["EG"]},"Africa/Casablanca":{u:60,d:0,c:["MA"]},"Africa/Ceuta":{u:60,d:120,c:["ES"]},"Africa/Conakry":{a:"Africa/Abidjan",c:["GN"],r:1},"Africa/Dakar":{a:"Africa/Abidjan",c:["SN"],r:1},"Africa/Dar_es_Salaam":{a:"Africa/Nairobi",c:["TZ"],r:1},"Africa/Djibouti":{a:"Africa/Nairobi",c:["DJ"],r:1},"Africa/Douala":{a:"Africa/Lagos",c:["CM"],r:1},"Africa/El_Aaiun":{u:60,d:0,c:["EH"]},"Africa/Freetown":{a:"Africa/Abidjan",c:["SL"],r:1},"Africa/Gaborone":{a:"Africa/Maputo",c:["BW"],r:1},"Africa/Harare":{a:"Africa/Maputo",c:["ZW"],r:1},"Africa/Johannesburg":{u:120,c:["ZA","LS","SZ"]},"Africa/Juba":{u:120,c:["SS"]},"Africa/Kampala":{a:"Africa/Nairobi",c:["UG"],r:1},"Africa/Khartoum":{u:120,c:["SD"]},"Africa/Kigali":{a:"Africa/Maputo",c:["RW"],r:1},"Africa/Kinshasa":{a:"Africa/Lagos",c:["CD"],r:1},"Africa/Lagos":{u:60,c:["NG","AO","BJ","CD","CF","CG","CM","GA","GQ","NE"]},"Africa/Libreville":{a:"Africa/Lagos",c:["GA"],r:1},"Africa/Lome":{a:"Africa/Abidjan",c:["TG"],r:1},"Africa/Luanda":{a:"Africa/Lagos",c:["AO"],r:1},"Africa/Lubumbashi":{a:"Africa/Maputo",c:["CD"],r:1},"Africa/Lusaka":{a:"Africa/Maputo",c:["ZM"],r:1},"Africa/Malabo":{a:"Africa/Lagos",c:["GQ"],r:1},"Africa/Maputo":{u:120,c:["MZ","BI","BW","CD","MW","RW","ZM","ZW"]},"Africa/Maseru":{a:"Africa/Johannesburg",c:["LS"],r:1},"Africa/Mbabane":{a:"Africa/Johannesburg",c:["SZ"],r:1},"Africa/Mogadishu":{a:"Africa/Nairobi",c:["SO"],r:1},"Africa/Monrovia":{u:0,c:["LR"]},"Africa/Nairobi":{u:180,c:["KE","DJ","ER","ET","KM","MG","SO","TZ","UG","YT"]},"Africa/Ndjamena":{u:60,c:["TD"]},"Africa/Niamey":{a:"Africa/Lagos",c:["NE"],r:1},"Africa/Nouakchott":{a:"Africa/Abidjan",c:["MR"],r:1},"Africa/Ouagadougou":{a:"Africa/Abidjan",c:["BF"],r:1},"Africa/Porto-Novo":{a:"Africa/Lagos",c:["BJ"],r:1},"Africa/Sao_Tome":{u:0,c:["ST"]},"Africa/Timbuktu":{a:"Africa/Abidjan",c:["ML"],r:1},"Africa/Tripoli":{u:120,c:["LY"]},"Africa/Tunis":{u:60,c:["TN"]},"Africa/Windhoek":{u:120,c:["NA"]},"America/Adak":{u:-600,d:-540,c:["US"]},"America/Anchorage":{u:-540,d:-480,c:["US"]},"America/Anguilla":{a:"America/Puerto_Rico",c:["AI"],r:1},"America/Antigua":{a:"America/Puerto_Rico",c:["AG"],r:1},"America/Araguaina":{u:-180,c:["BR"]},"America/Argentina/Buenos_Aires":{u:-180,c:["AR"]},"America/Argentina/Catamarca":{u:-180,c:["AR"]},"America/Argentina/ComodRivadavia":{a:"America/Argentina/Catamarca",r:1},"America/Argentina/Cordoba":{u:-180,c:["AR"]},"America/Argentina/Jujuy":{u:-180,c:["AR"]},"America/Argentina/La_Rioja":{u:-180,c:["AR"]},"America/Argentina/Mendoza":{u:-180,c:["AR"]},"America/Argentina/Rio_Gallegos":{u:-180,c:["AR"]},"America/Argentina/Salta":{u:-180,c:["AR"]},"America/Argentina/San_Juan":{u:-180,c:["AR"]},"America/Argentina/San_Luis":{u:-180,c:["AR"]},"America/Argentina/Tucuman":{u:-180,c:["AR"]},"America/Argentina/Ushuaia":{u:-180,c:["AR"]},"America/Aruba":{a:"America/Puerto_Rico",c:["AW"],r:1},"America/Asuncion":{u:-240,d:-180,c:["PY"]},"America/Atikokan":{a:"America/Panama",c:["CA"],r:1},"America/Atka":{a:"America/Adak",r:1},"America/Bahia":{u:-180,c:["BR"]},"America/Bahia_Banderas":{u:-360,d:-300,c:["MX"]},"America/Barbados":{u:-240,c:["BB"]},"America/Belem":{u:-180,c:["BR"]},"America/Belize":{u:-360,c:["BZ"]},"America/Blanc-Sablon":{a:"America/Puerto_Rico",c:["CA"],r:1},"America/Boa_Vista":{u:-240,c:["BR"]},"America/Bogota":{u:-300,c:["CO"]},"America/Boise":{u:-420,d:-360,c:["US"]},"America/Buenos_Aires":{a:"America/Argentina/Buenos_Aires",r:1},"America/Cambridge_Bay":{u:-420,d:-360,c:["CA"]},"America/Campo_Grande":{u:-240,c:["BR"]},"America/Cancun":{u:-300,c:["MX"]},"America/Caracas":{u:-240,c:["VE"]},"America/Catamarca":{a:"America/Argentina/Catamarca",r:1},"America/Cayenne":{u:-180,c:["GF"]},"America/Cayman":{a:"America/Panama",c:["KY"],r:1},"America/Chicago":{u:-360,d:-300,c:["US"]},"America/Chihuahua":{u:-420,d:-360,c:["MX"]},"America/Coral_Harbour":{a:"America/Panama",c:["CA"],r:1},"America/Cordoba":{a:"America/Argentina/Cordoba",r:1},"America/Costa_Rica":{u:-360,c:["CR"]},"America/Creston":{a:"America/Phoenix",c:["CA"],r:1},"America/Cuiaba":{u:-240,c:["BR"]},"America/Curacao":{a:"America/Puerto_Rico",c:["CW"],r:1},"America/Danmarkshavn":{u:0,c:["GL"]},"America/Dawson":{u:-420,c:["CA"]},"America/Dawson_Creek":{u:-420,c:["CA"]},"America/Denver":{u:-420,d:-360,c:["US"]},"America/Detroit":{u:-300,d:-240,c:["US"]},"America/Dominica":{a:"America/Puerto_Rico",c:["DM"],r:1},"America/Edmonton":{u:-420,d:-360,c:["CA"]},"America/Eirunepe":{u:-300,c:["BR"]},"America/El_Salvador":{u:-360,c:["SV"]},"America/Ensenada":{a:"America/Tijuana",r:1},"America/Fort_Nelson":{u:-420,c:["CA"]},"America/Fort_Wayne":{a:"America/Indiana/Indianapolis",r:1},"America/Fortaleza":{u:-180,c:["BR"]},"America/Glace_Bay":{u:-240,d:-180,c:["CA"]},"America/Godthab":{a:"America/Nuuk",r:1},"America/Goose_Bay":{u:-240,d:-180,c:["CA"]},"America/Grand_Turk":{u:-300,d:-240,c:["TC"]},"America/Grenada":{a:"America/Puerto_Rico",c:["GD"],r:1},"America/Guadeloupe":{a:"America/Puerto_Rico",c:["GP"],r:1},"America/Guatemala":{u:-360,c:["GT"]},"America/Guayaquil":{u:-300,c:["EC"]},"America/Guyana":{u:-240,c:["GY"]},"America/Halifax":{u:-240,d:-180,c:["CA"]},"America/Havana":{u:-300,d:-240,c:["CU"]},"America/Hermosillo":{u:-420,c:["MX"]},"America/Indiana/Indianapolis":{u:-300,d:-240,c:["US"]},"America/Indiana/Knox":{u:-360,d:-300,c:["US"]},"America/Indiana/Marengo":{u:-300,d:-240,c:["US"]},"America/Indiana/Petersburg":{u:-300,d:-240,c:["US"]},"America/Indiana/Tell_City":{u:-360,d:-300,c:["US"]},"America/Indiana/Vevay":{u:-300,d:-240,c:["US"]},"America/Indiana/Vincennes":{u:-300,d:-240,c:["US"]},"America/Indiana/Winamac":{u:-300,d:-240,c:["US"]},"America/Indianapolis":{a:"America/Indiana/Indianapolis",r:1},"America/Inuvik":{u:-420,d:-360,c:["CA"]},"America/Iqaluit":{u:-300,d:-240,c:["CA"]},"America/Jamaica":{u:-300,c:["JM"]},"America/Jujuy":{a:"America/Argentina/Jujuy",r:1},"America/Juneau":{u:-540,d:-480,c:["US"]},"America/Kentucky/Louisville":{u:-300,d:-240,c:["US"]},"America/Kentucky/Monticello":{u:-300,d:-240,c:["US"]},"America/Knox_IN":{a:"America/Indiana/Knox",r:1},"America/Kralendijk":{a:"America/Puerto_Rico",c:["BQ"],r:1},"America/La_Paz":{u:-240,c:["BO"]},"America/Lima":{u:-300,c:["PE"]},"America/Los_Angeles":{u:-480,d:-420,c:["US"]},"America/Louisville":{a:"America/Kentucky/Louisville",r:1},"America/Lower_Princes":{a:"America/Puerto_Rico",c:["SX"],r:1},"America/Maceio":{u:-180,c:["BR"]},"America/Managua":{u:-360,c:["NI"]},"America/Manaus":{u:-240,c:["BR"]},"America/Marigot":{a:"America/Puerto_Rico",c:["MF"],r:1},"America/Martinique":{u:-240,c:["MQ"]},"America/Matamoros":{u:-360,d:-300,c:["MX"]},"America/Mazatlan":{u:-420,d:-360,c:["MX"]},"America/Mendoza":{a:"America/Argentina/Mendoza",r:1},"America/Menominee":{u:-360,d:-300,c:["US"]},"America/Merida":{u:-360,d:-300,c:["MX"]},"America/Metlakatla":{u:-540,d:-480,c:["US"]},"America/Mexico_City":{u:-360,d:-300,c:["MX"]},"America/Miquelon":{u:-180,d:-120,c:["PM"]},"America/Moncton":{u:-240,d:-180,c:["CA"]},"America/Monterrey":{u:-360,d:-300,c:["MX"]},"America/Montevideo":{u:-180,c:["UY"]},"America/Montreal":{a:"America/Toronto",c:["CA"],r:1},"America/Montserrat":{a:"America/Puerto_Rico",c:["MS"],r:1},"America/Nassau":{a:"America/Toronto",c:["BS"],r:1},"America/New_York":{u:-300,d:-240,c:["US"]},"America/Nipigon":{u:-300,d:-240,c:["CA"]},"America/Nome":{u:-540,d:-480,c:["US"]},"America/Noronha":{u:-120,c:["BR"]},"America/North_Dakota/Beulah":{u:-360,d:-300,c:["US"]},"America/North_Dakota/Center":{u:-360,d:-300,c:["US"]},"America/North_Dakota/New_Salem":{u:-360,d:-300,c:["US"]},"America/Nuuk":{u:-180,d:-120,c:["GL"]},"America/Ojinaga":{u:-420,d:-360,c:["MX"]},"America/Panama":{u:-300,c:["PA","CA","KY"]},"America/Pangnirtung":{u:-300,d:-240,c:["CA"]},"America/Paramaribo":{u:-180,c:["SR"]},"America/Phoenix":{u:-420,c:["US","CA"]},"America/Port-au-Prince":{u:-300,d:-240,c:["HT"]},"America/Port_of_Spain":{a:"America/Puerto_Rico",c:["TT"],r:1},"America/Porto_Acre":{a:"America/Rio_Branco",r:1},"America/Porto_Velho":{u:-240,c:["BR"]},"America/Puerto_Rico":{u:-240,c:["PR","AG","CA","AI","AW","BL","BQ","CW","DM","GD","GP","KN","LC","MF","MS","SX","TT","VC","VG","VI"]},"America/Punta_Arenas":{u:-180,c:["CL"]},"America/Rainy_River":{u:-360,d:-300,c:["CA"]},"America/Rankin_Inlet":{u:-360,d:-300,c:["CA"]},"America/Recife":{u:-180,c:["BR"]},"America/Regina":{u:-360,c:["CA"]},"America/Resolute":{u:-360,d:-300,c:["CA"]},"America/Rio_Branco":{u:-300,c:["BR"]},"America/Rosario":{a:"America/Argentina/Cordoba",r:1},"America/Santa_Isabel":{a:"America/Tijuana",r:1},"America/Santarem":{u:-180,c:["BR"]},"America/Santiago":{u:-240,d:-180,c:["CL"]},"America/Santo_Domingo":{u:-240,c:["DO"]},"America/Sao_Paulo":{u:-180,c:["BR"]},"America/Scoresbysund":{u:-60,d:0,c:["GL"]},"America/Shiprock":{a:"America/Denver",r:1},"America/Sitka":{u:-540,d:-480,c:["US"]},"America/St_Barthelemy":{a:"America/Puerto_Rico",c:["BL"],r:1},"America/St_Johns":{u:-150,d:-90,c:["CA"]},"America/St_Kitts":{a:"America/Puerto_Rico",c:["KN"],r:1},"America/St_Lucia":{a:"America/Puerto_Rico",c:["LC"],r:1},"America/St_Thomas":{a:"America/Puerto_Rico",c:["VI"],r:1},"America/St_Vincent":{a:"America/Puerto_Rico",c:["VC"],r:1},"America/Swift_Current":{u:-360,c:["CA"]},"America/Tegucigalpa":{u:-360,c:["HN"]},"America/Thule":{u:-240,d:-180,c:["GL"]},"America/Thunder_Bay":{u:-300,d:-240,c:["CA"]},"America/Tijuana":{u:-480,d:-420,c:["MX"]},"America/Toronto":{u:-300,d:-240,c:["CA","BS"]},"America/Tortola":{a:"America/Puerto_Rico",c:["VG"],r:1},"America/Vancouver":{u:-480,d:-420,c:["CA"]},"America/Virgin":{a:"America/Puerto_Rico",c:["VI"],r:1},"America/Whitehorse":{u:-420,c:["CA"]},"America/Winnipeg":{u:-360,d:-300,c:["CA"]},"America/Yakutat":{u:-540,d:-480,c:["US"]},"America/Yellowknife":{u:-420,d:-360,c:["CA"]},"Antarctica/Casey":{u:660,c:["AQ"]},"Antarctica/Davis":{u:420,c:["AQ"]},"Antarctica/DumontDUrville":{a:"Pacific/Port_Moresby",c:["AQ"],r:1},"Antarctica/Macquarie":{u:600,d:660,c:["AU"]},"Antarctica/Mawson":{u:300,c:["AQ"]},"Antarctica/McMurdo":{a:"Pacific/Auckland",c:["AQ"],r:1},"Antarctica/Palmer":{u:-180,c:["AQ"]},"Antarctica/Rothera":{u:-180,c:["AQ"]},"Antarctica/South_Pole":{a:"Pacific/Auckland",c:["AQ"],r:1},"Antarctica/Syowa":{a:"Asia/Riyadh",c:["AQ"],r:1},"Antarctica/Troll":{u:0,d:120,c:["AQ"]},"Antarctica/Vostok":{u:360,c:["AQ"]},"Arctic/Longyearbyen":{a:"Europe/Oslo",c:["SJ"],r:1},"Asia/Aden":{a:"Asia/Riyadh",c:["YE"],r:1},"Asia/Almaty":{u:360,c:["KZ"]},"Asia/Amman":{u:120,d:180,c:["JO"]},"Asia/Anadyr":{u:720,c:["RU"]},"Asia/Aqtau":{u:300,c:["KZ"]},"Asia/Aqtobe":{u:300,c:["KZ"]},"Asia/Ashgabat":{u:300,c:["TM"]},"Asia/Ashkhabad":{a:"Asia/Ashgabat",r:1},"Asia/Atyrau":{u:300,c:["KZ"]},"Asia/Baghdad":{u:180,c:["IQ"]},"Asia/Bahrain":{a:"Asia/Qatar",c:["BH"],r:1},"Asia/Baku":{u:240,c:["AZ"]},"Asia/Bangkok":{u:420,c:["TH","KH","LA","VN"]},"Asia/Barnaul":{u:420,c:["RU"]},"Asia/Beirut":{u:120,d:180,c:["LB"]},"Asia/Bishkek":{u:360,c:["KG"]},"Asia/Brunei":{u:480,c:["BN"]},"Asia/Calcutta":{a:"Asia/Kolkata",r:1},"Asia/Chita":{u:540,c:["RU"]},"Asia/Choibalsan":{u:480,c:["MN"]},"Asia/Chongqing":{a:"Asia/Shanghai",r:1},"Asia/Chungking":{a:"Asia/Shanghai",r:1},"Asia/Colombo":{u:330,c:["LK"]},"Asia/Dacca":{a:"Asia/Dhaka",r:1},"Asia/Damascus":{u:120,d:180,c:["SY"]},"Asia/Dhaka":{u:360,c:["BD"]},"Asia/Dili":{u:540,c:["TL"]},"Asia/Dubai":{u:240,c:["AE","OM"]},"Asia/Dushanbe":{u:300,c:["TJ"]},"Asia/Famagusta":{u:120,d:180,c:["CY"]},"Asia/Gaza":{u:120,d:180,c:["PS"]},"Asia/Harbin":{a:"Asia/Shanghai",r:1},"Asia/Hebron":{u:120,d:180,c:["PS"]},"Asia/Ho_Chi_Minh":{u:420,c:["VN"]},"Asia/Hong_Kong":{u:480,c:["HK"]},"Asia/Hovd":{u:420,c:["MN"]},"Asia/Irkutsk":{u:480,c:["RU"]},"Asia/Istanbul":{a:"Europe/Istanbul",r:1},"Asia/Jakarta":{u:420,c:["ID"]},"Asia/Jayapura":{u:540,c:["ID"]},"Asia/Jerusalem":{u:120,d:180,c:["IL"]},"Asia/Kabul":{u:270,c:["AF"]},"Asia/Kamchatka":{u:720,c:["RU"]},"Asia/Karachi":{u:300,c:["PK"]},"Asia/Kashgar":{a:"Asia/Urumqi",r:1},"Asia/Kathmandu":{u:345,c:["NP"]},"Asia/Katmandu":{a:"Asia/Kathmandu",r:1},"Asia/Khandyga":{u:540,c:["RU"]},"Asia/Kolkata":{u:330,c:["IN"]},"Asia/Krasnoyarsk":{u:420,c:["RU"]},"Asia/Kuala_Lumpur":{u:480,c:["MY"]},"Asia/Kuching":{u:480,c:["MY"]},"Asia/Kuwait":{a:"Asia/Riyadh",c:["KW"],r:1},"Asia/Macao":{a:"Asia/Macau",r:1},"Asia/Macau":{u:480,c:["MO"]},"Asia/Magadan":{u:660,c:["RU"]},"Asia/Makassar":{u:480,c:["ID"]},"Asia/Manila":{u:480,c:["PH"]},"Asia/Muscat":{a:"Asia/Dubai",c:["OM"],r:1},"Asia/Nicosia":{u:120,d:180,c:["CY"]},"Asia/Novokuznetsk":{u:420,c:["RU"]},"Asia/Novosibirsk":{u:420,c:["RU"]},"Asia/Omsk":{u:360,c:["RU"]},"Asia/Oral":{u:300,c:["KZ"]},"Asia/Phnom_Penh":{a:"Asia/Bangkok",c:["KH"],r:1},"Asia/Pontianak":{u:420,c:["ID"]},"Asia/Pyongyang":{u:540,c:["KP"]},"Asia/Qatar":{u:180,c:["QA","BH"]},"Asia/Qostanay":{u:360,c:["KZ"]},"Asia/Qyzylorda":{u:300,c:["KZ"]},"Asia/Rangoon":{a:"Asia/Yangon",r:1},"Asia/Riyadh":{u:180,c:["SA","AQ","KW","YE"]},"Asia/Saigon":{a:"Asia/Ho_Chi_Minh",r:1},"Asia/Sakhalin":{u:660,c:["RU"]},"Asia/Samarkand":{u:300,c:["UZ"]},"Asia/Seoul":{u:540,c:["KR"]},"Asia/Shanghai":{u:480,c:["CN"]},"Asia/Singapore":{u:480,c:["SG","MY"]},"Asia/Srednekolymsk":{u:660,c:["RU"]},"Asia/Taipei":{u:480,c:["TW"]},"Asia/Tashkent":{u:300,c:["UZ"]},"Asia/Tbilisi":{u:240,c:["GE"]},"Asia/Tehran":{u:210,d:270,c:["IR"]},"Asia/Tel_Aviv":{a:"Asia/Jerusalem",r:1},"Asia/Thimbu":{a:"Asia/Thimphu",r:1},"Asia/Thimphu":{u:360,c:["BT"]},"Asia/Tokyo":{u:540,c:["JP"]},"Asia/Tomsk":{u:420,c:["RU"]},"Asia/Ujung_Pandang":{a:"Asia/Makassar",r:1},"Asia/Ulaanbaatar":{u:480,c:["MN"]},"Asia/Ulan_Bator":{a:"Asia/Ulaanbaatar",r:1},"Asia/Urumqi":{u:360,c:["CN"]},"Asia/Ust-Nera":{u:600,c:["RU"]},"Asia/Vientiane":{a:"Asia/Bangkok",c:["LA"],r:1},"Asia/Vladivostok":{u:600,c:["RU"]},"Asia/Yakutsk":{u:540,c:["RU"]},"Asia/Yangon":{u:390,c:["MM"]},"Asia/Yekaterinburg":{u:300,c:["RU"]},"Asia/Yerevan":{u:240,c:["AM"]},"Atlantic/Azores":{u:-60,d:0,c:["PT"]},"Atlantic/Bermuda":{u:-240,d:-180,c:["BM"]},"Atlantic/Canary":{u:0,d:60,c:["ES"]},"Atlantic/Cape_Verde":{u:-60,c:["CV"]},"Atlantic/Faeroe":{a:"Atlantic/Faroe",r:1},"Atlantic/Faroe":{u:0,d:60,c:["FO"]},"Atlantic/Jan_Mayen":{a:"Europe/Oslo",c:["SJ"],r:1},"Atlantic/Madeira":{u:0,d:60,c:["PT"]},"Atlantic/Reykjavik":{u:0,c:["IS"]},"Atlantic/South_Georgia":{u:-120,c:["GS"]},"Atlantic/St_Helena":{a:"Africa/Abidjan",c:["SH"],r:1},"Atlantic/Stanley":{u:-180,c:["FK"]},"Australia/ACT":{a:"Australia/Sydney",r:1},"Australia/Adelaide":{u:570,d:630,c:["AU"]},"Australia/Brisbane":{u:600,c:["AU"]},"Australia/Broken_Hill":{u:570,d:630,c:["AU"]},"Australia/Canberra":{a:"Australia/Sydney",r:1},"Australia/Currie":{a:"Australia/Hobart",r:1},"Australia/Darwin":{u:570,c:["AU"]},"Australia/Eucla":{u:525,c:["AU"]},"Australia/Hobart":{u:600,d:660,c:["AU"]},"Australia/LHI":{a:"Australia/Lord_Howe",r:1},"Australia/Lindeman":{u:600,c:["AU"]},"Australia/Lord_Howe":{u:630,d:660,c:["AU"]},"Australia/Melbourne":{u:600,d:660,c:["AU"]},"Australia/NSW":{a:"Australia/Sydney",r:1},"Australia/North":{a:"Australia/Darwin",r:1},"Australia/Perth":{u:480,c:["AU"]},"Australia/Queensland":{a:"Australia/Brisbane",r:1},"Australia/South":{a:"Australia/Adelaide",r:1},"Australia/Sydney":{u:600,d:660,c:["AU"]},"Australia/Tasmania":{a:"Australia/Hobart",r:1},"Australia/Victoria":{a:"Australia/Melbourne",r:1},"Australia/West":{a:"Australia/Perth",r:1},"Australia/Yancowinna":{a:"Australia/Broken_Hill",r:1},"Brazil/Acre":{a:"America/Rio_Branco",r:1},"Brazil/DeNoronha":{a:"America/Noronha",r:1},"Brazil/East":{a:"America/Sao_Paulo",r:1},"Brazil/West":{a:"America/Manaus",r:1},CET:{u:60,d:120},CST6CDT:{u:-360,d:-300},"Canada/Atlantic":{a:"America/Halifax",r:1},"Canada/Central":{a:"America/Winnipeg",r:1},"Canada/Eastern":{a:"America/Toronto",c:["CA"],r:1},"Canada/Mountain":{a:"America/Edmonton",r:1},"Canada/Newfoundland":{a:"America/St_Johns",r:1},"Canada/Pacific":{a:"America/Vancouver",r:1},"Canada/Saskatchewan":{a:"America/Regina",r:1},"Canada/Yukon":{a:"America/Whitehorse",r:1},"Chile/Continental":{a:"America/Santiago",r:1},"Chile/EasterIsland":{a:"Pacific/Easter",r:1},Cuba:{a:"America/Havana",r:1},EET:{u:120,d:180},EST:{u:-300},EST5EDT:{u:-300,d:-240},Egypt:{a:"Africa/Cairo",r:1},Eire:{a:"Europe/Dublin",r:1},"Etc/GMT":{u:0},"Etc/GMT+0":{a:"Etc/GMT",r:1},"Etc/GMT+1":{u:-60},"Etc/GMT+10":{u:-600},"Etc/GMT+11":{u:-660},"Etc/GMT+12":{u:-720},"Etc/GMT+2":{u:-120},"Etc/GMT+3":{u:-180},"Etc/GMT+4":{u:-240},"Etc/GMT+5":{u:-300},"Etc/GMT+6":{u:-360},"Etc/GMT+7":{u:-420},"Etc/GMT+8":{u:-480},"Etc/GMT+9":{u:-540},"Etc/GMT-0":{a:"Etc/GMT",r:1},"Etc/GMT-1":{u:60},"Etc/GMT-10":{u:600},"Etc/GMT-11":{u:660},"Etc/GMT-12":{u:720},"Etc/GMT-13":{u:780},"Etc/GMT-14":{u:840},"Etc/GMT-2":{u:120},"Etc/GMT-3":{u:180},"Etc/GMT-4":{u:240},"Etc/GMT-5":{u:300},"Etc/GMT-6":{u:360},"Etc/GMT-7":{u:420},"Etc/GMT-8":{u:480},"Etc/GMT-9":{u:540},"Etc/GMT0":{a:"Etc/GMT",r:1},"Etc/Greenwich":{a:"Etc/GMT",r:1},"Etc/UCT":{a:"Etc/UTC",r:1},"Etc/UTC":{u:0},"Etc/Universal":{a:"Etc/UTC",r:1},"Etc/Zulu":{a:"Etc/UTC",r:1},"Europe/Amsterdam":{u:60,d:120,c:["NL"]},"Europe/Andorra":{u:60,d:120,c:["AD"]},"Europe/Astrakhan":{u:240,c:["RU"]},"Europe/Athens":{u:120,d:180,c:["GR"]},"Europe/Belfast":{a:"Europe/London",c:["GB"],r:1},"Europe/Belgrade":{u:60,d:120,c:["RS","BA","HR","ME","MK","SI"]},"Europe/Berlin":{u:60,d:120,c:["DE"]},"Europe/Bratislava":{a:"Europe/Prague",c:["SK"],r:1},"Europe/Brussels":{u:60,d:120,c:["BE"]},"Europe/Bucharest":{u:120,d:180,c:["RO"]},"Europe/Budapest":{u:60,d:120,c:["HU"]},"Europe/Busingen":{a:"Europe/Zurich",c:["DE"],r:1},"Europe/Chisinau":{u:120,d:180,c:["MD"]},"Europe/Copenhagen":{u:60,d:120,c:["DK"]},"Europe/Dublin":{u:60,d:0,c:["IE"]},"Europe/Gibraltar":{u:60,d:120,c:["GI"]},"Europe/Guernsey":{a:"Europe/London",c:["GG"],r:1},"Europe/Helsinki":{u:120,d:180,c:["FI","AX"]},"Europe/Isle_of_Man":{a:"Europe/London",c:["IM"],r:1},"Europe/Istanbul":{u:180,c:["TR"]},"Europe/Jersey":{a:"Europe/London",c:["JE"],r:1},"Europe/Kaliningrad":{u:120,c:["RU"]},"Europe/Kiev":{u:120,d:180,c:["UA"]},"Europe/Kirov":{u:180,c:["RU"]},"Europe/Lisbon":{u:0,d:60,c:["PT"]},"Europe/Ljubljana":{a:"Europe/Belgrade",c:["SI"],r:1},"Europe/London":{u:0,d:60,c:["GB","GG","IM","JE"]},"Europe/Luxembourg":{u:60,d:120,c:["LU"]},"Europe/Madrid":{u:60,d:120,c:["ES"]},"Europe/Malta":{u:60,d:120,c:["MT"]},"Europe/Mariehamn":{a:"Europe/Helsinki",c:["AX"],r:1},"Europe/Minsk":{u:180,c:["BY"]},"Europe/Monaco":{u:60,d:120,c:["MC"]},"Europe/Moscow":{u:180,c:["RU"]},"Europe/Nicosia":{a:"Asia/Nicosia",r:1},"Europe/Oslo":{u:60,d:120,c:["NO","SJ","BV"]},"Europe/Paris":{u:60,d:120,c:["FR"]},"Europe/Podgorica":{a:"Europe/Belgrade",c:["ME"],r:1},"Europe/Prague":{u:60,d:120,c:["CZ","SK"]},"Europe/Riga":{u:120,d:180,c:["LV"]},"Europe/Rome":{u:60,d:120,c:["IT","SM","VA"]},"Europe/Samara":{u:240,c:["RU"]},"Europe/San_Marino":{a:"Europe/Rome",c:["SM"],r:1},"Europe/Sarajevo":{a:"Europe/Belgrade",c:["BA"],r:1},"Europe/Saratov":{u:240,c:["RU"]},"Europe/Simferopol":{u:180,c:["RU","UA"]},"Europe/Skopje":{a:"Europe/Belgrade",c:["MK"],r:1},"Europe/Sofia":{u:120,d:180,c:["BG"]},"Europe/Stockholm":{u:60,d:120,c:["SE"]},"Europe/Tallinn":{u:120,d:180,c:["EE"]},"Europe/Tirane":{u:60,d:120,c:["AL"]},"Europe/Tiraspol":{a:"Europe/Chisinau",r:1},"Europe/Ulyanovsk":{u:240,c:["RU"]},"Europe/Uzhgorod":{u:120,d:180,c:["UA"]},"Europe/Vaduz":{a:"Europe/Zurich",c:["LI"],r:1},"Europe/Vatican":{a:"Europe/Rome",c:["VA"],r:1},"Europe/Vienna":{u:60,d:120,c:["AT"]},"Europe/Vilnius":{u:120,d:180,c:["LT"]},"Europe/Volgograd":{u:180,c:["RU"]},"Europe/Warsaw":{u:60,d:120,c:["PL"]},"Europe/Zagreb":{a:"Europe/Belgrade",c:["HR"],r:1},"Europe/Zaporozhye":{u:120,d:180,c:["UA"]},"Europe/Zurich":{u:60,d:120,c:["CH","DE","LI"]},Factory:{u:0},GB:{a:"Europe/London",c:["GB"],r:1},"GB-Eire":{a:"Europe/London",c:["GB"],r:1},GMT:{a:"Etc/GMT",r:1},"GMT+0":{a:"Etc/GMT",r:1},"GMT-0":{a:"Etc/GMT",r:1},GMT0:{a:"Etc/GMT",r:1},Greenwich:{a:"Etc/GMT",r:1},HST:{u:-600},Hongkong:{a:"Asia/Hong_Kong",r:1},Iceland:{a:"Atlantic/Reykjavik",r:1},"Indian/Antananarivo":{a:"Africa/Nairobi",c:["MG"],r:1},"Indian/Chagos":{u:360,c:["IO"]},"Indian/Christmas":{u:420,c:["CX"]},"Indian/Cocos":{u:390,c:["CC"]},"Indian/Comoro":{a:"Africa/Nairobi",c:["KM"],r:1},"Indian/Kerguelen":{u:300,c:["TF","HM"]},"Indian/Mahe":{u:240,c:["SC"]},"Indian/Maldives":{u:300,c:["MV"]},"Indian/Mauritius":{u:240,c:["MU"]},"Indian/Mayotte":{a:"Africa/Nairobi",c:["YT"],r:1},"Indian/Reunion":{u:240,c:["RE","TF"]},Iran:{a:"Asia/Tehran",r:1},Israel:{a:"Asia/Jerusalem",r:1},Jamaica:{a:"America/Jamaica",r:1},Japan:{a:"Asia/Tokyo",r:1},Kwajalein:{a:"Pacific/Kwajalein",r:1},Libya:{a:"Africa/Tripoli",r:1},MET:{u:60,d:120},MST:{u:-420},MST7MDT:{u:-420,d:-360},"Mexico/BajaNorte":{a:"America/Tijuana",r:1},"Mexico/BajaSur":{a:"America/Mazatlan",r:1},"Mexico/General":{a:"America/Mexico_City",r:1},NZ:{a:"Pacific/Auckland",c:["NZ"],r:1},"NZ-CHAT":{a:"Pacific/Chatham",r:1},Navajo:{a:"America/Denver",r:1},PRC:{a:"Asia/Shanghai",r:1},PST8PDT:{u:-480,d:-420},"Pacific/Apia":{u:780,c:["WS"]},"Pacific/Auckland":{u:720,d:780,c:["NZ","AQ"]},"Pacific/Bougainville":{u:660,c:["PG"]},"Pacific/Chatham":{u:765,d:825,c:["NZ"]},"Pacific/Chuuk":{u:600,c:["FM"]},"Pacific/Easter":{u:-360,d:-300,c:["CL"]},"Pacific/Efate":{u:660,c:["VU"]},"Pacific/Enderbury":{a:"Pacific/Kanton",r:1},"Pacific/Fakaofo":{u:780,c:["TK"]},"Pacific/Fiji":{u:720,d:780,c:["FJ"]},"Pacific/Funafuti":{u:720,c:["TV"]},"Pacific/Galapagos":{u:-360,c:["EC"]},"Pacific/Gambier":{u:-540,c:["PF"]},"Pacific/Guadalcanal":{u:660,c:["SB"]},"Pacific/Guam":{u:600,c:["GU","MP"]},"Pacific/Honolulu":{u:-600,c:["US","UM"]},"Pacific/Johnston":{a:"Pacific/Honolulu",c:["UM"],r:1},"Pacific/Kanton":{u:780,c:["KI"]},"Pacific/Kiritimati":{u:840,c:["KI"]},"Pacific/Kosrae":{u:660,c:["FM"]},"Pacific/Kwajalein":{u:720,c:["MH"]},"Pacific/Majuro":{u:720,c:["MH"]},"Pacific/Marquesas":{u:-510,c:["PF"]},"Pacific/Midway":{a:"Pacific/Pago_Pago",c:["UM"],r:1},"Pacific/Nauru":{u:720,c:["NR"]},"Pacific/Niue":{u:-660,c:["NU"]},"Pacific/Norfolk":{u:660,d:720,c:["NF"]},"Pacific/Noumea":{u:660,c:["NC"]},"Pacific/Pago_Pago":{u:-660,c:["AS","UM"]},"Pacific/Palau":{u:540,c:["PW"]},"Pacific/Pitcairn":{u:-480,c:["PN"]},"Pacific/Pohnpei":{u:660,c:["FM"]},"Pacific/Ponape":{a:"Pacific/Pohnpei",r:1},"Pacific/Port_Moresby":{u:600,c:["PG","AQ"]},"Pacific/Rarotonga":{u:-600,c:["CK"]},"Pacific/Saipan":{a:"Pacific/Guam",c:["MP"],r:1},"Pacific/Samoa":{a:"Pacific/Pago_Pago",c:["WS"],r:1},"Pacific/Tahiti":{u:-600,c:["PF"]},"Pacific/Tarawa":{u:720,c:["KI"]},"Pacific/Tongatapu":{u:780,c:["TO"]},"Pacific/Truk":{a:"Pacific/Chuuk",r:1},"Pacific/Wake":{u:720,c:["UM"]},"Pacific/Wallis":{u:720,c:["WF"]},"Pacific/Yap":{a:"Pacific/Chuuk",r:1},Poland:{a:"Europe/Warsaw",r:1},Portugal:{a:"Europe/Lisbon",r:1},ROC:{a:"Asia/Taipei",r:1},ROK:{a:"Asia/Seoul",r:1},Singapore:{a:"Asia/Singapore",c:["SG"],r:1},Turkey:{a:"Europe/Istanbul",r:1},UCT:{a:"Etc/UTC",r:1},"US/Alaska":{a:"America/Anchorage",r:1},"US/Aleutian":{a:"America/Adak",r:1},"US/Arizona":{a:"America/Phoenix",c:["US"],r:1},"US/Central":{a:"America/Chicago",r:1},"US/East-Indiana":{a:"America/Indiana/Indianapolis",r:1},"US/Eastern":{a:"America/New_York",r:1},"US/Hawaii":{a:"Pacific/Honolulu",c:["US"],r:1},"US/Indiana-Starke":{a:"America/Indiana/Knox",r:1},"US/Michigan":{a:"America/Detroit",r:1},"US/Mountain":{a:"America/Denver",r:1},"US/Pacific":{a:"America/Los_Angeles",r:1},"US/Samoa":{a:"Pacific/Pago_Pago",c:["WS"],r:1},UTC:{a:"Etc/UTC",r:1},Universal:{a:"Etc/UTC",r:1},"W-SU":{a:"Europe/Moscow",r:1},WET:{u:0,d:60},Zulu:{a:"Etc/UTC",r:1}};function qt(){let n=Intl.DateTimeFormat().resolvedOptions().timeZone;if(n===""||!n)return null;try{let e=Jt[n]?.c?.[0];return e&&jr[e]||null}catch{return null}}function be(){let n=Intl.DateTimeFormat().resolvedOptions().timeZone;if(n===""||!n)return"Unknown";try{return Jt[n]?.c?.[0]||"Unknown"}catch{return"Unknown"}}function Xt(){let n=Intl.DateTimeFormat().resolvedOptions().timeZone;return n===""||!n?null:n.split("/")[1]?.replace("_"," ")||null}var we=class{constructor(e,t){this.isDestroyed=!1;this.currentPath=null;this.originalPushState=null;this.originalReplaceState=null;this.previousPage=null;this.landingPage=null;this.pageViewCount=0;this.handlePopState=()=>{this.isDestroyed||this.trackCurrentPage()};this.handleHashChange=()=>{this.isDestroyed||this.trackCurrentPage()};this.tracker=e,this.config=t,this.trackCurrentPage(!0),this.setupHistoryListeners(),this.setupHashChangeListener()}setupHistoryListeners(){typeof window>"u"||typeof history>"u"||(this.originalPushState=history.pushState,history.pushState=(e,t,i)=>{this.originalPushState?.call(history,e,t,i),this.trackCurrentPage()},this.originalReplaceState=history.replaceState,history.replaceState=(e,t,i)=>{this.originalReplaceState?.call(history,e,t,i),this.trackCurrentPage()},window.addEventListener("popstate",this.handlePopState))}setupHashChangeListener(){typeof window>"u"||window.addEventListener("hashchange",this.handleHashChange)}trackCurrentPage(e=!1){if(this.isDestroyed||typeof window>"u")return;let t=this.extractPath(window.location.href);if(!e&&t===this.currentPath)return;this.currentPath&&(this.previousPage=this.currentPath),this.currentPath=t,this.pageViewCount++,e&&(this.landingPage=t);let i=this.tracker.hasConsent("analytics"),r=window.location.href,s=document.referrer||"",a=re(r);Object.keys(a).length>0&&(!K()||e)&&Yt(a);let o=K()||{},c=ve(this.config.tenantId,s,r,o),l={page:t,timestamp:Date.now()};if(i){l.title=document.title||"",l.full_url=this.cleanUrl(r),l.session_id=this.tracker.getSessionId(),s&&(l.referrer=s,l.referrer_domain=this.extractDomain(s),l.referrer_category=V(s,r)),this.landingPage&&!e&&(l.landing_page=this.landingPage),this.previousPage&&(l.previous_page=this.previousPage,this.tracker.trackSystemEvent("_grain_navigation",{from_page:this.previousPage,to_page:t,timestamp:Date.now()})),o.utm_source&&(l.utm_source=o.utm_source),o.utm_medium&&(l.utm_medium=o.utm_medium),o.utm_campaign&&(l.utm_campaign=o.utm_campaign),o.utm_term&&(l.utm_term=o.utm_term),o.utm_content&&(l.utm_content=o.utm_content),l.first_touch_source=c.source,l.first_touch_medium=c.medium,l.first_touch_campaign=c.campaign,l.first_touch_referrer_category=c.referrer_category,l.device=this.getDeviceType(),l.browser=this.getBrowser(),l.os=this.getOS(),l.language=navigator.language||"";let u=Intl.DateTimeFormat().resolvedOptions().timeZone;l.timezone=u,l.country=be(),l.screen_resolution=`${screen.width}x${screen.height}`,l.viewport=`${window.innerWidth}x${window.innerHeight}`}this.tracker.trackSystemEvent("page_view",l)}extractDomain(e){try{return new URL(e).hostname}catch{return""}}getBrowser(){let e=navigator.userAgent;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")&&!e.includes("Chrome/")?"Safari":e.includes("Opera/")||e.includes("OPR/")?"Opera":"Unknown"}getOS(){let e=navigator.userAgent;return e.includes("Win")?"Windows":e.includes("Mac")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown"}getDeviceType(){let e=navigator.userAgent,t=window.innerWidth;return e.includes("iPad")||e.includes("Android")&&!e.includes("Mobile")?"Tablet":e.includes("Mobile")||e.includes("iPhone")||e.includes("Android")||t<768?"Mobile":t>=768&&t<1024?"Tablet":"Desktop"}extractPath(e){try{let t=new URL(e),i=t.pathname;return!this.config.stripQueryParams&&t.search&&(i+=t.search),!this.config.stripHash&&t.hash&&(i+=t.hash),i}catch(t){return this.config.debug&&console.warn("[Page Tracking] Failed to parse URL:",e,t),e}}cleanUrl(e){if(!this.config.stripQueryParams)return e;try{let t=new URL(e);return`${t.origin}${t.pathname}${this.config.stripHash?"":t.hash}`}catch{return e}}getCurrentPage(){return this.currentPath}trackPage(e,t){if(this.isDestroyed)return;let i=this.tracker.hasConsent("analytics"),r={page:e,timestamp:Date.now(),...t};i&&typeof document<"u"&&typeof window<"u"&&(r.referrer||(r.referrer=document.referrer||""),r.title||(r.title=document.title||""),r.full_url||(r.full_url=window.location.href),r.session_id||(r.session_id=this.tracker.getSessionId()),r.browser||(r.browser=this.getBrowser()),r.os||(r.os=this.getOS())),this.tracker.trackSystemEvent("page_view",r)}getPageViewCount(){return this.pageViewCount}destroy(){this.isDestroyed||(typeof history<"u"&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState)),typeof window<"u"&&(window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("hashchange",this.handleHashChange)),this.isDestroyed=!0)}};function ti(n){let e=0;for(let t=0;t<n.length;t++){let i=n.charCodeAt(t);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}function Zt(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Qr(){if(typeof window>"u")return"server";let n=[screen.width?.toString()||"",screen.height?.toString()||"",navigator.language||"",Intl.DateTimeFormat().resolvedOptions().timeZone||""];return ti(n.join("|"))}function ei(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),i=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${i}`}var Se=class{constructor(e){this.cachedDailyId=null;this.dailyIdDate=null;this.dailyRandomSeed=null;this.permanentId=null;this.config=e,e.mode==="permanent"&&e.useLocalStorage&&this.loadPermanentId(),e.mode==="cookieless"&&this.loadDailySeed()}generateDailyRotatingId(){let e=ei();if(this.cachedDailyId&&this.dailyIdDate===e&&this.dailyRandomSeed)return this.cachedDailyId;let t=this.loadDailySeed();this.dailyIdDate!==e&&(this.dailyRandomSeed=null,this.clearDailySeed()),this.dailyRandomSeed||(this.dailyRandomSeed=t||Zt(),this.saveDailySeed(this.dailyRandomSeed,e));let i=Qr(),r=`${this.config.tenantId}|${e}|${i}|${this.dailyRandomSeed}`,s=`daily_${ti(r)}`;return this.cachedDailyId=s,this.dailyIdDate=e,s}generatePermanentId(){if(this.permanentId)return this.permanentId;if(this.config.useLocalStorage){let t=this.loadPermanentId();if(t)return t}let e=Zt();return this.permanentId=e,this.config.useLocalStorage&&this.savePermanentId(e),e}getCurrentUserId(){return this.config.mode==="cookieless"?this.generateDailyRotatingId():this.generatePermanentId()}setMode(e){this.config.mode=e,e==="permanent"&&(this.cachedDailyId=null,this.dailyIdDate=null,this.dailyRandomSeed=null,this.clearDailySeed()),e==="cookieless"&&(this.permanentId=null,this.config.useLocalStorage&&this.clearPermanentId(),this.loadDailySeed())}loadPermanentId(){if(typeof window>"u")return null;try{let e=`grain_anonymous_user_id_${this.config.tenantId}`,t=localStorage.getItem(e);if(t)return this.permanentId=t,t}catch{}return null}savePermanentId(e){if(!(typeof window>"u"))try{let t=`grain_anonymous_user_id_${this.config.tenantId}`;localStorage.setItem(t,e)}catch{}}clearPermanentId(){if(!(typeof window>"u"))try{let e=`grain_anonymous_user_id_${this.config.tenantId}`;localStorage.removeItem(e)}catch{}}loadDailySeed(){if(typeof window>"u")return null;try{let e=`grain_daily_seed_${this.config.tenantId}`,t=sessionStorage.getItem(e);if(t){let i=JSON.parse(t),r=ei();if(i.date===r&&i.seed)return this.dailyRandomSeed=i.seed,this.dailyIdDate=i.date,i.seed;this.clearDailySeed()}}catch{}return null}saveDailySeed(e,t){if(!(typeof window>"u"))try{let i=`grain_daily_seed_${this.config.tenantId}`,r={seed:e,date:t};sessionStorage.setItem(i,JSON.stringify(r))}catch{}}clearDailySeed(){if(!(typeof window>"u"))try{let e=`grain_daily_seed_${this.config.tenantId}`;sessionStorage.removeItem(e)}catch{}}getIdInfo(){let e=this.getCurrentUserId();return{mode:this.config.mode,id:e,isDailyRotating:e.startsWith("daily_")}}};var ee=class{constructor(e){this.eventQueue=[];this.waitingForConsentQueue=[];this.flushTimer=null;this.isDestroyed=!1;this.globalUserId=null;this.persistentAnonymousUserId=null;this.configCache=null;this.configRefreshTimer=null;this.configChangeListeners=[];this.configFetchPromise=null;this.cookiesEnabled=!1;this.activityDetector=null;this.heartbeatManager=null;this.pageTrackingManager=null;this.ephemeralSessionId=null;this.eventCountSinceLastHeartbeat=0;this.interactionTrackingManager=null;this.sectionTrackingManager=null;this.heatmapTrackingManager=null;this.sessionStartTime=Date.now();this.sessionEventCount=0;this.debugAgent=null;this.isDebugMode=!1;this.config={apiUrl:"https://api.grainql.com",authStrategy:"NONE",batchSize:50,flushInterval:5e3,retryAttempts:3,retryDelay:1e3,maxEventsPerRequest:160,debug:!1,defaultConfigurations:{},configCacheKey:"grain_config",configRefreshInterval:3e5,enableConfigCache:!0,consentMode:"COOKIELESS",waitForConsent:!1,disableAutoProperties:!1,enableHeartbeat:!0,heartbeatActiveInterval:12e4,heartbeatInactiveInterval:3e5,enableAutoPageView:!0,stripQueryParams:!0,stripHash:!1,enableHeatmapTracking:!0,...e,tenantId:e.tenantId},this.consentManager=new ge(this.config.tenantId,this.config.consentMode);let t=this.consentManager.getIdMode();this.idManager=new Se({mode:t,tenantId:this.config.tenantId,useLocalStorage:!0}),e.userId&&(this.globalUserId=e.userId),this.validateConfig(),this.setupBeforeUnload(),this.startFlushTimer(),this.initializeConfigCache(),this.ephemeralSessionId=this.generateUUID(),typeof window<"u"&&(this.checkAndInitializeDebugMode(),this.initializeAutomaticTracking(),this.trackSessionStart(),this.config.enableHeatmapTracking&&this.initializeHeatmapTracking()),this.consentManager.addListener(i=>{let r=this.consentManager.getIdMode();this.idManager.setMode(r),i.granted&&this.handleConsentGranted()})}validateConfig(){if(!this.config.tenantId)throw new Error("Grain Analytics: tenantId is required");if(this.config.authStrategy==="SERVER_SIDE"&&!this.config.secretKey)throw new Error("Grain Analytics: secretKey is required for SERVER_SIDE auth strategy");if(this.config.authStrategy==="JWT"&&!this.config.authProvider)throw new Error("Grain Analytics: authProvider is required for JWT auth strategy")}generateUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}shouldAllowPersistentStorage(){let e=this.consentManager.hasConsent("analytics"),t=this.config.consentMode==="COOKIELESS",i=!!this.globalUserId,r=this.config.authStrategy==="JWT";return t?!1:e||i||r}generateAnonymousUserId(){return this.generateUUID()}initializePersistentAnonymousUserId(){if(typeof window>"u")return;if(!this.shouldAllowPersistentStorage()){this.log("Opt-in mode without consent: skipping persistent ID initialization (GDPR compliance)");return}let e=`grain_anonymous_user_id_${this.config.tenantId}`,t="_grain_uid";try{if(this.cookiesEnabled){let r=Wt(t);if(r){this.persistentAnonymousUserId=r,this.log("Loaded persistent anonymous user ID from cookie:",this.persistentAnonymousUserId);return}}let i=localStorage.getItem(e);i?(this.persistentAnonymousUserId=i,this.log("Loaded persistent anonymous user ID from localStorage:",this.persistentAnonymousUserId),this.cookiesEnabled&&this.savePersistentAnonymousUserId(i)):(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId),this.log("Generated new persistent anonymous user ID:",this.persistentAnonymousUserId))}catch(i){this.log("Failed to initialize persistent anonymous user ID:",i),this.persistentAnonymousUserId=this.generateAnonymousUserId()}}savePersistentAnonymousUserId(e){if(typeof window>"u")return;if(!this.shouldAllowPersistentStorage()){this.log("Opt-in mode without consent: skipping persistent ID save (GDPR compliance)");return}let t=`grain_anonymous_user_id_${this.config.tenantId}`,i="_grain_uid";try{if(this.cookiesEnabled){let r={maxAge:31536e3,sameSite:"lax",secure:typeof window<"u"&&window.location.protocol==="https:",...this.config.cookieOptions};Kt(i,e,r)}localStorage.setItem(t,e)}catch(r){this.log("Failed to save persistent anonymous user ID:",r)}}getEffectiveUserIdInternal(){return this.globalUserId?this.globalUserId:this.idManager.getCurrentUserId()}log(...e){this.config.debug&&console.log("[Grain Analytics]",...e)}createErrorDigest(e){let t=[...new Set(e.map(a=>a.eventName))],i=[...new Set(e.map(a=>a.userId))],r=0,s=0;return e.forEach(a=>{let o=a.properties||{};r+=Object.keys(o).length,s+=JSON.stringify(a).length}),{eventCount:e.length,totalProperties:r,totalSize:s,eventNames:t,userIds:i}}formatError(e,t,i){let r=i?this.createErrorDigest(i):{eventCount:0,totalProperties:0,totalSize:0,eventNames:[],userIds:[]},s="UNKNOWN_ERROR",a="An unknown error occurred";if(e instanceof Error)a=e.message,a.includes("fetch failed")||a.includes("network error")?s="NETWORK_ERROR":a.includes("timeout")?s="TIMEOUT_ERROR":a.includes("HTTP 4")?s="CLIENT_ERROR":a.includes("HTTP 5")?s="SERVER_ERROR":a.includes("JSON")?s="PARSE_ERROR":a.includes("auth")||a.includes("unauthorized")?s="AUTH_ERROR":a.includes("rate limit")||a.includes("429")?s="RATE_LIMIT_ERROR":s="GENERAL_ERROR";else if(typeof e=="string")a=e,s="STRING_ERROR";else if(e&&typeof e=="object"&&"status"in e){let o=e.status;s=`HTTP_${o}`,a=`HTTP ${o} error`}return{code:s,message:a,digest:r,timestamp:new Date().toISOString(),context:t,originalError:e}}logError(e){if(!this.config.debug)return;let{code:t,message:i,digest:r,timestamp:s,context:a}=e,o={"\u{1F6A8} Grain Analytics Error":{"Error Code":t,Message:i,Context:a,Timestamp:s,"Event Digest":{Events:r.eventCount,Properties:r.totalProperties,"Size (bytes)":r.totalSize,"Event Names":r.eventNames.length>0?r.eventNames.join(", "):"None","User IDs":r.userIds.length>0?r.userIds.slice(0,3).join(", ")+(r.userIds.length>3?"...":""):"None"}}};console.error("\u{1F6A8} Grain Analytics Error:",o),console.error(`[Grain Analytics] ${t}: ${i} (${a}) - Events: ${r.eventCount}, Props: ${r.totalProperties}, Size: ${r.totalSize}B`)}async safeExecute(e,t,i){try{return await e()}catch(r){let s=this.formatError(r,t,i);return this.logError(s),null}}formatEvent(e){let t=e.properties||{};if(!this.config.disableAutoProperties&&typeof window<"u"){let i=this.consentManager.hasConsent("analytics");if(!e.eventName.startsWith("_grain_")&&i){let s=K();s&&(s.utm_source&&(t.utm_source=s.utm_source),s.utm_medium&&(t.utm_medium=s.utm_medium),s.utm_campaign&&(t.utm_campaign=s.utm_campaign),s.utm_term&&(t.utm_term=s.utm_term),s.utm_content&&(t.utm_content=s.utm_content));let a=tt(this.config.tenantId);a&&(t.first_touch_source=a.source,t.first_touch_medium=a.medium,t.first_touch_campaign=a.campaign,t.first_touch_referrer_category=a.referrer_category),t.session_id||(t.session_id=this.getSessionId())}}return{eventName:e.eventName,userId:e.userId||this.getEffectiveUserIdInternal(),properties:t}}async getAuthHeaders(){let e={"Content-Type":"application/json"};switch(this.config.authStrategy){case"NONE":break;case"SERVER_SIDE":e.Authorization=`Chase ${this.config.secretKey}`;break;case"JWT":if(this.config.authProvider){let t=await this.config.authProvider.getToken();e.Authorization=`Bearer ${t}`}break}return e}async delay(e){return new Promise(t=>setTimeout(t,e))}isRetriableError(e){if(e instanceof Error){let t=e.message.toLowerCase();if(t.includes("fetch failed")||t==="network error"||t.includes("timeout")||t.includes("connection"))return!0}if(typeof e=="object"&&e!==null&&"status"in e){let t=e.status;return t>=500||t===429}return!1}async sendEvents(e){if(e.length===0)return;let t;for(let i=0;i<=this.config.retryAttempts;i++)try{let r=await this.getAuthHeaders(),s=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`,a=await fetch(s,{method:"POST",headers:r,body:JSON.stringify(e)});if(!a.ok){let o=`HTTP ${a.status}`;try{let l=await a.json();l?.message&&(o=l.message)}catch{let l=await a.text();l&&(o=l)}let c=new Error(`Failed to send events: ${o}`);throw c.status=a.status,c}this.log(`Successfully sent ${e.length} events`);return}catch(r){if(t=r,i===this.config.retryAttempts){let a=this.formatError(r,`sendEvents (attempt ${i+1}/${this.config.retryAttempts+1})`,e);this.logError(a);return}if(!this.isRetriableError(r)){let a=this.formatError(r,"sendEvents (non-retriable error)",e);this.logError(a);return}let s=this.config.retryDelay*Math.pow(2,i);this.log(`Retrying in ${s}ms after error:`,r),await this.delay(s)}}async sendEventsWithBeacon(e){if(e.length!==0)try{let t=await this.getAuthHeaders(),i=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`,r=JSON.stringify(e);if(!(this.config.authStrategy!=="NONE")&&typeof navigator<"u"&&"sendBeacon"in navigator){let a=new Blob([r],{type:"application/json"});if(navigator.sendBeacon(i,a)){this.log(`Successfully sent ${e.length} events via beacon`);return}}await fetch(i,{method:"POST",headers:t,body:r,keepalive:!0})}catch(t){let i=this.formatError(t,"sendEventsWithBeacon",e);this.logError(i)}}startFlushTimer(){typeof window>"u"||(this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=window.setInterval(()=>{this.eventQueue.length>0&&this.flush().catch(e=>{let t=this.formatError(e,"auto-flush");this.logError(t)})},this.config.flushInterval))}setupBeforeUnload(){if(typeof window>"u")return;let e=()=>{if(this.trackSessionEnd(),this.eventQueue.length>0){let t=[...this.eventQueue];this.eventQueue=[];let i=this.chunkEvents(t,this.config.maxEventsPerRequest);i.length>0&&this.sendEventsWithBeacon(i[0]).catch(()=>{})}};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden"&&this.eventQueue.length>0){let t=[...this.eventQueue];this.eventQueue=[];let i=this.chunkEvents(t,this.config.maxEventsPerRequest);i.length>0&&this.sendEventsWithBeacon(i[0]).catch(()=>{})}})}initializeAutomaticTracking(){if(this.config.enableHeartbeat)try{this.activityDetector=new me,this.heartbeatManager=new ye(this,this.activityDetector,{activeInterval:this.config.heartbeatActiveInterval,inactiveInterval:this.config.heartbeatInactiveInterval,debug:this.config.debug})}catch(e){this.log("Failed to initialize heartbeat tracking:",e)}if(this.config.enableAutoPageView)try{this.pageTrackingManager=new we(this,{stripQueryParams:this.config.stripQueryParams,stripHash:this.config.stripHash,debug:this.config.debug,tenantId:this.config.tenantId})}catch(e){this.log("Failed to initialize page view tracking:",e)}this.initializeAutoTracking()}initializeHeatmapTracking(){if(!(typeof window>"u"))try{this.log("Initializing heatmap tracking"),Promise.resolve().then(()=>(Pr(),Mr)).then(({HeatmapTrackingManager:e})=>{try{this.heatmapTrackingManager=new e(this,{scrollDebounceDelay:100,batchDelay:2e3,maxBatchSize:20,debug:this.config.debug}),this.log("Heatmap tracking initialized")}catch(t){this.log("Failed to initialize heatmap tracking:",t)}}).catch(e=>{this.log("Failed to load heatmap tracking module:",e)})}catch(e){this.log("Failed to initialize heatmap tracking:",e)}}async initializeAutoTracking(){try{this.log("Initializing auto-tracking");let e=this.globalUserId||this.persistentAnonymousUserId||this.generateUUID(),t=typeof window<"u"?window.location.href:"",i={userId:e,immediateKeys:[],properties:{},currentUrl:t},r=await this.getAuthHeaders(),s=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`,a=await fetch(s,{method:"POST",headers:r,body:JSON.stringify(i)});if(!a.ok){this.log("Failed to fetch auto-tracking config:",a.status);return}let o=await a.json();o.autoTrackingConfig&&(this.log("Auto-tracking config loaded"),this.setupAutoTrackingManagers(o.autoTrackingConfig))}catch(e){this.log("Failed to initialize auto-tracking:",e)}}setupAutoTrackingManagers(e){this.log("Setting up auto-tracking managers"),e.interactions&&e.interactions.length>0&&(this.log("Loading interaction tracking:",e.interactions.length,"interactions"),Promise.resolve().then(()=>(_r(),Ir)).then(({InteractionTrackingManager:t})=>{try{this.interactionTrackingManager=new t(this,e.interactions,{debug:this.config.debug,enableMutationObserver:!0,mutationDebounceDelay:500,tenantId:this.config.tenantId,apiUrl:this.config.apiUrl}),this.log("Interaction tracking initialized")}catch(i){this.log("Failed to initialize interaction tracking:",i)}}).catch(t=>{this.log("Failed to load interaction tracking module:",t)})),e.sections&&e.sections.length>0&&(this.log("Loading section tracking:",e.sections.length,"sections"),Promise.resolve().then(()=>(Dr(),Rr)).then(({SectionTrackingManager:t})=>{try{this.sectionTrackingManager=new t(this,e.sections,{minDwellTime:1e3,scrollVelocityThreshold:500,intersectionThreshold:.1,debounceDelay:100,batchDelay:2e3,debug:this.config.debug}),this.log("Section tracking initialized")}catch(i){this.log("Failed to initialize section tracking:",i)}}).catch(t=>{this.log("Failed to load section tracking module:",t)}))}trackSessionStart(){if(typeof window>"u")return;let e=this.consentManager.hasConsent("analytics"),t={session_id:this.getSessionId(),timestamp:this.sessionStartTime};if(e){let i=document.referrer||"",r=window.location.href,s=re(r),a=K()||s,o=ve(this.config.tenantId,i,r,a);t.landing_page=window.location.pathname,i?(t.referrer=i,t.referrer_domain=new URL(i).hostname,t.referrer_category=V(i,r)):t.referrer_category="direct",a.utm_source&&(t.utm_source=a.utm_source),a.utm_medium&&(t.utm_medium=a.utm_medium),a.utm_campaign&&(t.utm_campaign=a.utm_campaign),a.utm_term&&(t.utm_term=a.utm_term),a.utm_content&&(t.utm_content=a.utm_content),t.first_touch_source=o.source,t.first_touch_medium=o.medium,t.first_touch_campaign=o.campaign,t.first_touch_referrer_category=o.referrer_category,t.device=this.getDeviceType(),t.screen_resolution=`${screen.width}x${screen.height}`,t.viewport=`${window.innerWidth}x${window.innerHeight}`,t.browser=this.getBrowser(),t.os=this.getOS(),t.language=navigator.language||"",t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}this.trackSystemEvent("_grain_session_start",t),this.log("Session started")}trackSessionEnd(){if(typeof window>"u")return;let e=this.consentManager.hasConsent("analytics"),t=Date.now()-this.sessionStartTime,i={session_id:this.getSessionId(),session_duration:Math.floor(t/1e3),duration:t,event_count:this.sessionEventCount,timestamp:Date.now()};if(e&&this.pageTrackingManager){let r=this.pageTrackingManager.getPageViewCount();i.pages_per_session=r,i.page_count=r}this.trackSystemEvent("_grain_session_end",i),this.log("Session ended")}getBrowser(){if(typeof navigator>"u")return"Unknown";let e=navigator.userAgent;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")&&!e.includes("Chrome/")?"Safari":e.includes("Opera/")||e.includes("OPR/")?"Opera":"Unknown"}getOS(){if(typeof navigator>"u")return"Unknown";let e=navigator.userAgent;return e.includes("Win")?"Windows":e.includes("Mac")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown"}getDeviceType(){if(typeof window>"u"||typeof navigator>"u")return"Unknown";let e=navigator.userAgent,t=window.innerWidth;return e.includes("iPad")||e.includes("Android")&&!e.includes("Mobile")?"Tablet":e.includes("Mobile")||e.includes("iPhone")||e.includes("Android")||t<768?"Mobile":t>=768&&t<1024?"Tablet":"Desktop"}handleConsentGranted(){this.flushWaitingForConsentQueue(),this.persistentAnonymousUserId||(this.initializePersistentAnonymousUserId(),this.log("Initialized persistent ID after consent grant")),this.ephemeralSessionId&&this.trackSystemEvent("_grain_consent_granted",{previous_session_id:this.ephemeralSessionId,new_user_id:this.getEffectiveUserId(),timestamp:Date.now()})}trackSystemEvent(e,t){if(this.isDestroyed)return;let i=this.consentManager.hasConsent("analytics"),r={eventName:e,userId:this.getEffectiveUserId(),properties:{...t,_minimal:!i,_consent_status:i?"granted":"pending"}};this.eventQueue.push(r),this.eventCountSinceLastHeartbeat++,this.log(`Queued system event: ${e}`),this.eventQueue.length>=this.config.batchSize&&this.flush().catch(s=>{let a=this.formatError(s,"flush system event");this.logError(a)})}getEphemeralSessionId(){return this.ephemeralSessionId||(this.ephemeralSessionId=this.generateUUID()),this.ephemeralSessionId}getCurrentPage(){return this.pageTrackingManager?.getCurrentPage()||null}getEventCountSinceLastHeartbeat(){return this.eventCountSinceLastHeartbeat}resetEventCountSinceLastHeartbeat(){this.eventCountSinceLastHeartbeat=0}getActivityDetector(){if(!this.activityDetector)throw new Error("Activity detector not initialized");return this.activityDetector}getEffectiveUserId(){return this.getEffectiveUserIdInternal()}getSessionId(){return this.consentManager.hasConsent("analytics")?this.getEffectiveUserId():this.getEphemeralSessionId()}async track(e,t,i){try{if(this.isDestroyed){let c=new Error("Grain Analytics: Client has been destroyed"),l=this.formatError(c,"track (client destroyed)");this.logError(l);return}let r,s={};if(typeof e=="string"?(r={eventName:e,properties:t},s=i||{}):(r=e,s=t||{}),this.config.allowedProperties&&r.properties){let c={};for(let l of this.config.allowedProperties)l in r.properties&&(c[l]=r.properties[l]);r.properties=c}let a=this.formatEvent(r);if(this.consentManager.shouldWaitForConsent()&&this.config.waitForConsent){this.waitingForConsentQueue.push(a),this.log(`Event waiting for consent: ${r.eventName}`,r.properties);return}let o=this.consentManager.hasConsent("analytics");a.properties={...a.properties,_minimal:!o,_consent_status:o?"granted":"pending"},this.eventQueue.push(a),this.eventCountSinceLastHeartbeat++,this.sessionEventCount++,this.log(`Queued event: ${r.eventName}`),(s.flush||this.eventQueue.length>=this.config.batchSize)&&await this.flush()}catch(r){let s=this.formatError(r,"track");this.logError(s)}}flushWaitingForConsentQueue(){this.waitingForConsentQueue.length!==0&&(this.log(`Flushing ${this.waitingForConsentQueue.length} events waiting for consent`),this.eventQueue.push(...this.waitingForConsentQueue),this.waitingForConsentQueue=[],this.flush().catch(e=>{let t=this.formatError(e,"flush waiting for consent queue");this.logError(t)}))}identify(e){this.log(`Identified user: ${e}`),this.globalUserId=e,this.persistentAnonymousUserId=null}setUserId(e){this.log(`Set global user ID: ${e}`),this.globalUserId=e,e?this.persistentAnonymousUserId=null:this.persistentAnonymousUserId||(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId))}getUserId(){return this.globalUserId}getEffectiveUserIdPublic(){return this.getEffectiveUserIdInternal()}login(e){try{if(this.isDestroyed){let t=new Error("Grain Analytics: Client has been destroyed"),i=this.formatError(t,"login (client destroyed)");this.logError(i);return}e.userId&&(this.log(`Login: Setting user ID to ${e.userId}`),this.globalUserId=e.userId,this.persistentAnonymousUserId=null),e.authToken&&(this.log("Login: Setting auth token"),this.config.authStrategy==="NONE"&&(this.config.authStrategy="JWT"),this.config.authProvider={getToken:()=>e.authToken}),e.authStrategy&&(this.log(`Login: Setting auth strategy to ${e.authStrategy}`),this.config.authStrategy=e.authStrategy),this.log(`Login successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`)}catch(t){let i=this.formatError(t,"login");this.logError(i)}}logout(){try{if(this.isDestroyed){let e=new Error("Grain Analytics: Client has been destroyed"),t=this.formatError(e,"logout (client destroyed)");this.logError(t);return}if(this.log("Logout: Clearing user session"),this.globalUserId=null,this.config.authStrategy="NONE",this.config.authProvider=void 0,!this.persistentAnonymousUserId&&(this.persistentAnonymousUserId=this.generateAnonymousUserId(),typeof window<"u"))try{let e=`grain_anonymous_user_id_${this.config.tenantId}`;localStorage.setItem(e,this.persistentAnonymousUserId)}catch(e){this.log("Failed to persist new anonymous user ID after logout:",e)}this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`)}catch(e){let t=this.formatError(e,"logout");this.logError(t)}}async setProperty(e,t){try{if(this.isDestroyed){let o=new Error("Grain Analytics: Client has been destroyed"),c=this.formatError(o,"setProperty (client destroyed)");this.logError(c);return}let i=t?.userId||this.getEffectiveUserIdInternal(),r=Object.keys(e);if(r.length>4){let o=new Error("Grain Analytics: Maximum 4 properties allowed per request"),c=this.formatError(o,"setProperty (validation)");this.logError(c);return}if(r.length===0){let o=new Error("Grain Analytics: At least one property is required"),c=this.formatError(o,"setProperty (validation)");this.logError(c);return}let s={};for(let[o,c]of Object.entries(e))c==null?s[o]="":typeof c=="string"?s[o]=c:s[o]=JSON.stringify(c);let a={userId:i,...s};await this.sendProperties(a)}catch(i){let r=this.formatError(i,"setProperty");this.logError(r)}}async sendProperties(e){let t;for(let i=0;i<=this.config.retryAttempts;i++)try{let r=await this.getAuthHeaders(),s=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/properties`,a=await fetch(s,{method:"POST",headers:r,body:JSON.stringify(e)});if(!a.ok){let o=`HTTP ${a.status}`;try{let l=await a.json();l?.message&&(o=l.message)}catch{let l=await a.text();l&&(o=l)}let c=new Error(`Failed to set properties: ${o}`);throw c.status=a.status,c}this.log(`Successfully set properties for user ${e.userId}`);return}catch(r){if(t=r,i===this.config.retryAttempts){let a=this.formatError(r,`sendProperties (attempt ${i+1}/${this.config.retryAttempts+1})`);this.logError(a);return}if(!this.isRetriableError(r)){let a=this.formatError(r,"sendProperties (non-retriable error)");this.logError(a);return}let s=this.config.retryDelay*Math.pow(2,i);this.log(`Retrying in ${s}ms after error:`,r),await this.delay(s)}}async trackLogin(e,t){try{return await this.track("login",e,t)}catch(i){let r=this.formatError(i,"trackLogin");this.logError(r)}}async trackSignup(e,t){try{return await this.track("signup",e,t)}catch(i){let r=this.formatError(i,"trackSignup");this.logError(r)}}async trackCheckout(e,t){try{return await this.track("checkout",e,t)}catch(i){let r=this.formatError(i,"trackCheckout");this.logError(r)}}async trackPageView(e,t){try{return await this.track("page_view",e,t)}catch(i){let r=this.formatError(i,"trackPageView");this.logError(r)}}async trackPurchase(e,t){try{return await this.track("purchase",e,t)}catch(i){let r=this.formatError(i,"trackPurchase");this.logError(r)}}async trackSearch(e,t){try{return await this.track("search",e,t)}catch(i){let r=this.formatError(i,"trackSearch");this.logError(r)}}async trackAddToCart(e,t){try{return await this.track("add_to_cart",e,t)}catch(i){let r=this.formatError(i,"trackAddToCart");this.logError(r)}}async trackRemoveFromCart(e,t){try{return await this.track("remove_from_cart",e,t)}catch(i){let r=this.formatError(i,"trackRemoveFromCart");this.logError(r)}}async flush(){try{if(this.eventQueue.length===0)return;let e=[...this.eventQueue];this.eventQueue=[];let t=this.chunkEvents(e,this.config.maxEventsPerRequest);for(let i of t)await this.sendEvents(i)}catch(e){let t=this.formatError(e,"flush");this.logError(t)}}initializeConfigCache(){if(!(!this.config.enableConfigCache||typeof window>"u"))try{let e=localStorage.getItem(this.config.configCacheKey);e&&(this.configCache=JSON.parse(e),this.log("Loaded configuration from cache:",this.configCache))}catch(e){this.log("Failed to load configuration cache:",e)}}saveConfigCache(e){if(!(!this.config.enableConfigCache||typeof window>"u"))try{localStorage.setItem(this.config.configCacheKey,JSON.stringify(e)),this.log("Saved configuration to cache:",e)}catch(t){this.log("Failed to save configuration cache:",t)}}getConfig(e){if(this.configCache?.configurations?.[e])return this.configCache.configurations[e];if(this.config.defaultConfigurations?.[e])return this.config.defaultConfigurations[e]}getAllConfigs(){let e={...this.config.defaultConfigurations};return this.configCache?.configurations&&Object.assign(e,this.configCache.configurations),e}async fetchConfig(e={}){try{if(this.isDestroyed){let c=new Error("Grain Analytics: Client has been destroyed"),l=this.formatError(c,"fetchConfig (client destroyed)");return this.logError(l),null}let t=e.userId||this.getEffectiveUserIdInternal(),i=e.immediateKeys||[],r=e.properties||{},s=e.currentUrl??(typeof window<"u"?window.location.href:void 0);if(s)try{let c=new URL(s);s=`${c.protocol}//${c.host}${c.pathname}`}catch{}let a={userId:t,immediateKeys:i,properties:r,currentUrl:s},o;for(let c=0;c<=this.config.retryAttempts;c++)try{let l=await this.getAuthHeaders(),u=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`,d=await fetch(u,{method:"POST",headers:l,body:JSON.stringify(a)});if(!d.ok){let y=`HTTP ${d.status}`;try{let v=await d.json();v?.message&&(y=v.message)}catch{let v=await d.text();v&&(y=v)}let g=new Error(`Failed to fetch configurations: ${y}`);throw g.status=d.status,g}let f=await d.json();return f.configurations&&this.updateConfigCache(f,t),this.log("Successfully fetched configurations"),f}catch(l){if(o=l,c===this.config.retryAttempts){let d=this.formatError(l,`fetchConfig (attempt ${c+1}/${this.config.retryAttempts+1})`);return this.logError(d),null}if(!this.isRetriableError(l)){let d=this.formatError(l,"fetchConfig (non-retriable error)");return this.logError(d),null}let u=this.config.retryDelay*Math.pow(2,c);this.log(`Retrying config fetch in ${u}ms after error:`,l),await this.delay(u)}return null}catch(t){let i=this.formatError(t,"fetchConfig");return this.logError(i),null}}async getConfigAsync(e,t={}){try{if(!t.forceRefresh&&this.configCache?.configurations?.[e])return this.configCache.configurations[e];if(!t.forceRefresh&&this.config.defaultConfigurations?.[e])return this.config.defaultConfigurations[e];let i=await this.fetchConfig(t);return i?i.configurations[e]:this.config.defaultConfigurations?.[e]}catch(i){let r=this.formatError(i,"getConfigAsync");return this.logError(r),this.config.defaultConfigurations?.[e]}}async getAllConfigsAsync(e={}){try{if(!e.forceRefresh&&this.configCache?.configurations)return{...this.config.defaultConfigurations,...this.configCache.configurations};let t=await this.fetchConfig(e);return t?{...this.config.defaultConfigurations,...t.configurations}:{...this.config.defaultConfigurations}}catch(t){let i=this.formatError(t,"getAllConfigsAsync");return this.logError(i),{...this.config.defaultConfigurations}}}updateConfigCache(e,t){let i={configurations:e.configurations,snapshotId:e.snapshotId,timestamp:e.timestamp,userId:t},r=this.configCache?.configurations||{};this.configCache=i,this.saveConfigCache(i),JSON.stringify(r)!==JSON.stringify(e.configurations)&&this.notifyConfigChangeListeners(e.configurations)}addConfigChangeListener(e){this.configChangeListeners.push(e)}removeConfigChangeListener(e){let t=this.configChangeListeners.indexOf(e);t>-1&&this.configChangeListeners.splice(t,1)}notifyConfigChangeListeners(e){this.configChangeListeners.forEach(t=>{try{t(e)}catch(i){console.error("[Grain Analytics] Config change listener error:",i)}})}startConfigRefreshTimer(){typeof window>"u"||(this.configRefreshTimer&&clearInterval(this.configRefreshTimer),this.configRefreshTimer=window.setInterval(()=>{this.isDestroyed||this.fetchConfig().catch(e=>{let t=this.formatError(e,"auto-config refresh");this.logError(t)})},this.config.configRefreshInterval))}stopConfigRefreshTimer(){this.configRefreshTimer&&(clearInterval(this.configRefreshTimer),this.configRefreshTimer=null)}async preloadConfig(e=[],t){try{let i=this.getEffectiveUserIdInternal();this.log(`Preloading config for user: ${i}`),await this.fetchConfig({immediateKeys:e,properties:t})&&this.startConfigRefreshTimer()}catch(i){let r=this.formatError(i,"preloadConfig");this.logError(r)}}chunkEvents(e,t){let i=[];for(let r=0;r<e.length;r+=t)i.push(e.slice(r,r+t));return i}grantConsent(e){try{this.consentManager.grantConsent(e);let t=this.consentManager.getIdMode();this.idManager.setMode(t),this.log("Consent granted, switched to permanent IDs",e),this.waitingForConsentQueue.length>0&&(this.log(`Processing ${this.waitingForConsentQueue.length} queued events`),this.eventQueue.push(...this.waitingForConsentQueue),this.waitingForConsentQueue=[],this.flush())}catch(t){let i=this.formatError(t,"grantConsent");this.logError(i)}}revokeConsent(e){try{this.consentManager.revokeConsent(e);let t=this.consentManager.getIdMode();this.idManager.setMode(t),this.log("Consent revoked, switched to cookieless mode",e),this.consentManager.hasConsent()||(this.eventQueue=[],this.waitingForConsentQueue=[])}catch(t){let i=this.formatError(t,"revokeConsent");this.logError(i)}}getConsentState(){return this.consentManager.getConsentState()}hasConsent(e){return this.consentManager.hasConsent(e)}onConsentChange(e){this.consentManager.addListener(e)}offConsentChange(e){this.consentManager.removeListener(e)}checkAndInitializeDebugMode(){if(!(typeof window>"u"))try{let e=new URLSearchParams(window.location.search),t=e.get("grain_debug")==="1",i=e.get("grain_session");if(!t||!i)return;this.log("Debug mode detected, verifying session:",i),this.verifyDebugSession(i,window.location.hostname).then(r=>{r?(this.log("Debug session verified, initializing debug agent"),this.isDebugMode=!0,this.initializeDebugAgent(i)):this.log("Debug session verification failed")}).catch(r=>{this.log("Failed to verify debug session:",r)})}catch(e){this.log("Error checking debug mode:",e)}}async verifyDebugSession(e,t){try{let i=`${this.config.apiUrl}/v1/tenant/${encodeURIComponent(this.config.tenantId)}/debug-sessions/verify`,r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,domain:t})});return r.ok?(await r.json()).valid===!0:!1}catch(i){return this.log("Debug session verification error:",i),!1}}initializeDebugAgent(e){if(!(typeof window>"u"))try{this.log("Loading debug agent module"),Promise.resolve().then(()=>(Or(),Lr)).then(({DebugAgent:t})=>{try{this.debugAgent=new t(this,e,this.config.tenantId,this.config.apiUrl,{debug:this.config.debug}),this.log("Debug agent initialized")}catch(i){this.log("Failed to initialize debug agent:",i)}}).catch(t=>{this.log("Failed to load debug agent module:",t)})}catch(t){this.log("Error initializing debug agent:",t)}}destroy(){if(this.isDestroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.stopConfigRefreshTimer(),this.configChangeListeners=[],this.heartbeatManager&&(this.heartbeatManager.destroy(),this.heartbeatManager=null),this.pageTrackingManager&&(this.pageTrackingManager.destroy(),this.pageTrackingManager=null),this.activityDetector&&(this.activityDetector.destroy(),this.activityDetector=null),this.interactionTrackingManager&&(this.interactionTrackingManager.destroy(),this.interactionTrackingManager=null),this.sectionTrackingManager&&(this.sectionTrackingManager.destroy(),this.sectionTrackingManager=null),this.heatmapTrackingManager&&(this.heatmapTrackingManager.destroy(),this.heatmapTrackingManager=null),this.debugAgent&&(this.debugAgent.destroy(),this.debugAgent=null),this.eventQueue.length>0){let e=[...this.eventQueue];this.eventQueue=[];let t=this.chunkEvents(e,this.config.maxEventsPerRequest);if(t.length>0){this.sendEventsWithBeacon(t[0]).catch(()=>{});for(let i=1;i<t.length;i++)this.sendEventsWithBeacon(t[i]).catch(()=>{})}}}};function Nr(n){return new ee(n)}var Ha=ee;typeof window<"u"&&(window.Grain={GrainAnalytics:ee,createGrainAnalytics:Nr});return Fr(Ba);})();
|
|
507
533
|
//# sourceMappingURL=index.global.js.map
|