PageSourceSearch

https://pregonesprtt.org/?grain_tag_script=1

js pregonesprtt.org collected 2026-09-24 09:30:37 UTC 210,363 bytes, 487 lines download raw bytes

1window.__GRAIN_CONFIG__={"tenantId":"pregones-prtt-lii467","apiUrl":"https://clientapis.grainql.com","debug":false,"version":"4.5.1","enableDataLayer":true};
2/* Grain Tag v4.5.1 | MIT License */
3"use strict";var GrainTag=(()=>{var _t=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var gn=Object.getOwnPropertyNames;var mn=Object.prototype.hasOwnProperty;var P=(n,e)=>()=>(n&&(e=n(n=0)),e);var Te=(n,e)=>{for(var t in e)_t(n,t,{get:e[t],enumerable:!0})},yn=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gn(e))!mn.call(n,r)&&r!==t&&_t(n,r,{get:()=>e[r],enumerable:!(i=fn(e,r))||i.enumerable});return n};var vn=n=>yn(_t({},"__esModule",{value:!0}),n);function wn(){return typeof window>"u"?null:window.__GRAIN_CONFIG__??null}function Sn(n){if(!n||typeof n!="string")return!1;let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,t=/^[a-zA-Z0-9_-]{3,64}$/;return e.test(n)||t.test(n)}function Ci(n){let e=wn(),t={...bn,...e&&{tenantId:e.tenantId,apiUrl:e.apiUrl,debug:e.debug,version:e.version,...e.enableDataLayer!=null&&{enableDataLayer:e.enableDataLayer}},...n};if(!Sn(t.tenantId))throw new Error("Grain Tag: Invalid or missing tenantId. Ensure the script is loaded via tag.grainql.com/v4/{tenantId}.js or provide tenantId in config.");return t}function Ei(n){if(typeof window>"u")return!1;if(new URLSearchParams(window.location.search).get("grain_debug")==="1"){try{sessionStorage.setItem("_grain_debug","1")}catch{}return!0}try{if(sessionStorage.getItem("_grain_debug")==="1")return!0}catch{}return n.debug??!1}function ki(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search).get("grain_session");if(e){try{sessionStorage.setItem("_grain_debug_session",e)}catch{}return e}try{return sessionStorage.getItem("_grain_debug_session")}catch{return null}}function _(n,e){return`_grain_${n}_${e}`}var bn,j=P(()=>{"use strict";bn={tenantId:"",apiUrl:"https://clientapis.grainql.com",debug:!1,version:"1.0.0",consentMode:"auto",enablePageViews:!0,enableHeatmaps:!0,enableSnapshots:!0,enableRescue:!0,enableDataLayer:!1,batchSize:50,flushInterval:5e3,retryAttempts:3}});function _i(n){try{let t=new URL(n).searchParams;return{utm_source:t.get("utm_source")||void 0,utm_medium:t.get("utm_medium")||void 0,utm_campaign:t.get("utm_campaign")||void 0,utm_term:t.get("utm_term")||void 0,utm_content:t.get("utm_content")||void 0}}catch{return{}}}function le(){return!It&&typeof window<"u"&&(It=_i(window.location.href)),It||{}}function Ti(n){let e=n.toLowerCase().replace(/\.+$/,"").split(".").filter(Boolean);if(e.length<=2)return e.join(".");let t=e.slice(-2).join(".");return In.has(t)?e.slice(-3).join("."):t}function Mn(n,e){return!n||!e?!1:n===e?!0:Ti(n)===Ti(e)}function ce(n,e){if(!n)return"direct";try{let t=new URL(n),i=new URL(e),r=t.hostname.toLowerCase();if(Mn(r,i.hostname.toLowerCase()))return"direct";let s=i.searchParams;if(_n.some(a=>s.has(a)))return"paid";let o=s.get("utm_medium")?.toLowerCase();return o&&["cpc","ppc","paid","paidsearch","cpm"].includes(o)?"paid":kn.some(a=>r.includes(a))?"organic":xn.some(a=>r.includes(a))?"social":Tn.some(a=>r.includes(a))||o==="email"||o==="e-mail"||o==="newsletter"?"email":"referral"}catch{return"direct"}}function Mt(n){if(typeof localStorage>"u"||typeof window>"u")return null;let e=_(n,"first_touch");try{let t=localStorage.getItem(e);if(t)return JSON.parse(t);let i=document.referrer||"",r=window.location.href,s=_i(r),o=ce(i,r),a="";if(i)try{a=new URL(i).hostname}catch{a=""}let l={source:s.utm_source||(o!=="direct"&&a?a:"direct"),medium:s.utm_medium||o,campaign:s.utm_campaign||"",referrer:i,referrer_category:o,timestamp:Date.now()};return localStorage.setItem(e,JSON.stringify(l)),l}catch{return null}}function Ii(n,e){let{identity:t,consent:i,tenantId:r,disableAutoProperties:s}=e,o=i.hasConsent("analytics"),a=t.getMode()==="cookieless",l={...n.properties};if(a||(l._minimal=!o,l._consent_status=o?"granted":"pending"),!s&&typeof window<"u"){l.device||(l.device=Lt()),l.browser||(l.browser=Dt()),l.os||(l.os=Pt());let c=le();c.utm_source&&(l.utm_source=c.utm_source),c.utm_medium&&(l.utm_medium=c.utm_medium),c.utm_campaign&&(l.utm_campaign=c.utm_campaign),c.utm_term&&(l.utm_term=c.utm_term),c.utm_c
3ontent&&(l.utm_content=c.utm_content);let u=Mt(r);u&&(l.first_touch_source=u.source,l.first_touch_medium=u.medium,l.first_touch_campaign=u.campaign,l.first_touch_referrer_category=u.referrer_category);let h=n.eventName.startsWith("_grain_");!h&&o&&(l.session_id=t.getSessionId()),!h&&e.sentEvents&&(l.occurrence=e.sentEvents.record(n.eventName))}return{eventName:n.eventName,userId:n.userId||t.getUserId(),properties:l}}function H(n){try{let e=new URL(n),t=e.hostname.toLowerCase();t.startsWith("www.")&&(t=t.substring(4));let i=e.pathname;return i.endsWith("/")||(i+="/"),`${t}${i}`}catch{let e=n.trim();return e=e.replace(/^https?:\/\//i,""),e=e.split("?")[0].split("#")[0].trim(),e=e.replace(/^www\./i,""),!e||e==="/"?n:(e.endsWith("/")||(e+="/"),e)}}function Re(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let e=(window.innerWidth||screen?.width||0)<768,t=navigator.userAgent.toLowerCase(),r=["mobile","android","iphone","ipad","ipod","blackberry","windows phone"].some(s=>t.includes(s));return e||r?"mobile":"desktop"}function Lt(){if(typeof window>"u"||typeof navigator>"u")return"Desktop";let n=navigator.userAgent,e=window.innerWidth;return n.includes("iPad")||n.includes("Android")&&!n.includes("Mobile")?"Tablet":n.includes("Mobile")||n.includes("iPhone")||n.includes("Android")||e<768?"Mobile":e<1024?"Tablet":"Desktop"}function Dt(){if(typeof navigator>"u")return"Unknown";let n=navigator.userAgent;return n.includes("Firefox/")?"Firefox":n.includes("Edg/")?"Edge":n.includes("Chrome/")?"Chrome":n.includes("Safari/")&&!n.includes("Chrome/")?"Safari":n.includes("Opera/")||n.includes("OPR/")?"Opera":"Unknown"}function Pt(){if(typeof navigator>"u")return"Unknown";let n=navigator.userAgent;return n.includes("Win")?"Windows":n.includes("Mac")?"macOS":n.includes("Linux")?"Linux":n.includes("Android")?"Android":n.includes("iOS")||n.includes("iPhone")||n.includes("iPad")?"iOS":"Unknown"}var It,kn,xn,Tn,_n,In,X=P(()=>{"use strict";j();It=null;kn=["google","bing","yahoo","duckduckgo","baidu","yandex"],xn=["facebook","twitter","instagram","linkedin","pinterest","tiktok","youtube","reddit"],Tn=["mail.google.com","outlook.","mail.yahoo.","webmail."],_n=["gclid","msclkid","fbclid","ttclid","li_fat_id"],In=new Set(["co.uk","org.uk","me.uk","ac.uk","gov.uk","net.uk","sch.uk","ltd.uk","plc.uk","co.jp","or.jp","ne.jp","ac.jp","go.jp","com.au","net.au","org.au","edu.au","gov.au","id.au","co.nz","net.nz","org.nz","govt.nz","ac.nz","co.za","org.za","web.za","net.za","com.br","net.br","org.br","gov.br","com.cn","net.cn","org.cn","gov.cn","co.in","net.in","org.in","gen.in","firm.in","ind.in","com.mx","com.ar","com.sg","com.hk","com.tw","com.tr","com.ua","com.pl","co.kr","or.kr","co.id","co.th","or.th","co.il","org.il","com.vn"])});function Dn(n){if(n.length<=8||n.includes("-")||n.includes("_"))return!1;let e=/[a-zA-Z]/.test(n),t=/[0-9]/.test(n);return e&&t}function Pn(n){if(!n.classList||n.classList.length===0)return;let e=Array.from(n.classList).filter(t=>!(Ln.test(t)||Dn(t)));return e.length>0?e:void 0}function Rn(n,e){let t=[],i=e,r=[];for(;i&&i!==n;)r.unshift(i),i=i.parentElement;if(r.length>6)return"";for(let s of r){let o=s.parentElement;if(!o)break;let a=s.tagName.toLowerCase(),l=Array.from(o.children).filter(u=>u.tagName===s.tagName),c=l.indexOf(s)+1;t.push(l.length>1?`${a}[${c}]`:a)}return t.join("/")}function On(n){let e=n.parentElement;for(;e&&e!==document.documentElement;){if(e.id){let t=Rn(e,n);if(t)return{ancestorId:e.id,relativePath:t};break}e=e.parentElement}}function K(n){let e=n.tagName.toLowerCase(),t=n.getAttribute("data-grain-id")||void 0,i=n.id||void 0,r=n.getAttribute("data-testid")||void 0,s=n.getAttribute("aria-label")||void 0,o=n.getAttribute("role")||void 0,a=n.getAttribute("name")||void 0,l,c=n.textContent?.trim();c&&(l=c.replace(/\s+/g," ").substring(0,100)||void 0);let u;e==="a"&&(u=n.getAttribute("href")||void 0);let h;(e==="input"||e==="button")&&(h=n.getAttribute("type")||void 0);let p=Pn(n),m=W(n)||void 0,v=ue(n)||void 0,g=On(n),d;try{let S=n.getBoundingClientRect(),T=window.innerWidth,f=window.innerHeight;T>0&&f>0&&S.width>0&&S.height>0&&(d={xPercent:Math.round(S.left/T*1e4)/100,yPercent:Math.round(S.top/f*1e4)/100,widthPercent:Math.round(S.width/T*1e4)/100,heightPercent:Math.round(S.height/f*1e4)/100})}catch{}return{...t&&{grainId:t},...i&&{id:i},...r&&{testId:r},...s&&{ariaLabel:s},...o&&{role:o},...a&&{name:a},tag:e,...l&&{textContent:l},...u&&{href:u},...h&&{type:h},...p&&{classes:p},...m&&{xpath:m}
3,...v&&{css:v},...g&&{nearestIdAncestor:g},...d&&{rect:d}}}var Ln,Ae=P(()=>{"use strict";de();Ln=/^(active|hover|focus|open|closed|selected|disabled|visible|hidden|is-|has-|js-|ng-|css-|sc-|_|svelte-)/});function W(n){if(!n)return"";if(n.id)return`//*[@id="${n.id}"]`;let e=[],t=n;for(;t&&t.nodeType===Node.ELEMENT_NODE;){let i=0,r=t;for(;r;)r=r.previousElementSibling,r&&r.nodeName===t.nodeName&&i++;let s=t.nodeName.toLowerCase(),o=i>0?`[${i+1}]`:"";e.unshift(`${s}${o}`),t=t.parentElement}return e.length?`/${e.join("/")}`:""}function ue(n){if(!n)return"";if(n.id)return`#${n.id}`;let e=Array.from(n.attributes).filter(r=>r.name.startsWith("data-"));if(e.length>0){let r=e[0];return`${n.tagName.toLowerCase()}[${r.name}="${r.value}"]`}if(n.className&&typeof n.className=="string"){let r=n.className.split(" ").filter(s=>s&&!s.match(/^(active|hover|focus)/));if(r.length>0)return`${n.tagName.toLowerCase()}.${r[0]}`}let t=[],i=n;for(;i&&i!==document.body;){let r=i.tagName.toLowerCase();if(i.parentElement){let o=Array.from(i.parentElement.children).filter(a=>a.tagName===i.tagName);if(o.length>1){let a=o.indexOf(i)+1;r+=`:nth-child(${a})`}}if(t.unshift(r),i=i.parentElement,t.length>=5)break}return t.join(" > ")}function Mi(n){return n&&n.trim().replace(/\s+/g," ").substring(0,100)||void 0}var Ne,de=P(()=>{"use strict";X();Ae();Ne=class{constructor(e,t={}){this.isDestroyed=!1;this.pendingClicks=[];this.batchTimer=null;this.clickHistory=[];this.currentScrollState=null;this.maxViewportSection=0;this.pendingScrolls=[];this.scrollDebounceTimer=null;this.scrollTrackingTimer=null;this.periodicScrollTimer=null;this.lastScrollY=0;this.scrollContainer=window;this.isNestedScroll=!1;this.scrollHandler=null;this.clickHandler=null;this.tracker=e,this.config={batchDelay:2e3,maxBatchSize:20,scrollDebounceDelay:100,splitDuration:3e3,debug:!1,...t},this.deviceType=Re(),typeof window<"u"&&this.initialize()}initialize(){this.detectScrollContainer(),this.setupClickTracking(),this.setupScrollTracking(),this.startScrollTracking(),this.setupUnloadHandler(),this.log("Heatmap tracking initialized",{isNestedScroll:this.isNestedScroll,container:this.isNestedScroll?this.scrollContainer.id||"unnamed":"window"})}detectScrollContainer(){let e=document.documentElement.scrollHeight,t=document.documentElement.clientHeight;if(e>t){this.scrollContainer=window,this.isNestedScroll=!1;return}let r=[document.getElementById("pageContent"),document.querySelector("[data-scroll-container]"),document.querySelector(".scroll-container"),document.querySelector(".main-content"),document.querySelector('[role="main"]'),...Array.from(document.querySelectorAll("div, section, main, article")).filter(a=>{let l=a.scrollHeight,c=a.clientHeight;if(!(l>c))return!1;let h=a.getBoundingClientRect(),p=window.getComputedStyle(a);return(p.overflow==="auto"||p.overflow==="scroll"||p.overflowY==="auto"||p.overflowY==="scroll"||l>c*1.5)&&h.height>=window.innerHeight*.5})].filter(a=>a!=null),s=null,o=0;for(let a of r)if(a instanceof HTMLElement){let l=a.scrollHeight,c=a.clientHeight,u=l-c;u>o&&(o=u,s=a)}s?(this.scrollContainer=s,this.isNestedScroll=!0,this.log("Detected nested scroll container:",{id:s.id,className:s.className,scrollHeight:s.scrollHeight,clientHeight:s.clientHeight})):(this.scrollContainer=window,this.isNestedScroll=!1)}getScrollY(){return this.isNestedScroll&&this.scrollContainer instanceof HTMLElement?this.scrollContainer.scrollTop:window.scrollY||window.pageYOffset}getScrollHeight(){return this.isNestedScroll&&this.scrollContainer instanceof HTMLElement?this.scrollContainer.scrollHeight:document.documentElement.scrollHeight}getClientHeight(){return this.isNestedScroll&&this.scrollContainer instanceof HTMLElement?this.scrollContainer.clientHeight:window.innerHeight}setupClickTracking(){this.clickHandler=e=>this.handleClick(e),document.addEventListener("click",this.clickHandler,{passive:!0,capture:!0})}setupScrollTracking(){this.scrollHandler=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.handleScroll(),this.scrollDebounceTimer=null},this.config.scrollDebounceDelay)},this.isNestedScroll&&this.scrollContainer instanceof HTMLElement?this.scrollContainer.addEventListener("scroll",this.scrollHandler,{passive:!0}):window.addEventListener("scroll",this.scrollHandler,{passive:!0})}startScrollTracking(){this.updateScrollState(),this.scrollTrackingTimer=window.setInterval(()=>{this.isDestroyed||this.updateScrollState()},500),this.periodicScrollTimer=window.setInterval(()=>{if(this.isDestroyed||!this.currentScrollState)return;let e=Date.now();if(e-this.currentScrollState.entryTime>
31e3){if(this.shouldSendPeriodicEvent()){let r=this.buildScrollData(e,!0);this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:r.pageUrl,viewport_section:r.viewportSection,scroll_depth_px:r.scrollDepthPx,scroll_depth_percent:r.scrollDepthPercent,duration_ms:r.durationMs,entry_timestamp:r.entryTimestamp,exit_timestamp:r.exitTimestamp,page_height:r.pageHeight,viewport_height:r.viewportHeight,device_type:r.deviceType,is_split:!0,max_viewport_section:r.maxViewportSection,is_nested_scroll:r.isNestedScroll,scroll_container_id:r.scrollContainerId},{flush:!0}),this.currentScrollState.eventCount++}this.currentScrollState.entryTime=e}},this.config.splitDuration)}shouldSendPeriodicEvent(){if(!this.currentScrollState)return!1;if(this.currentScrollState.eventCount<2)return!0;if(typeof document<"u"&&document.visibilityState==="hidden")return this.log("Skipping scroll event: page hidden"),!1;let e=this.getScrollY();return Math.abs(e-this.lastScrollY)<50?(this.log("Skipping scroll event: no significant scroll"),!1):(this.lastScrollY=e,!0)}setupUnloadHandler(){let e=()=>{if(this.currentScrollState){let t=this.buildScrollData(Date.now(),!1);this.pendingScrolls.push(t)}this.flushWithBeacon()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}handleClick(e){if(this.isDestroyed)return;let t=e.target;if(!t)return;let i=H(window.location.href),r=W(t),s=ue(t),o,a;try{let g=t.getBoundingClientRect();g.width>0&&g.height>0&&(o=Math.max(0,Math.min(1,(e.clientX-g.left)/g.width)),a=Math.max(0,Math.min(1,(e.clientY-g.top)/g.height)))}catch{}let l=Math.round(e.pageX),c=Math.round(e.pageY);if(this.isNestedScroll&&this.scrollContainer instanceof HTMLElement){let g=this.scrollContainer.getBoundingClientRect(),d=this.scrollContainer.scrollTop,S=this.scrollContainer.scrollLeft;l=Math.round(S+(e.clientX-g.left)),c=Math.round(d+(e.clientY-g.top))}let u=K(t),h={pageUrl:i,xpath:r,selector:s,fingerprint:JSON.stringify(u),relX:o,relY:a,viewportX:Math.round(e.clientX),viewportY:Math.round(e.clientY),pageX:l,pageY:c,elementTag:t.tagName?.toLowerCase()||"unknown",elementText:Mi(t.textContent),timestamp:Date.now(),deviceType:this.deviceType,isNestedScroll:this.isNestedScroll,scrollContainerId:this.isNestedScroll&&this.scrollContainer instanceof HTMLElement&&this.scrollContainer.id||void 0},p=Date.now();this.clickHistory.push({xpath:r,timestamp:p}),this.clickHistory=this.clickHistory.filter(g=>p-g.timestamp<1e3);let m=this.clickHistory.filter(g=>g.xpath===r).length;m>=3&&(this.tracker.trackSystemEvent("_grain_rage_click",{page_url:i,xpath:r,selector:s,page_x:l,page_y:c,viewport_x:Math.round(e.clientX),viewport_y:Math.round(e.clientY),element_tag:t.tagName?.toLowerCase(),element_text:Mi(t.textContent),click_count:m,window_ms:p-this.clickHistory.filter(g=>g.xpath===r)[0].timestamp,device_type:this.deviceType},{flush:!0}),this.clickHistory=this.clickHistory.filter(g=>g.xpath!==r)),this.isInteractiveElement(t)||this.tracker.trackSystemEvent("_grain_dead_click",{...this.formatClickData(h)}),t instanceof HTMLAnchorElement&&t.href?this.tracker.trackSystemEvent("_grain_heatmap_click",this.formatClickData(h),{flush:!0,transport:"keepalive"}):(this.pendingClicks.push(h),this.considerBatchFlush())}isInteractiveElement(e){let t=["A","BUTTON","INPUT","SELECT","TEXTAREA","DETAILS","SUMMARY"],i=["button","link","tab","menuitem","checkbox","radio","switch"],r=e;for(;r;){if(t.includes(r.tagName)||r.hasAttribute("onclick")||r.hasAttribute("tabindex"))return!0;let s=r.getAttribute("role");if(s&&i.includes(s))return!0;try{if(getComputedStyle(r).cursor==="pointer")return!0}catch{}r=r.parentElement}return!1}handleScroll(){this.isDestroyed||this.updateScrollState()}updateScrollState(){let e=Date.now(),t=this.getScrollY(),i=this.getClientHeight(),r=Math.floor(t/i);if(this.maxViewportSection=Math.max(this.maxViewportSection,r),this.currentScrollState&&this.currentScrollState.viewportSection!==r&&e-this.currentScrollState.entryTime>100){let o=this.buildScrollData(e,!1);this.pendingScrolls.push(o)}(!this.currentScrollState||this.currentScrollState.viewportSection!==r)&&(this.currentScrollState={viewportSection:r,entryTime:e,scrollDepthPx:t,eventCount:0}),this.considerBatchFlush()}buildScrollData(e,t){let i=this.getScrollHeight(),r=this.getClientHeight(),s=this.getScrollY();return{pageUrl:H(window.location.href),scrollDepthPx:s,scrollDepthPercent:Math.round(s/(i-r)*100),viewportSection:this.currentScrollState?.viewportSection||0,durationMs:e-(this.currentScrollState?.entryTime||e),entryTimestamp:this.currentScrollState?.entryTime||e,exitTimestamp:e,pageHeight:i,viewportHe
3ight:r,deviceType:this.deviceType,isSplit:t,maxViewportSection:this.maxViewportSection,isNestedScroll:this.isNestedScroll,scrollContainerId:this.isNestedScroll&&this.scrollContainer instanceof HTMLElement&&this.scrollContainer.id||void 0}}formatClickData(e){return{page_url:e.pageUrl,xpath:e.xpath,selector:e.selector,fingerprint:e.fingerprint,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,device_type:e.deviceType,is_nested_scroll:e.isNestedScroll,scroll_container_id:e.scrollContainerId}}considerBatchFlush(){let e=this.pendingClicks.length+this.pendingScrolls.length;if(e>=this.config.maxBatchSize){this.flushPendingEvents();return}this.batchTimer===null&&e>0&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents(),this.batchTimer=null},this.config.batchDelay))}flushPendingEvents(){if(!this.isDestroyed){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",this.formatClickData(e));this.pendingClicks=[];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,scroll_depth_percent:e.scrollDepthPercent,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight,device_type:e.deviceType,is_split:e.isSplit,max_viewport_section:e.maxViewportSection,is_nested_scroll:e.isNestedScroll,scroll_container_id:e.scrollContainerId});this.pendingScrolls=[],this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null)}}flushWithBeacon(){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",this.formatClickData(e),{flush:!0});this.pendingClicks=[];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,scroll_depth_percent:e.scrollDepthPercent,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight,device_type:e.deviceType,is_split:e.isSplit,max_viewport_section:e.maxViewportSection,is_nested_scroll:e.isNestedScroll,scroll_container_id:e.scrollContainerId},{flush:!0});this.pendingScrolls=[]}log(...e){this.config.debug&&console.log("[Grain Tag Heatmap]",...e)}destroy(){this.isDestroyed=!0,this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler&&(this.isNestedScroll&&this.scrollContainer instanceof HTMLElement?this.scrollContainer.removeEventListener("scroll",this.scrollHandler):window.removeEventListener("scroll",this.scrollHandler),this.scrollHandler=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.scrollTrackingTimer!==null&&(clearInterval(this.scrollTrackingTimer),this.scrollTrackingTimer=null),this.periodicScrollTimer!==null&&(clearInterval(this.periodicScrollTimer),this.periodicScrollTimer=null),this.flushPendingEvents()}}});var en={};Te(en,{IGNORED_NODE:()=>Ut,Mirror:()=>te,absolutifyURLs:()=>fe,adaptCssForReplay:()=>ct,buildNodeWithSN:()=>fi,classMatchesRegex:()=>Ze,cleanupSnapshot:()=>bs,createCache:()=>fa,createMirror:()=>Kn,escapeImportStatement:()=>ir,extractFileExtension:()=>ii,fixSafariColons:()=>nr,genId:()=>fr,getInputType:()=>ur,ignoreAttribute:()=>mr,is2DCanvasBlank:()=>lr,isCSSImportRule:()=>sr,isCSSStyleRule:()=>or,isElement:()=>rt,isNativeShadowDom:()=>qe,isNodeMetaEqual:()=>cr,isShadowRoot:()=>tr,markCssSplits:()=>hr,maskInputValue:()=>ar,needMaskingText:()=>yr,normalizeCssString:()=>Ye,rebuild:()=>wa,serializeNodeWithId:()=>ee,snapshot:()=>ys,splitCssText:()=>dr,stringifyRule:()=>rr,stringifyStylesheet:()=>Ke,toLowerCase:()=>be,transformAttribute:()=>gr,visitSnapshot:()=>vs});function ti(n){if(He[n])return He[n];let e=globalThis[n],t=e.prototype,i=n in Di?Di[n]:void 0,r=!!(i&&i.every(a=>{var l,c;return!!((c=(l=Object.getOwnPropertyDescriptor(t,a))==null?void 0:l.get)!=null&&c.toString().includes("[native code]"))})),s=n in Pi?Pi[n]:void 0,o=!!(s&&s.every(a=>{var l;return typeof t[a]=="function"&&((l=t[a])==null?void 0:l.toString().includes("[native code]"))}));if(r&&o&&!Hn())return He[n]=e.prototype,e.prototype;try{let a=document.createElement("iframe");document.body.appendChild(a);let l=a.contentWindow;if(!l)return e.prototype;let c=l[n].prototype;return document.body.removeChild(a),c?He[n]=c:t}catch{return t}}function B(n,e,t){var i;let r=`${n}.${String(t)}`;if(Rt[r])return Rt[r].call(e);let s=ti(n),o=(i=Object.getOwnPropertyDescriptor(s,t))==null?void 0:i.get;return o?(Rt[r]=o,o.call(e)):e[t]}function er(n,e,t){let i=`${n}.${String(t)}`;if(Ot[i])return Ot[i].bind(e);let s=ti(n)[t];return typeof s!="function"?e[t]:(Ot[i]=s,s.bind(e))}function $n(n){return B("Node",n,"childNodes")}function Un(n){return B("Node",n,"parentNode")}function Fn(n){return B("Node",n,"parentElement")}function zn(n){return B("Node",n,"textContent")}function Bn(n,e){return er("Node",n,"contains")(e)}function jn(n){return er("Node",n,"getRootNode")()}function Wn(n){return!n||!("host"in n)?null:B("ShadowRoot",n,"host")}function Vn(n){return n.styleSheets}function Gn(n){return!n||!("shadowRoot"in n)?null:B("Element",n,"shadowRoot")}function qn(n,e){return B("Element",n,"querySelector")(e)}function Yn(n,e){return B("Element",n,"querySelectorAll")(e)}function Jn(){return ti("MutationObserver").constructor}function rt(n){return n.nodeType===n.ELEMENT_NODE}function tr(n){let e=n&&"host"in n&&"mode"in n&&I.host(n)||null;return!!(e&&"shadowRoot"in e&&I.shadowRoot(e)===n)}function qe(n){return Object.prototype.toString.call(n)==="[object ShadowRoot]"}function Xn(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 ir(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 Ke(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=>rr(r,t)).join("");return Xn(i)}catch{return null}}function rr(n,e){if(sr(n)){let t;try{t=Ke(n.styleSheet)||ir(n)}catch{t=n.cssText}return n.styleSheet.href?fe(t,n.styleSheet.href):t}else{let t=n.cssText;return or(n)&&n.selectorText.includes(":")&&(t=nr(t)),e?fe(t,e):t}}function nr(n){let e=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return n.replace(e,"$1\\$2")}function sr(n){return"styleSheet"in n}function or(n){return"selectorText"in n}function Kn(){return new te}function ar({element:n,maskInputOptions:e,tagName:t,type:i,value:r,maskInputFn:s}){let o=r||"",a=i&&be(i);
vendor: 7,592 bytes, line 3
3return(e[t.toLowerCase()]||a&&e[a])&&(s?o=s(o,n):o="*".repeat(o.length)),o}function be(n){return n.toLowerCase()}function lr(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,o=Ri in s?s[Ri]:s;if(new Uint32Array(o.call(e,i,r,Math.min(t,n.width-i),Math.min(t,n.height-r)).data.buffer).some(l=>l!==0))return!1}return!0}function cr(n,e){return!n||!e||n.type!==e.type?!1:n.type===y.Document?n.compatMode===e.compatMode:n.type===y.DocumentType?n.name===e.name&&n.publicId===e.publicId&&n.systemId===e.systemId:n.type===y.Comment||n.type===y.Text||n.type===y.CDATA?n.textContent===e.textContent:n.type===y.Element?n.tagName===e.tagName&&JSON.stringify(n.attributes)===JSON.stringify(e.attributes)&&n.isSVG===e.isSVG&&n.needBlock===e.needBlock:!1}function ur(n){let e=n.type;return n.hasAttribute("data-rr-is-password")?"password":e?be(e):null}function ii(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 Zn(n){let e="";return n.indexOf("//")>-1?e=n.split("/").slice(0,3).join("/"):e=n.split("/")[0],e=e.split("?")[0],e}function fe(n,e){return(n||"").replace(Qn,(t,i,r,s,o,a)=>{let l=r||o||a,c=i||s||"";if(!l)return t;if(es.test(l)||ts.test(l))return`url(${c}${l}${c})`;if(is.test(l))return`url(${c}${l}${c})`;if(l[0]==="/")return`url(${c}${Zn(e)+l}${c})`;let u=e.split("/"),h=l.split("/");u.pop();for(let p of h)p!=="."&&(p===".."?u.pop():u.push(p));return`url(${c}${u.join("/")}${c})`})}function Ye(n){return n.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"")}function dr(n,e){let t=Array.from(e.childNodes),i=[];if(t.length>1&&n&&typeof n=="string"){let r=Ye(n);for(let s=1;s<t.length;s++)if(t[s].textContent&&typeof t[s].textContent=="string"){let o=Ye(t[s].textContent);for(let a=3;a<o.length;a++){let l=o.substring(0,a);if(r.split(l).length===2){let c=r.indexOf(l);for(let u=c;u<n.length;u++)if(Ye(n.substring(0,u)).length===c){i.push(n.substring(0,u)),n=n.substring(u);break}break}}}}return i.push(n),i}function hr(n,e){return dr(n,e).join("/* rr_split */")}function fr(){return pr++}function ns(n){if(n instanceof HTMLFormElement)return"form";let e=be(n.tagName);return rs.test(e)?"div":e}function as(n,e){if(e.trim()==="")return e;let t=0;function i(s){let o,a=s.exec(e.substring(t));return a?(o=a[0],t+=o.length,o):""}let r=[];for(;i(os),!(t>=e.length);){let s=i(ss);if(s.slice(-1)===",")s=Q(n,s.substring(0,s.length-1)),r.push(s);else{let o="";s=Q(n,s);let a=!1;for(;;){let l=e.charAt(t);if(l===""){r.push((s+o).trim());break}else if(a)l===")"&&(a=!1);else if(l===","){t+=1,r.push((s+o).trim());break}else l==="("&&(a=!0);o+=l,t+=1}}}return r.join(", ")}function Q(n,e){return!e||e.trim()===""?e:ri(n,e)}function ls(n){return!!(n.tagName==="svg"||n.ownerSVGElement)}function ri(n,e){let t=Ai.get(n);if(t||(t=n.createElement("a"),Ai.set(n,t)),!e)e="";else if(e.startsWith("blob:")||e.startsWith("data:"))return e;return t.setAttribute("href",e),t.href}function gr(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"?as(n,i):t==="style"?fe(i,ri(n)):e==="object"&&t==="data"?Q(n,i):i)}function mr(n,e,t){return(n==="video"||n==="audio")&&e==="autoplay"}function cs(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 Ze(n,e,t){if(!n)return!1;if(n.nodeType!==n.ELEMENT_NODE)return t?Ze(I.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?Ze(I.parentNode(n),e,t):!1}function yr(n,e,t,i){let r;if(rt(n)){if(r=n,!I.childNodes(r).length)return!1}else{if(I.parentElement(n)===null)return!1;r=I.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(Ze(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 us(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 a=setTimeout(()=>{r||(e(),r=!0)},t);n.addEventListener("load",()=>{clearTimeout(a),r=!0,e()});return}let o="about:blank";if(i.location.href!==o||n.src===o||n.src==="")return setTimeout(e,0),n.addEventListener("load",e);n.addEventListener("load",e)}function ds(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 hs(n,e){let{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:o,inlineStylesheet:a,maskInputOptions:l={},maskTextFn:c,maskInputFn:u,dataURLOptions:h={},inlineImages:p,recordCanvas:m,keepIframeSrcFn:v,newlyAddedElement:g=!1,cssCaptured:d=!1}=e,S=ps(t,i);switch(n.nodeType){case n.DOCUMENT_NODE:return n.compatMode!=="CSS1Compat"?{type:y.Document,childNodes:[],compatMode:n.compatMode}:{type:y.Document,childNodes:[]};case n.DOCUMENT_TYPE_NODE:return{type:y.DocumentType,name:n.name,publicId:n.publicId,systemId:n.systemId,rootId:S};case n.ELEMENT_NODE:return gs(n,{doc:t,blockClass:r,blockSelector:s,inlineStylesheet:a,maskInputOptions:l,maskInputFn:u,dataURLOptions:h,inlineImages:p,recordCanvas:m,keepIframeSrcFn:v,newlyAddedElement:g,rootId:S});case n.TEXT_NODE:return fs(n,{doc:t,needsMask:o,maskTextFn:c,rootId:S,cssCaptured:d});case n.CDATA_SECTION_NODE:return{type:y.CDATA,textContent:"",rootId:S};case n.COMMENT_NODE:return{type:y.Comment,textContent:I.textContent(n)||"",rootId:S};default:return!1}}function ps(n,e){if(!e.hasNode(n))return;let t=e.getId(n);return t===1?void 0:t}function fs(n,e){let{needsMask:t,maskTextFn:i,rootId:r,cssCaptured:s}=e,o=I.parentNode(n),a=o&&o.tagName,l="",c=a==="STYLE"?!0:void 0,u=a==="SCRIPT"?!0:void 0;return u?l="SCRIPT_PLACEHOLDER":s||(l=I.textContent(n),c&&l&&(l=fe(l,ri(e.doc)))),!c&&!u&&l&&t&&(l=i?i(l,I.parentElement(n)):l.replace(/[\S]/g,"*")),{type:y.Text,textContent:l||"",rootId:r}}function gs(n,e){let{doc:t,blockClass:i,blockSelector:r,inlineStylesheet:s,maskInputOptions:o={},maskInputFn:a,dataURLOptions:l={},inlineImages:c,recordCanvas:u,keepIframeSrcFn:h,newlyAddedElement:p=!1,rootId:m}=e,v=cs(n,i,r),g=ns(n),d={},S=n.attributes.length;for(let f=0;f<S;f++){let b=n.attributes[f];mr(g,b.name,b.value)||(d[b.name]=gr(t,g,be(b.name),b.value))}if(g==="link"&&s){let f=Array.from(t.styleSheets).find(M=>M.href===n.href),b=null;f&&(b=Ke(f)),b&&(delete d.rel,delete d.href,d._cssText=b)}if(g==="style"&&n.sheet){let f=Ke(n.sheet);f&&(n.childNodes.length>1&&(f=hr(f,n)),d._cssText=f)}if(g==="input"||g==="textarea"||g==="select"){let f=n.value,b=n.checked;d.type!=="radio"&&d.type!=="checkbox"&&d.type!=="submit"&&d.type!=="button"&&f?d.value=ar({element:n,type:ur(n),tagName:g,value:f,maskInputOptions:o,maskInputFn:a}):b&&(d.checked=b)}if(g==="option"&&(n.selected&&!o.select?d.selected=!0:delete d.selected),g==="dialog"&&n.open&&(d.rr_open_mode=n.matches("dialog:modal")?"modal":"non-modal"),g==="canvas"&&u){if(n.__context==="2d")lr(n)||(d.rr_dataURL=n.toDataURL(l.type,l.quality));else if(!("__context"in n)){let f=n.toDataURL(l.type,l.quality),b=t.createElement("canvas");b.width=n.width,b.height=n.height;let M=b.toDataURL(l.type,l.quality);f!==M&&(d.rr_dataURL=f)}}if(g==="img"&&c){Z||(Z=t.createElement("canvas"),Oi=Z.getContext("2d"));let f=n,b=f.currentSrc||f.getAttribute("src")||"<unknown-src>",M=f.crossOrigin,D=()=>{f.removeEventListener("load",D);
vendor: 4,374 bytes, line 3
3try{Z.width=f.naturalWidth,Z.height=f.naturalHeight,Oi.drawImage(f,0,0),d.rr_dataURL=Z.toDataURL(l.type,l.quality)}catch(q){if(f.crossOrigin!=="anonymous"){f.crossOrigin="anonymous",f.complete&&f.naturalWidth!==0?D():f.addEventListener("load",D);return}else console.warn(`Cannot inline img src=${b}! Error: ${q}`)}f.crossOrigin==="anonymous"&&(M?d.crossOrigin=M:f.removeAttribute("crossorigin"))};f.complete&&f.naturalWidth!==0?D():f.addEventListener("load",D)}if(g==="audio"||g==="video"){let f=d;f.rr_mediaState=n.paused?"paused":"played",f.rr_mediaCurrentTime=n.currentTime,f.rr_mediaPlaybackRate=n.playbackRate,f.rr_mediaMuted=n.muted,f.rr_mediaLoop=n.loop,f.rr_mediaVolume=n.volume}if(p||(n.scrollLeft&&(d.rr_scrollLeft=n.scrollLeft),n.scrollTop&&(d.rr_scrollTop=n.scrollTop)),v){let{width:f,height:b}=n.getBoundingClientRect();d={class:d.class,rr_width:`${f}px`,rr_height:`${b}px`}}g==="iframe"&&!h(d.src)&&(n.contentDocument||(d.rr_src=d.src),delete d.src);let T;try{customElements.get(g)&&(T=!0)}catch{}return{type:y.Element,tagName:g,attributes:d,childNodes:[],isSVG:ls(n)||void 0,needBlock:v,rootId:m,isCustom:T}}function E(n){return n==null?"":n.toLowerCase()}function ms(n,e){if(e.comment&&n.type===y.Comment)return!0;if(n.type===y.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"&&ii(n.attributes.href)==="js"))return!0;if(e.headFavicon&&(n.tagName==="link"&&n.attributes.rel==="shortcut icon"||n.tagName==="meta"&&(E(n.attributes.name).match(/^msapplication-tile(image|color)$/)||E(n.attributes.name)==="application-name"||E(n.attributes.rel)==="icon"||E(n.attributes.rel)==="apple-touch-icon"||E(n.attributes.rel)==="shortcut icon")))return!0;if(n.tagName==="meta"){if(e.headMetaDescKeywords&&E(n.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(E(n.attributes.property).match(/^(og|twitter|fb):/)||E(n.attributes.name).match(/^(og|twitter):/)||E(n.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(E(n.attributes.name)==="robots"||E(n.attributes.name)==="googlebot"||E(n.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&n.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(E(n.attributes.name)==="author"||E(n.attributes.name)==="generator"||E(n.attributes.name)==="framework"||E(n.attributes.name)==="publisher"||E(n.attributes.name)==="progid"||E(n.attributes.property).match(/^article:/)||E(n.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(E(n.attributes.name)==="google-site-verification"||E(n.attributes.name)==="yandex-verification"||E(n.attributes.name)==="csrf-token"||E(n.attributes.name)==="p:domain_verify"||E(n.attributes.name)==="verify-v1"||E(n.attributes.name)==="verification"||E(n.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function ee(n,e){let{doc:t,mirror:i,blockClass:r,blockSelector:s,maskTextClass:o,maskTextSelector:a,skipChild:l=!1,inlineStylesheet:c=!0,maskInputOptions:u={},maskTextFn:h,maskInputFn:p,slimDOMOptions:m,dataURLOptions:v={},inlineImages:g=!1,recordCanvas:d=!1,onSerialize:S,onIframeLoad:T,iframeLoadTimeout:f=5e3,onStylesheetLoad:b,stylesheetLoadTimeout:M=5e3,keepIframeSrcFn:D=()=>!1,newlyAddedElement:q=!1,cssCaptured:F=!1}=e,{needsMask:R}=e,{preserveWhiteSpace:z=!0}=e;R||(R=yr(n,o,a,R===void 0));let se=hs(n,{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:R,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,dataURLOptions:v,inlineImages:g,recordCanvas:d,keepIframeSrcFn:D,newlyAddedElement:q,cssCaptured:F});if(!se)return console.warn(n,"not serialized"),null;let oe;i.hasNode(n)?oe=i.getId(n):ms(se,m)||!z&&se.type===y.Text&&!se.textContent.replace(/^\s+|\s+$/gm,"").length?oe=Ut:oe=fr();let C=Object.assign(se,{id:oe});if(i.add(n,C),oe===Ut)return null;S&&S(n);let kt=!l;if(C.type===y.Element){kt=kt&&!C.needBlock,delete C.needBlock;let L=I.shadowRoot(n);L&&qe(L)&&(C.isShadowHost=!0)}if((C.type===y.Document||C.type===y.Element)&&kt){m.headWhitespace&&C.type===y.Element&&C.tagName==="head"&&(z=!1);let L={doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:R,maskTextClass:o,maskTextSelector:a,skipChild:l,inlineStylesheet:c,maskInputOptions:u,maskTextFn:
vendor: 5,018 bytes, line 3
3h,maskInputFn:p,slimDOMOptions:m,dataURLOptions:v,inlineImages:g,recordCanvas:d,preserveWhiteSpace:z,onSerialize:S,onIframeLoad:T,iframeLoadTimeout:f,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:D,cssCaptured:!1};if(!(C.type===y.Element&&C.tagName==="textarea"&&C.attributes.value!==void 0)){C.type===y.Element&&C.attributes._cssText!==void 0&&typeof C.attributes._cssText=="string"&&(L.cssCaptured=!0);for(let Tt of Array.from(I.childNodes(n))){let J=ee(Tt,L);J&&C.childNodes.push(J)}}let Y=null;if(rt(n)&&(Y=I.shadowRoot(n)))for(let Tt of Array.from(I.childNodes(Y))){let J=ee(Tt,L);J&&(qe(Y)&&(J.isShadow=!0),C.childNodes.push(J))}}let xt=I.parentNode(n);return xt&&tr(xt)&&qe(xt)&&(C.isShadow=!0),C.type===y.Element&&C.tagName==="iframe"&&us(n,()=>{let L=n.contentDocument;if(L&&T){let Y=ee(L,{doc:L,mirror:i,blockClass:r,blockSelector:s,needsMask:R,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:m,dataURLOptions:v,inlineImages:g,recordCanvas:d,preserveWhiteSpace:z,onSerialize:S,onIframeLoad:T,iframeLoadTimeout:f,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:D});Y&&T(n,Y)}},f),C.type===y.Element&&C.tagName==="link"&&typeof C.attributes.rel=="string"&&(C.attributes.rel==="stylesheet"||C.attributes.rel==="preload"&&typeof C.attributes.href=="string"&&ii(C.attributes.href)==="css")&&ds(n,()=>{if(b){let L=ee(n,{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:R,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:m,dataURLOptions:v,inlineImages:g,recordCanvas:d,preserveWhiteSpace:z,onSerialize:S,onIframeLoad:T,iframeLoadTimeout:f,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:D});L&&b(n,L)}},M),C}function ys(n,e){let{mirror:t=new te,blockClass:i="rr-block",blockSelector:r=null,maskTextClass:s="rr-mask",maskTextSelector:o=null,inlineStylesheet:a=!0,inlineImages:l=!1,recordCanvas:c=!1,maskAllInputs:u=!1,maskTextFn:h,maskInputFn:p,slimDOM:m=!1,dataURLOptions:v,preserveWhiteSpace:g,onSerialize:d,onIframeLoad:S,iframeLoadTimeout:T,onStylesheetLoad:f,stylesheetLoadTimeout:b,keepIframeSrcFn:M=()=>!1}=e||{};return ee(n,{doc:n,mirror:t,blockClass:i,blockSelector:r,maskTextClass:s,maskTextSelector:o,skipChild:!1,inlineStylesheet:a,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:h,maskInputFn:p,slimDOMOptions:m===!0||m==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:m==="all",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:m===!1?{}:m,dataURLOptions:v,inlineImages:l,recordCanvas:c,preserveWhiteSpace:g,onSerialize:d,onIframeLoad:S,iframeLoadTimeout:T,onStylesheetLoad:f,stylesheetLoadTimeout:b,keepIframeSrcFn:M,newlyAddedElement:!1})}function vs(n,e){function t(i){e(i),(i.type===y.Document||i.type===y.Element)&&i.childNodes.forEach(t)}t(n)}function bs(){pr=1}function Es(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function ks(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 Is(n){return n[0].toUpperCase()+n.slice(1)}function Bt(n,e){new Ms(e).stringify(n)}function jt(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(o=>jt(o,t)):(s==="object"&&r!==null&&(r=jt(r)),t[i]=r)}return t}function Bs(n){return Buffer?Buffer.from(n,"base64").toString():window.atob(n)}function Rr(n){return n.map(e=>(e.nodes&&(e.nodes=Rr(e.nodes)),delete e.source,e))}function Or(n){if(n[_r]=!1,n.proxyOf.nodes)for(let e of n.proxyOf.nodes)Or(e)}function So(n){for(let e=n.length-1;e>=0;e--){let t=n[e],i=t[3]||t[2];if(i)return i}}function it(n,e){let t=new To(n,e),i=new xo(t);try{i.parse()}catch(r){throw r}return i.root}function pe(n){return typeof n=="object"&&typeof n.then=="function"}function Vr(n){let e=!1,t=Oo[n.type];return n.type==="decl"?e=n.prop.toLowerCase():n.type==="atrule"&&(e=n.name.toLowerCase()),e&&n.append?[t,t+"-"+e,re,t+"Exit",t+"Exit-"+e]:e?[t,t+"-"+e,t+"Exit",t+"Exit-"+e]:n.append?[t,re,t+"Exit"]:[t,t+"Exit"]}function Zi(n){let e;return n.type==="document"?e=["Document",re,"DocumentExit"]:n.type==="root"?e=["Root",re,"RootExit"]:e=Vr(n),{eventIndex:0,events:e,iterator:0,node:n,visitorIndex:0,visitors:[]}}
3function Zt(n){return n[N]=!1,n.nodes&&n.nodes.forEach(e=>Zt(e)),n}function ve(n,e){if(Array.isArray(n))return n.map(r=>ve(r));let{inputs:t,...i}=n;if(t){e=[];for(let r of t){let s={...r,__proto__:Ko.prototype};s.map&&(s.map={...s.map,__proto__:Yo.prototype}),e.push(s)}}if(i.nodes&&(i.nodes=n.nodes.map(r=>ve(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 Zo(i);if(i.type==="decl")return new qo(i);if(i.type==="rule")return new Qo(i);if(i.type==="comment")return new Jo(i);if(i.type==="atrule")return new Xo(i);throw new Error("Unknown node type: "+n.type)}function w(...n){return n.length===1&&Array.isArray(n[0])&&(n=n[0]),new pi(n)}function pa(n){let e=Qi[n.tagName]?Qi[n.tagName]:n.tagName;return e==="link"&&n.attributes._cssText&&(e="style"),e}function ct(n,e){let t=e?.stylesWithHoverClass.get(n);if(t)return t;let r=x([Ss,Cs]).process(n).css;return e?.stylesWithHoverClass.set(n,r),r}function fa(){return{stylesWithHoverClass:new Map}}function ga(n,e,t,i){let r=[];for(let o of n.childNodes)o.type===y.Text&&r.push(o);let s=e.split("/* rr_split */");for(;s.length>1&&s.length>r.length;)s.splice(-2,2,s.slice(-2).join(""));for(let o=0;o<r.length;o++){let a=r[o],l=s[o];a&&l&&(a.textContent=t?ct(l,i):l)}}function ma(n,e,t,i){let{doc:r,hackCss:s,cache:o}=i;n.childNodes.length?ga(n,t,s,o):(s&&(t=ct(t,o)),e.appendChild(r.createTextNode(t)))}function ya(n,e){var t;let{doc:i,hackCss:r,cache:s}=e;switch(n.type){case y.Document:return i.implementation.createDocument(null,"",null);case y.DocumentType:return i.implementation.createDocumentType(n.name||"html",n.publicId,n.systemId);case y.Element:{let o=pa(n),a;n.isSVG?a=i.createElementNS("http://www.w3.org/2000/svg",o):(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{}),a=i.createElement(o));let l={};for(let c in n.attributes){if(!Object.prototype.hasOwnProperty.call(n.attributes,c))continue;let u=n.attributes[c];if(!(o==="option"&&c==="selected"&&u===!1)&&u!==null){if(u===!0&&(u=""),c.startsWith("rr_")){l[c]=u;continue}if(typeof u=="string"){if(o==="style"&&c==="_cssText"){ma(n,a,u,e);continue}else if(o==="textarea"&&c==="value"){a.appendChild(i.createTextNode(u)),n.childNodes=[];continue}}try{if(n.isSVG&&c==="xlink:href")a.setAttributeNS("http://www.w3.org/1999/xlink",c,u.toString());else if(c==="onload"||c==="onclick"||c.substring(0,7)==="onmouse")a.setAttribute("_"+c,u.toString());else if(o==="meta"&&n.attributes["http-equiv"]==="Content-Security-Policy"&&c==="content"){a.setAttribute("csp-content",u.toString());continue}else o==="link"&&(n.attributes.rel==="preload"||n.attributes.rel==="modulepreload")&&n.attributes.as==="script"||o==="link"&&n.attributes.rel==="prefetch"&&typeof n.attributes.href=="string"&&n.attributes.href.endsWith(".js")||(o==="img"&&n.attributes.srcset&&n.attributes.rr_dataURL?a.setAttribute("rrweb-original-srcset",n.attributes.srcset):a.setAttribute(c,u.toString()))}catch{}}}for(let c in l){let u=l[c];if(o==="canvas"&&c==="rr_dataURL"){let h=i.createElement("img");h.onload=()=>{let p=a.getContext("2d");p&&p.drawImage(h,0,0,h.width,h.height)},h.src=u.toString(),a.RRNodeType&&(a.rr_dataURL=u.toString())}else if(o==="img"&&c==="rr_dataURL"){let h=a;h.currentSrc.startsWith("data:")||(h.setAttribute("rrweb-original-src",n.attributes.src),h.src=u.toString())}if(c==="rr_width")a.style.setProperty("width",u.toString());else if(c==="rr_height")a.style.setProperty("height",u.toString());else if(c==="rr_mediaCurrentTime"&&typeof u=="number")a.currentTime=u;else if(c==="rr_mediaState")switch(u){case"played":a.play().catch(h=>console.warn("media playback error",h));break;case"paused":a.pause();break}else c==="rr_mediaPlaybackRate"&&typeof u=="number"?a.playbackRate=u:c==="rr_mediaMuted"&&typeof u=="boolean"?a.muted=u:c==="rr_mediaLoop"&&typeof u=="boolean"?a.loop=u:c==="rr_mediaVolume"&&typeof u=="number"?a.volume=u:c==="rr_open_mode"&&a.setAttribute("rr_open_mode",u)}if(n.isShadowHost)if(!a.shadowRoot)a.attachShadow({mode:"open"});else for(;a.shadowRoot.firstChild;)a.shadowRoot.removeChild(a.shadowRoot.firstChild);return a}case y.Text:return n.isStyle&&r?i.createTextNode(ct(n.textContent,s)):i.createTextNode(n.textContent);case y.CDATA:return i.createCDATASection(n.textContent);case y.Comment:return i.createComment(n.textContent);default:return null}}function fi(n,e){let{doc:t,mirror:i,skipChild:r=!1,hackCss:s=!0,afterAppend:o,cache:a}=e;if(i.has(n.id)){let c=i.getNode(n.id),u=i.getMeta(c);if(cr(u,n))return i.getNode(n.id)}let l=ya(n,{doc:t,hackCss:s,cache:a});if(!l)return null;if(n.rootId&&i.getNode(n.rootId)!==t&&i.replace(n.rootId,t),n.type===y.Document&&(t.close(),t.open(),n.compatMode==="BackCompat"&&n.childNodes&&n.childNodes[0].type!==y.DocumentType&&(n.childNodes[0].type===y.Element&&"xmlns"in n.childNodes[0].attributes&&n.childNodes[0].attributes.xmlns==="http://www.w3.org/1999/xhtml"?t.write('
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">'):t.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "">')),l=t),i.add(l,n),(n.type===y.Document||n.type===y.Element)&&!r)for(let c of n.childNodes){let u=fi(c,{doc:t,mirror:i,skipChild:!1,hackCss:s,afterAppend:o,cache:a});if(!u){console.warn("Failed to rebuild",c);continue}if(c.isShadow&&rt(l)&&l.shadowRoot)l.shadowRoot.appendChild(u);else if(n.type===y.Document&&c.type==y.Element){let h=u,p=null;h.childNodes.forEach(m=>{m.nodeName==="BODY"&&(p=m)}),p?(h.removeChild(p),l.appendChild(u),h.appendChild(p)):l.appendChild(u)}else l.appendChild(u);o&&o(u,c.id)}return l}function va(n,e){function t(i){e(i)}for(let i of n.getIds())n.has(i)&&t(n.getNode(i))}function ba(n,e){let t=e.getMeta(n);if(t?.type!==y.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 wa(n,e){let{doc:t,onVisit:i,hackCss:r=!0,afterAppend:s,cache:o,mirror:a=new te}=e,l=fi(n,{doc:t,mirror:a,skipChild:!1,hackCss:r,afterAppend:s,cache:o});return va(a,c=>{i&&i(c),ba(c,a)}),l}var An,Nn,Li,y,Di,Pi,He,Hn,Rt,Ot,I,te,Ri,Qn,es,ts,is,pr,rs,Ut,Z,Oi,ss,os,Ai,ws,Ni,Ss,Cs,ni,k,vr,xs,Ts,_s,O,Hi,$i,Ft,si,we,Ui,zt,wr,Ms,nt,$e,Ls,Ds,Ps,Rs,Wt,st,Os,Vt,ot,As,Ns,Hs,$s,Fi,zi,Us,Fs,At,zs,Gt,Sr,js,Ws,Bi,Ue,qt,Yt,Vs,Nt,ji,Gs,Ht,qs,Wi,Qe,at,Cr,Je,Xe,Er,kr,xr,Vi,Ys,Js,Xs,Ks,Tr,Zs,Jt,lt,_r,Ir,Mr,Lr,Qs,Dr,oi,ai,Pr,$,V,eo,Nr,Hr,ge,li,Xt,$r,to,Kt,ci,$t,Gi,Fe,qi,ze,he,Be,je,We,io,ro,no,so,oo,ao,lo,co,uo,ho,Ve,Ge,po,Yi,fo,Ur,et,ui,Fr,zr,Br,ie,Se,me,jr,Wr,go,tt,di,mo,yo,vo,bo,wo,Ji,Xi,Co,Eo,ko,xo,To,hi,N,_o,Io,Mo,Lo,Do,Ki,Po,Ro,Oo,Ao,No,re,Qt,ne,qr,Ho,$o,Uo,Fo,ei,zo,Bo,jo,Wo,Vo,ye,Go,qo,Yo,Jo,Xo,Ko,Zo,Qo,ea,ta,Yr,ia,ra,pi,na,sa,Jr,oa,Xr,Kr,aa,la,ca,ua,Zr,Qr,da,ha,x,Qi,tn=P(()=>{An=Object.defineProperty,Nn=(n,e,t)=>e in n?An(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Li=(n,e,t)=>Nn(n,typeof e!="symbol"?e+"":e,t),y=(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))(y||{}),Di={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Pi={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},He={},Hn=()=>!!globalThis.Zone;Rt={};Ot={};I={childNodes:$n,parentNode:Un,parentElement:Fn,textContent:zn,contains:Bn,getRootNode:jn,host:Wn,styleSheets:Vn,shadowRoot:Gn,querySelector:qn,querySelectorAll:Yn,mutationObserver:Jn};te=class{constructor(){Li(this,"idNodeMap",new Map),Li(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}};Ri="__rrweb_original__";Qn=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,es=/^(?:[a-z+]+:)?\/\//i,ts=/^www\..*/i,is=/^(data:)([^,]*),(.*)/i;pr=1,rs=new RegExp("[^a-z0-9-_:]"),Ut=-2;ss=/^[^ \t\n\r\u000c]+/,os=/^[, \t\n\r\u000c]+/;Ai=new WeakMap;ws=/(max|min)-device-(width|height)/,Ni=new RegExp(ws.source,"g"),Ss={postcssPlugin:"postcss-custom-selectors",prepare(){return{postcssPlugin:"postcss-custom-selectors",AtRule:function(n){n.params.match(Ni)&&(n.params=n.params.replace(Ni,"$1-$2"))}}}},Cs={postcssPlugin:"postcss-hover-classes",prepare:function(){let n=[];return{Rule:function(e){n.indexOf(e)===-1&&(n.push(e),e.selectors.forEac
vendor: 6,871 bytes, lines 3-20
3h(function(t){t.includes(":hover")&&(e.selector+=`,
4`+t.replace(/:hover/g,".\\:hover"))}))}}}};ni={exports:{}},k=String,vr=function(){return{isColorSupported:!1,reset:k,bold:k,dim:k,italic:k,underline:k,inverse:k,hidden:k,strikethrough:k,black:k,red:k,green:k,yellow:k,blue:k,magenta:k,cyan:k,white:k,gray:k,bgBlack:k,bgRed:k,bgGreen:k,bgYellow:k,bgBlue:k,bgMagenta:k,bgCyan:k,bgWhite:k}};ni.exports=vr();ni.exports.createColors=vr;xs=ni.exports,Ts={},_s=Object.freeze(Object.defineProperty({__proto__:null,default:Ts},Symbol.toStringTag,{value:"Module"})),O=ks(_s),Hi=xs,$i=O,Ft=class br extends Error{constructor(e,t,i,r,s,o){super(e),this.name="CssSyntaxError",this.reason=e,s&&(this.file=s),r&&(this.source=r),o&&(this.plugin=o),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,br)}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=Hi.isColorSupported),$i&&e&&(t=$i(t));let i=t.split(/\r?\n/),r=Math.max(this.line-3,0),s=Math.min(this.line+2,i.length),o=String(s).length,a,l;if(e){let{bold:c,gray:u,red:h}=Hi.createColors(!0);a=p=>c(h(p)),l=p=>u(p)}else a=l=c=>c;return i.slice(r,s).map((c,u)=>{let h=r+1+u,p=" "+(" "+h).slice(-o)+" | ";if(h===this.line){let m=l(p.replace(/\d/g," "))+c.slice(0,this.column-1).replace(/[^\t]/g," ");return a(">")+l(p)+c+`
5 `+m+a("^")}return" "+l(p)+c}).join(`
6`)}toString(){let e=this.showSourceCode();return e&&(e=`
7
8`+e+`
9`),this.name+": "+this.message+e}},si=Ft;Ft.default=Ft;we={};we.isClean=Symbol("isClean");we.my=Symbol("my");Ui={after:`
10`,beforeClose:`
11`,beforeComment:`
12`,beforeDecl:`
13`,beforeOpen:" ",beforeRule:`
14`,colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:"    ",semicolon:!1};zt=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(`
15`)){let o=this.raw(e,null,"indent");if(o.length)for(let a=0;a<s;a++)i+=o}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],o=this.raw(s,"before");o&&this.builder(o),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 Ui[i];let o=e.root();if(o.rawCache||(o.rawCache={}),typeof o.rawCache[i]<"u")return o.rawCache[i];if(i==="before"||i==="after")return this.beforeAfter(e,i);{let a="raw"+Is(i);this[a]?r=this[a](o,e):o.walk(l=>{if(r=l.raws[t],typeof r<"u")return!1})}return typeof r>"u"&&(r=Ui[i]),o.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(`
16`)&&(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(`
17`)&&(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(`
18`)&&(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(`
19`)&&(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(`
20`);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)}},wr=zt;zt.default=zt;Ms=wr;nt=Bt;Bt.default=Bt;({isClean:$e,my:Ls}=we),Ds=si,Ps=wr,Rs=nt;Wt=class{constructor(e={}){this.raws={},this[$e]=!1,this[Ls]=!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=jt(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}
vendor: 5,694 bytes, lines 20-21
20error(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 Ds(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[$e]){this[$e]=!1;let e=this;for(;e=e.parent;)e[$e]=!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 o=0;o<e;o++)i[o]===`
21`?(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 Ps().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 o in this){if(!Object.prototype.hasOwnProperty.call(this,o)||o==="parent"||o==="proxyCache")continue;let a=this[o];if(Array.isArray(a))i[o]=a.map(l=>typeof l=="object"&&l.toJSON?l.toJSON(null,t):l);else if(typeof a=="object"&&a.toJSON)i[o]=a.toJSON(null,t);else if(o==="source"){let l=t.get(a.input);l==null&&(l=s,t.set(a.input,s),s++),i[o]={end:a.end,inputId:l,start:a.start}}else i[o]=a}return r&&(i.inputs=[...t.keys()].map(o=>o.toJSON())),i}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Rs){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}},st=Wt;Wt.default=Wt;Os=st,Vt=class extends Os{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]==="$"}},ot=Vt;Vt.default=Vt;As="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Ns=(n,e=21)=>(t=e)=>{let i="",r=t;for(;r--;)i+=n[Math.random()*n.length|0];return i},Hs=(n=21)=>{let e="",t=n;for(;t--;)e+=As[Math.random()*64|0];return e},$s={nanoid:Hs,customAlphabet:Ns},{SourceMapConsumer:Fi,SourceMapGenerator:zi}=O,{existsSync:Us,readFileSync:Fs}=O,{dirname:At,join:zs}=O;Gt=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 Fi(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 Bs(e.substr(RegExp.lastMatch.length));let o=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+o)}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),Us(e))return this.mapFile=e,Fs(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 Fi)return zi.fromSourceMap(t).toString();if(t instanceof zi)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=zs(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)}},Sr=Gt;Gt.default=Gt;({SourceMapConsumer:js,SourceMapGenerator:Ws}=O),{fileURLToPath:Bi,pathToFileURL:Ue}=O,{isAbsolute:qt,resolve:Yt}=O,{nanoid:Vs}
vendor: 17,655 bytes, lines 21-26
21=$s,Nt=O,ji=si,Gs=Sr,Ht=Symbol("fromOffsetCache"),qs=!!(js&&Ws),Wi=!!(Yt&&qt),Qe=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&&(!Wi||/^\w+:\/\//.test(t.from)||qt(t.from)?this.file=t.from:this.file=Yt(t.from)),Wi&&qs){let i=new Gs(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 "+Vs(6)+">"),this.map&&(this.map.file=this.from)}error(e,t,i,r={}){let s,o,a;if(t&&typeof t=="object"){let c=t,u=i;if(typeof c.offset=="number"){let h=this.fromOffset(c.offset);t=h.line,i=h.col}else t=c.line,i=c.column;if(typeof u.offset=="number"){let h=this.fromOffset(u.offset);o=h.line,a=h.col}else o=u.line,a=u.column}else if(!i){let c=this.fromOffset(t);t=c.line,i=c.col}let l=this.origin(t,i,o,a);return l?s=new ji(e,l.endLine===void 0?l.line:{column:l.column,line:l.line},l.endLine===void 0?l.column:{column:l.endColumn,line:l.endLine},l.source,l.file,r.plugin):s=new ji(e,o===void 0?t:{column:i,line:t},o===void 0?i:{column:a,line:o},this.css,this.file,r.plugin),s.input={column:i,endColumn:a,endLine:o,line:t,source:this.css},this.file&&(Ue&&(s.input.url=Ue(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,i;if(this[Ht])i=this[Ht];else{let s=this.css.split(`
22`);i=new Array(s.length);let o=0;for(let a=0,l=s.length;a<l;a++)i[a]=o,o+=s[a].length+1;this[Ht]=i}t=i[i.length-1];let r=0;if(e>=t)r=i.length-1;else{let s=i.length-2,o;for(;r<s;)if(o=r+(s-r>>1),e<i[o])s=o-1;else if(e>=i[o+1])r=o+1;else{r=o;break}}return{col:e-i[r]+1,line:r+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:Yt(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,i,r){if(!this.map)return!1;let s=this.map.consumer(),o=s.originalPositionFor({column:t,line:e});if(!o.source)return!1;let a;typeof i=="number"&&(a=s.originalPositionFor({column:r,line:i}));let l;qt(o.source)?l=Ue(o.source):l=new URL(o.source,this.map.consumer().sourceRoot||Ue(this.map.mapFile));let c={column:o.column,endColumn:a&&a.column,endLine:a&&a.line,line:o.line,url:l.toString()};if(l.protocol==="file:")if(Bi)c.file=Bi(l);else throw new Error("file: protocol is not available in this PostCSS build");let u=s.sourceContentFor(o.source);return u&&(c.source=u),c}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}},at=Qe;Qe.default=Qe;Nt&&Nt.registerInput&&Nt.registerInput(Qe);({SourceMapConsumer:Cr,SourceMapGenerator:Je}=O),{dirname:Xe,relative:Er,resolve:kr,sep:xr}=O,{pathToFileURL:Vi}=O,Ys=at,Js=!!(Cr&&Je),Xs=!!(Xe&&kr&&Er&&xr),Ks=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=`
23`;this.css.includes(`\r
24`)&&(t=`\r
25`),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t=this.toUrl(this.path(e.file)),i=e.root||Xe(e.file),r;this.mapOpts.sourcesContent===!1?(r=new Cr(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(),Xs&&Js&&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=Je.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Je({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 Je({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,o;this.stringify(this.root,(a,l,c)=>{if(this.css+=a,l&&c!=="end"&&(r.generated.line=e,r.generated.column=t-1,l.source&&l.source.start?(r.source=this.sourcePath(l),r.original.line=l.source.start.line,r.original.column=l.source.start.column-1,this.map.addMapping(r)):(r.source=i,r.original.line=1,r.original.column=0,this.map.addMapping(r))),s=a.match(/\n/g),s?(e+=s.length,o=a.lastIndexOf(`
26`),t=a.length-o):t+=a.length,l&&c!=="start"){let u=l.parent||{raws:{}};(!(l.type==="decl"||l.type==="atrule"&&!l.nodes)||l!==u.last||u.raws.semicolon)&&(l.source&&l.source.end?(r.source=this.sourcePath(l),r.original.line=l.source.end.line,r.original.column=l.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?Xe(this.opts.to):".";typeof this.mapOpts.annotation=="string"&&(i=Xe(kr(i,this.mapOpts.annotation)));let r=Er(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 Ys(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(Vi){let i=Vi(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;xr==="\\"&&(e=e.replace(/\\/g,"/"));let i=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,i),i}},Tr=Ks,Zs=st,Jt=class extends Zs{constructor(e){super(e),this.type="comment"}},lt=Jt;Jt.default=Jt;({isClean:_r,my:Ir}=we),Mr=ot,Lr=lt,Qs=st;$=class Ar extends Qs{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,o)=>r(s.toProxy(),o):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 o of r)this.proxyOf.nodes.splice(i+1,0,o);let s;for(let o in this.indexes)s=this.indexes[o],i<s&&(this.indexes[o]=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 a of s)this.proxyOf.nodes.splice(i,0,a);let o;for(let a in this.indexes)o=this.indexes[a],i<=o&&(this.indexes[a]=o+s.length);return this.markDirty(),this}normalize(e,t){if(typeof e=="string")e=Rr(Dr(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 Mr(e)]}else if(e.selector)e=[new oi(e)];else if(e.name)e=[new ai(e)];else if(e.text)e=[new Lr(e)];else throw new Error("Unknown node type in node creation");return e.map(r=>(r[Ir]||Ar.rebuild(r),r=r.proxyOf,r.parent&&r.parent.removeChild(r),r[_r]&&Or(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]}};$.registerParse=n=>{Dr=n};$.registerRule=n=>{oi=n};$.registerAtRule=n=>{ai=n};$.registerRoot=n=>{Pr=n};V=$;$.default=$;$.rebuild=n=>{n.type==="atrule"?Object.setPrototypeOf(n,ai.prototype):n.type==="rule"?Object.setPrototypeOf(n,oi.prototype):n.type==="decl"?Object.setPrototypeOf(n,Mr.prototype):n.type==="comment"?Object.setPrototypeOf(n,Lr.prototype):n.type==="root"&&Object.setPrototypeOf(n,Pr.prototype),n[Ir]=!0,n.nodes&&n.nodes.forEach(e=>{$.rebuild(e)})};eo=V,ge=class extends eo{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new Nr(new Hr,this,e).stringify()}};ge.registerLazyResult=n=>{Nr=n};ge.registerProcessor=n=>{Hr=n};li=ge;ge.default=ge;Xt=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}},$r=Xt;Xt.default=Xt;to=$r,Kt=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 to(e,t);return this.messages.push(i),i}warnings(){return this.messages.filter(e=>e.type==="warning")}get content(){return this.css}},ci=Kt;Kt.default=Kt;$t=39,Gi=34,Fe=92,qi=47,ze=10,he=32,Be=12,je=9,We=13,io=91,ro=93,no=40,so=41,oo=123,ao=125,lo=59,co=42,uo=58,ho=64,Ve=/[\t\n\f\r "#'()/;[\\\]{}]/g,Ge=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,po=/.[\r\n"'(/\\]/,Yi=/[\da-f]/i,fo=function(e,t={}){let i=e.css.valueOf(),r=t.ignoreErrors,s,o,a,l,c,u,h,p,m,v,g=i.length,d=0,S=[],T=[];function f(){return d}function b(F){throw e.error("Unclosed "+F,d)}function M(){return T.length===0&&d>=g}function D(F){if(T.length)return T.pop();if(d>=g)return;let R=F?F.ignoreUnclosed:!1;switch(s=i.charCodeAt(d),s){case ze:case he:case je:case We:case Be:{o=d;do o+=1,s=i.charCodeAt(o);while(s===he||s===ze||s===je||s===We||s===Be);v=["space",i.slice(d,o)],d=o-1;break}case io:case ro:case oo:case ao:case uo:case lo:case so:{let z=String.fromCharCode(s);v=[z,z,d];break}case no:{if(p=S.length?S.pop()[1]:"",m=i.charCodeAt(d+1),p==="url"&&m!==$t&&m!==Gi&&m!==he&&m!==ze&&m!==je&&m!==Be&&m!==We){o=d;do{if(u=!1,o=i.indexOf(")",o+1),o===-1)if(r||R){o=d;break}else b("bracket");for(h=o;i.charCodeAt(h-1)===Fe;)h-=1,u=!u}while(u);v=["brackets",i.slice(d,o+1),d,o],d=o}else o=i.indexOf(")",d+1),l=i.slice(d,o+1),o===-1||po.test(l)?v=["(","(",d]:(v=["brackets",l,d,o],d=o);break}case $t:case Gi:{a=s===$t?"'":'"',o=d;do{if(u=!1,o=i.indexOf(a,o+1),o===-1)if(r||R){o=d+1;break}else b("string");for(h=o;i.charCodeAt(h-1)===Fe;)h-=1,u=!u}while(u);v=["string",i.slice(d,o+1),d,o],d=o;break}case ho:{Ve.lastIndex=d+1,Ve.test(i),Ve.lastIndex===0?o=i.length-1:o=Ve.lastIndex-2,v=["at-word",i.slice(d,o+1),d,o],d=o;break}case Fe:{for(o=d,c=!0;i.charCodeAt(o+1)===Fe;)o+=1,c=!c;if(s=i.charCodeAt(o+1),c&&s!==qi&&s!==he&&s!==ze&&s!==je&&s!==We&&s!==Be&&(o+=1,Yi.test(i.charAt(o)))){for(;Yi.test(i.charAt(o+1));)o+=1;i.charCodeAt(o+1)===he&&(o+=1)}v=["word",i.slice(d,o+1),d,o],d=o;break}default:{s===qi&&i.charCodeAt(d+1)===co?(o=i.indexOf("*/",d+2)+1,o===0&&(r||R?o=i.length:b("comment")),v=["comment",i.slice(d,o+1),d,o],d=o):(Ge.lastIndex=d+1,Ge.test(i),Ge.lastIndex===0?o=i.length-1:o=Ge.lastIndex-2,v=["word",i.slice(d,o+1),d,o],S.push(v),d=o);break}}return d++,v}function q(F){T.push(F)}return{back:q,endOfFile:M,nextToken:D,position:f}},Ur=V,et=class extends Ur{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)}},ui=et;et.default=et;Ur.registerAtRule(et);Fr=V,ie=class extends Fr{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 zr(new Br,this,e).stringify()}};ie.registerLazyResult=n=>{zr=n};ie.registerProcessor=n=>{Br=n};Se=ie;ie.default=ie;Fr.registerRoot(ie);me={comma(n){return me.split(n,[","],!0)},space(n){let e=[" ",`
27`,"	"];return me.split(n,e)},split(n,e,t){let i=[],r="",s=!1,o=0,a=!1,l="",c=!1;for(let u of n)c?c=!1:u==="\\"?c=!0:a?u===l&&(a=!1):u==='"'||u==="'"?(a=!0,l=u):u==="("?o+=1:u===")"?o>0&&(o-=1):o===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}},jr=me;me.default=me;Wr=V,go=jr,tt=class extends Wr{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return go.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)}},di=tt;tt.default=tt;Wr.registerRule(tt);mo=ot,yo=fo,vo=lt,bo=ui,wo=Se,Ji=di,Xi={empty:!0,space:!0};Co=class{constructor(e){this.input=e,this.root=new wo,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 bo;t.name=e[1].slice(1),t.name===""&&this.unnamedAtrule(t,e),this.init(t,e[2]);let i,r,s,o=!1,a=!1,l=[],c=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),i=e[0],i==="("||i==="["?c.push(i==="("?")":"]"):i==="{"&&c.length>0?c.push("}"):i===c[c.length-1]&&c.pop(),c.length===0)if(i===";"){t.source.end=this.getPosition(e[2]),t.source.end.offset++,this.semicolon=!0;break}else if(i==="{"){a=!0;break}else if(i==="}"){if(l.length>0){for(s=l.length-1,r=l[s];r&&r[0]==="space";)r=l[--s];r&&(t.source.end=this.getPosition(r[3]||r[2]),t.source.end.offset++)}this.end(e);break}else l.push(e);else l.push(e);if(this.tokenizer.endOfFile()){o=!0;break}}t.raws.between=this.spacesAndCommentsFromEnd(l),l.length?(t.raws.afterName=this.spacesAndCommentsFromStart(l),this.raw(t,"params",l),o&&(e=l[l.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=""),a&&(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[o,a]of e.entries()){if(i=a,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 o}s=i}return!1}comment(e){let t=new vo;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=yo(this.input)}decl(e,t){let i=new mo;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]||So(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 c=e[0][0];if(c===":"||c==="space"||c==="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 o=[],a;for(;e.length&&(a=e[0][0],!(a!=="space"&&a!=="comment"));)o.push(e.shift());this.precheckMissedSemicolon(e);for(let c=e.length-1;c>=0;c--){if(s=e[c],s[1].toLowerCase()==="!important"){i.important=!0;let u=this.stringFrom(e,c);u=this.spacesFromEnd(e)+u,u!==" !important"&&(i.raws.important=u);break}else if(s[1].toLowerCase()==="important"){let u=e.slice(0),h="";for(let p=c;p>0;p--){let m=u[p][0];if(h.trim().indexOf("!")===0&&m!=="space")break;h=u.pop()[1]+h}h.trim().indexOf("!")===0&&(i.important=!0,i.raws.important=h,e=u)}if(s[0]!=="space"&&s[0]!=="comment")break}e.some(c=>c[0]!=="space"&&c[0]!=="comment")&&(i.raws.between+=o.map(c=>c[1]).join(""),o=[]),this.raw(i,"value",o.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 Ji;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,o=[],a=e[1].startsWith("--"),l=[],c=e;for(;c;){if(i=c[0],l.push(c),i==="("||i==="[")s||(s=c),o.push(i==="("?")":"]");else if(a&&r&&i==="{")s||(s=c),o.push("}");else if(o.length===0)if(i===";")if(r){this.decl(l,a);return}else break;else if(i==="{"){this.rule(l);return}else if(i==="}"){this.tokenizer.back(l.pop()),t=!0;break}else i===":"&&(r=!0);else i===o[o.length-1]&&(o.pop(),o.length===0&&(s=null));c=this.tokenizer.nextToken()}
vendor: 9,816 bytes, line 27
27if(this.tokenizer.endOfFile()&&(t=!0),o.length>0&&this.unclosedBracket(s),t&&r){if(!a)for(;l.length&&(c=l[l.length-1][0],!(c!=="space"&&c!=="comment"));)this.tokenizer.back(l.pop());this.decl(l,a)}else this.unknownWord(l)}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,o,a=i.length,l="",c=!0,u,h;for(let p=0;p<a;p+=1)s=i[p],o=s[0],o==="space"&&p===a-1&&!r?c=!1:o==="comment"?(h=i[p-1]?i[p-1][0]:"empty",u=i[p+1]?i[p+1][0]:"empty",!Xi[h]&&!Xi[u]?l.slice(-1)===","?c=!1:l+=s[1]:c=!1):l+=s[1];if(!c){let p=i.reduce((m,v)=>m+v[1],"");e.raws[t]={raw:p,value:l}}e[t]=l}rule(e){e.pop();let t=new Ji;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})}},Eo=Co,ko=V,xo=Eo,To=at;hi=it;it.default=it;ko.registerParse(it);({isClean:N,my:_o}=we),Io=Tr,Mo=nt,Lo=V,Do=li,Ki=ci,Po=hi,Ro=Se,Oo={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},Ao={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},No={Once:!0,postcssPlugin:!0,prepare:!0},re=0;Qt={},ne=class Gr{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=Zt(t);else if(t instanceof Gr||t instanceof Ki)r=Zt(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=Po;i.syntax&&(s=i.syntax.parse),i.parser&&(s=i.parser),s.parse&&(s=s.parse);try{r=s(t,i)}catch(o){this.processed=!0,this.error=o}r&&!r[_o]&&Lo.rebuild(r)}this.result=new Ki(e,r,i),this.helpers={...Qt,postcss:Qt,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(!Ao[i]&&/^[A-Z]/.test(i))throw new Error(`Unknown event ${i} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!No[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(pe(i))try{await i}catch(r){throw this.handleError(r)}}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[N];){e[N]=!0;let t=[Zi(e)];for(;t.length>0;){let i=this.visitTick(t);if(pe(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 pe(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=Mo;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new Io(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(pe(t))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[N];)e[N]=!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(o){throw this.handleError(o,t.proxyOf)}if(t.type!=="root"&&t.type!=="document"&&!t.parent)return!0;if(pe(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[o,a]=r[t.visitorIndex];t.visitorIndex+=1,t.visitorIndex===r.length&&(t.visitors=[],t.visitorIndex=0),this.result.lastPlugin=o;try{return a(i.toProxy(),this.helpers)}catch(l){throw this.handleError(l,i)}}if(t.iterator!==0){let o=t.iterator,a;for(;a=i.nodes[i.indexes[o]];)if(i.indexes[o]+=1,!a[N]){a[N]=!0,e.push(Zi(a));return}t.iterator=0,delete i.indexes[o]}let s=t.events;for(;t.eventIndex<s.length;){let o=s[t.eventIndex];if(t.eventIndex+=1,o===re){i.nodes&&i.nodes.length&&(i[N]=!0,t.iterator=i.getIterator());return}else if(this.listeners[o]){t.visitors=this.listeners[o];return}}e.pop()}walkSync(e){e[N]=!0;let t=Vr(e);for(let i of t)if(i===re)e.nodes&&e.each(r=>{r[N]||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"}};ne.registerPostcss=n=>{Qt=n};qr=ne;ne.default=ne;Ro.registerLazyResult(ne);Do.registerLazyResult(ne);Ho=Tr,$o=nt,Uo=hi,Fo=ci,ei=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=$o;this.result=new Fo(this._processor,r,this._opts),this.result.css=t;let o=this;Object.defineProperty(this.result,"root",{get(){return o.root}});let a=new Ho(s,r,this._opts,t);if(a.isMap()){let[l,c]=a.generate();l&&(this.result.css=l),c&&(this.result.map=c)}else a.clearAnnotation(),this.result.css=a.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=Uo;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"}},zo=ei;ei.default=ei;Bo=zo,jo=qr,Wo=li,Vo=Se,ye=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 Bo(this,e,t):new jo(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}},Go=ye;ye.default=ye;Vo.registerProcessor(ye);Wo.registerProcessor(ye);qo=ot,Yo=Sr,Jo=lt,Xo=ui,Ko=at,Zo=Se,Qo=di;ea=ve;ve.default=ve;
27ta=si,Yr=ot,ia=qr,ra=V,pi=Go,na=nt,sa=ea,Jr=li,oa=$r,Xr=lt,Kr=ui,aa=ci,la=at,ca=hi,ua=jr,Zr=di,Qr=Se,da=st;w.plugin=function(e,t){let i=!1;function r(...o){console&&console.warn&&!i&&(i=!0,console.warn(e+`: postcss.plugin was deprecated. Migration guide:
28https://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:
29https://www.w3ctech.com/topic/2226`));let a=t(...o);return a.postcssPlugin=e,a.postcssVersion=new pi().version,a}let s;return Object.defineProperty(r,"postcss",{get(){return s||(s=r()),s}}),r.process=function(o,a,l){return w([r(l)]).process(o,a)},r};w.stringify=na;w.parse=ca;w.fromJSON=sa;w.list=ua;w.comment=n=>new Xr(n);w.atRule=n=>new Kr(n);w.decl=n=>new Yr(n);w.rule=n=>new Zr(n);w.root=n=>new Qr(n);w.document=n=>new Jr(n);w.CssSyntaxError=ta;w.Declaration=Yr;w.Container=ra;w.Processor=pi;w.Document=Jr;w.Comment=Xr;w.Warning=oa;w.AtRule=Kr;w.Result=aa;w.Input=la;w.Rule=Zr;w.Root=Qr;w.Node=da;ia.registerPostcss(w);ha=w;w.default=w;x=Es(ha);x.stringify;x.fromJSON;x.plugin;x.parse;x.list;x.document;x.comment;x.atRule;x.rule;x.decl;x.root;x.CssSyntaxError;x.Declaration;x.Container;x.Processor;x.Document;x.Comment;x.Warning;x.AtRule;x.Result;x.Input;x.Rule;x.Root;x.Node;Qi={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"}});function Ee(n,e=document){let t=[{name:"grainId",confidence:1,find:()=>n.grainId?e.querySelector(`[data-grain-id="${CSS.escape(n.grainId)}"]`):null},{name:"id",confidence:.95,find:()=>{if(!n.id)return null;let i=e.querySelector(`#${CSS.escape(n.id)}`);return i&&i.id===n.id?i:null}},{name:"testId",confidence:.95,find:()=>n.testId?e.querySelector(`[data-testid="${CSS.escape(n.testId)}"]`):null},{name:"ariaLabel+tag",confidence:.85,find:()=>!n.ariaLabel||!n.tag?null:e.querySelector(`${n.tag}[aria-label="${CSS.escape(n.ariaLabel)}"]`)},{name:"name+tag",confidence:.85,find:()=>!n.name||!n.tag?null:e.querySelector(`${n.tag}[name="${CSS.escape(n.name)}"]`)},{name:"nearestIdAncestor",confidence:.75,find:()=>{if(!n.nearestIdAncestor)return null;let i=e.querySelector(`#${CSS.escape(n.nearestIdAncestor.ancestorId)}`);return i?Sa(i,n.nearestIdAncestor.relativePath):null}},{name:"tag+textContent",confidence:.7,find:()=>{if(!n.tag||!n.textContent)return null;let i=e.querySelectorAll(n.tag);for(let r of i)if(r.textContent?.trim().replace(/\s+/g," ").substring(0,100)===n.textContent)return r;return null}},{name:"tag+href",confidence:.7,find:()=>!n.tag||!n.href?null:e.querySelector(`${n.tag}[href="${CSS.escape(n.href)}"]`)},{name:"tag+classes",confidence:.6,find:()=>{if(!n.tag||!n.classes||n.classes.length<2)return null;let i=`${n.tag}.${n.classes.map(r=>CSS.escape(r)).join(".")}`;return e.querySelector(i)}},{name:"xpath",confidence:.5,find:()=>{if(!n.xpath)return null;try{return document.evaluate(n.xpath,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{return null}}},{name:"css",confidence:.5,find:()=>{if(!n.css)return null;try{return e.querySelector(n.css)}catch{return null}}}];for(let i of t)try{let r=i.find();if(r){let s=i.confidence;return n.tag&&r.tagName.toLowerCase()!==n.tag&&(s*=.5),{element:r,confidence:s,strategy:i.name}}}catch{}return null}function Sa(n,e){let t=e.split("/"),i=n;for(let r of t){if(!i)return null;let s=r.match(/^([a-z][a-z0-9]*?)(?:\[(\d+)\])?$/i);if(!s)return null;let o=s[1].toUpperCase(),a=s[2]?parseInt(s[2],10):1;i=Array.from(i.children).filter(c=>c.tagName===o)[a-1]||null}return i}var gi=P(()=>{"use strict"});var yt,sn=P(()=>{"use strict";yt=class{constructor(e){this.sessionCounts=new Map;this.tenantId=e,this.loadSessionCounts()}canShow(e,t){if(!t)return!0;let i=Date.now(),r=this.getCampaignData(e);
29if(t.cooldownAfterDismiss!=null&&r.lastDismissTime!=null&&(i-r.lastDismissTime)/1e3<t.cooldownAfterDismiss||t.cooldownAfterConvert!=null&&r.lastConvertTime!=null&&(i-r.lastConvertTime)/1e3<t.cooldownAfterConvert||t.maxImpressionsPerSession!=null&&(this.sessionCounts.get(e)||0)>=t.maxImpressionsPerSession)return!1;if(t.maxImpressionsPerDay!=null){let s=this.todayStartMs();if(r.impressions.filter(a=>a>=s).length>=t.maxImpressionsPerDay)return!1}return!(t.maxImpressionsTotal!=null&&r.impressions.length>=t.maxImpressionsTotal)}recordImpression(e){let t=Date.now(),i=this.getCampaignData(e);i.impressions.push(t),this.setCampaignData(e,i);let r=(this.sessionCounts.get(e)||0)+1;this.sessionCounts.set(e,r),this.saveSessionCounts()}recordDismiss(e){let t=this.getCampaignData(e);t.lastDismissTime=Date.now(),this.setCampaignData(e,t)}recordConvert(e){let t=this.getCampaignData(e);t.lastConvertTime=Date.now(),this.setCampaignData(e,t)}getCampaignData(e){try{let t=localStorage.getItem(this.storageKey());if(!t)return this.emptyData();let r=JSON.parse(t)[e];if(!r)return this.emptyData();let s=Date.now()-7776e6;return r.impressions=(r.impressions||[]).filter(o=>o>=s),r}catch{return this.emptyData()}}setCampaignData(e,t){try{let i=localStorage.getItem(this.storageKey()),r=i?JSON.parse(i):{};r[e]=t,localStorage.setItem(this.storageKey(),JSON.stringify(r))}catch{}}loadSessionCounts(){try{let e=sessionStorage.getItem(this.sessionKey());if(!e)return;let t=JSON.parse(e);for(let[i,r]of Object.entries(t))this.sessionCounts.set(i,r)}catch{}}saveSessionCounts(){try{let e={};for(let[t,i]of this.sessionCounts.entries())e[t]=i;sessionStorage.setItem(this.sessionKey(),JSON.stringify(e))}catch{}}emptyData(){return{impressions:[],lastDismissTime:null,lastConvertTime:null}}todayStartMs(){let e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}storageKey(){return`_grain_${this.tenantId}_rescue_caps`}sessionKey(){return`_grain_${this.tenantId}_rescue_session`}}});var _a,Ia,Ma,La,Da,vt,on=P(()=>{"use strict";_a={low:60,medium:40,high:25},Ia=5e3,Ma=1e4,La=6e4,Da=2e3,vt=class{constructor(e,t){this.callback=null;this.fired=!1;this.destroyed=!1;this.sessionStartTime=Date.now();this.hasEngaged=!1;this.lastEngagementTime=0;this.mouseSamples=[];this.lastMouseMoveTime=0;this.scrollSamples=[];this.lastRapidScrollUpTime=0;this.lastScrollTime=0;this.wasScrolling=!1;this.scrollStallInterval=null;this.hysteresisTimer=null;this.boundMouseLeave=null;this.boundMouseMove=null;this.boundVisibilityChange=null;this.boundScroll=null;this.boundClick=null;this.sensitivity=e,this.activityDetector=t}start(e){this.destroyed||(this.callback=e,this.boundMouseLeave=t=>this.handleMouseLeave(t),this.boundMouseMove=t=>this.handleMouseMove(t),document.addEventListener("mouseleave",this.boundMouseLeave),document.addEventListener("mousemove",this.boundMouseMove),this.boundClick=()=>this.recordEngagement(),document.addEventListener("click",this.boundClick),this.boundScroll=()=>this.handleScroll(),window.addEventListener("scroll",this.boundScroll,{passive:!0}),(this.sensitivity==="medium"||this.sensitivity==="high")&&(this.boundVisibilityChange=()=>this.handleVisibilityChange(),document.addEventListener("visibilitychange",this.boundVisibilityChange),this.scrollStallInterval=window.setInterval(()=>this.checkScrollStall(),Da)))}reset(){this.fired=!1,this.wasScrolling=!1,this.lastScrollTime=0,this.lastRapidScrollUpTime=0,this.mouseSamples=[],this.scrollSamples=[],this.hysteresisTimer!=null&&(clearTimeout(this.hysteresisTimer),this.hysteresisTimer=null)}destroy(){this.destroyed=!0,this.callback=null,this.boundMouseLeave&&(document.removeEventListener("mouseleave",this.boundMouseLeave),this.boundMouseLeave=null),this.boundMouseMove&&(document.removeEventListener("mousemove",this.boundMouseMove),this.boundMouseMove=null),this.boundVisibilityChange&&(document.removeEventListener("visibilitychange",this.boundVisibilityChange),this.boundVisibilityChange=null),this.boundScroll&&(window.removeEventListener("scroll",this.boundScroll),this.boundScroll=null),this.boundClick&&(document.removeEventListener("click",this.boundClick),this.boundClick=null),this.scrollStallInterval!=null&&(clearInterval(this.scrollStallInterval),this.scrollStallInterval=null),this.hysteresisTimer!=null&&(clearTimeout(this.hysteresisTimer),this.hysteresisTimer=null)}handleMouseMove(e){let t=Date.now();
29t-this.lastMouseMoveTime<50||(this.lastMouseMoveTime=t,this.mouseSamples.push({x:e.clientX,y:e.clientY,t}),this.mouseSamples.length>5&&this.mouseSamples.shift())}handleMouseLeave(e){if(e.clientY>0||!this.hasEngaged||this.fired||this.hysteresisTimer!=null)return;let t=this.calculateConfidence(),i=_a[this.sensitivity];t<i||this.startHysteresis()}calculateConfidence(){let e=0;return e+=this.scoreVelocity(),e+=this.scoreTrajectory(),e+=this.scoreJHook(),e+=this.scoreRecency(),e}scoreVelocity(){if(this.mouseSamples.length<2)return 0;let e=this.mouseSamples[0],t=this.mouseSamples[this.mouseSamples.length-1],i=t.t-e.t;if(i<=0)return 0;let r=e.y-t.y;if(r<=0)return 0;let s=r/i;if(s<.3)return 0;if(s>=1.5)return 35;let o=(s-.3)/(1.5-.3);return Math.round(o*35)}scoreTrajectory(){if(this.mouseSamples.length<2)return 0;let e=this.mouseSamples[0],t=this.mouseSamples[this.mouseSamples.length-1],i=Math.abs(t.x-e.x),r=e.y-t.y;if(r<=0)return 0;let s=Math.atan2(i,r)*(180/Math.PI);if(s<=30)return 25;if(s>=60)return 0;let o=1-(s-30)/30;return Math.round(o*25)}scoreJHook(){return this.lastRapidScrollUpTime===0?0:Date.now()-this.lastRapidScrollUpTime<=2e3?30:0}scoreRecency(){return this.lastEngagementTime===0?0:Date.now()-this.lastEngagementTime<=3e4?10:0}startHysteresis(){this.hysteresisTimer=window.setTimeout(()=>{this.hysteresisTimer=null,document.visibilityState!=="hidden"&&this.fire()},300)}recordEngagement(){this.hasEngaged=!0,this.lastEngagementTime=Date.now()}handleScroll(){let e=Date.now(),t=window.scrollY;for(this.recordEngagement(),this.scrollSamples.push({y:t,t:e});this.scrollSamples.length>1&&e-this.scrollSamples[0].t>500;)this.scrollSamples.shift();if(this.scrollSamples.length>=2){let i=this.scrollSamples[0],r=this.scrollSamples[this.scrollSamples.length-1],s=r.t-i.t;if(s>0){let o=i.y-r.y,a=o/s;o>0&&a>=1&&(this.lastRapidScrollUpTime=e)}}this.lastScrollTime=e,this.wasScrolling=!0}handleVisibilityChange(){document.visibilityState==="hidden"&&this.activityDetector.getIdleTime()>Ia&&this.fire()}checkScrollStall(){if(!this.wasScrolling||this.lastScrollTime===0)return;Date.now()-this.lastScrollTime>=Ma&&(this.wasScrolling=!1,this.fire())}fire(){this.fired||this.destroyed||!this.callback||this.sensitivity==="high"&&Date.now()-this.sessionStartTime<La||(this.fired=!0,this.callback())}}});var bt,an=P(()=>{"use strict";on();X();bt=class{constructor(e,t,i){this.campaigns=[];this.firedCampaigns=new Set;this.destroyed=!1;this.exitIntentDetector=null;this.scrollListener=null;this.timers=[];this.campaigns=e,this.callback=t,this.activityDetector=i}start(){this.destroyed||(this.evaluatePageLoadTriggers(),this.evaluateTimeDelayTriggers(),this.evaluateExitIntentTriggers(),this.evaluateScrollDepthTriggers(),this.evaluateUrlMatchTriggers())}notifyEvent(e,t){if(!this.destroyed){for(let i of this.campaigns)if(!this.firedCampaigns.has(i.campaignId)&&i.state==="armed")for(let r of i.triggers){if(r.config.type!=="EVENT_RULE")continue;let s=r.config;if(s.eventName===e){if(s.property&&s.value!=null){let o=String(t[s.property]??"");if(!this.matchOperator(o,s.operator,s.value))continue}this.fireTrigger(i.campaignId,r);break}}}}markFired(e){this.firedCampaigns.add(e)}resetCampaign(e){this.firedCampaigns.delete(e)}destroy(){this.destroyed=!0,this.exitIntentDetector?.destroy(),this.exitIntentDetector=null,this.scrollListener&&(window.removeEventListener("scroll",this.scrollListener),this.scrollListener=null);for(let e of this.timers)clearTimeout(e);this.timers=[]}evaluatePageLoadTriggers(){for(let e of this.campaigns)if(e.state==="armed")for(let t of e.triggers){if(t.config.type!=="PAGE_LOAD")continue;let i=t.config.delay||0,r=window.setTimeout(()=>{this.fireTrigger(e.campaignId,t)},i);this.timers.push(r)}}evaluateTimeDelayTriggers(){for(let e of this.campaigns)if(e.state==="armed")for(let t of e.triggers){if(t.config.type!=="TIME_DELAY")continue;let i=window.setTimeout(()=>{this.fireTrigger(e.campaignId,t)},t.config.delaySeconds*1e3);this.timers.push(i)}}evaluateExitIntentTriggers(){let e=null,t=[];for(let i of this.campaigns)if(i.state==="armed")for(let r of i.triggers){if(r.config.type!=="EXIT_INTENT")continue;t.push({campaign:i,trigger:r});let s=r.config.sensitivity;(!e||this.sensitivityRank(s)>this.sensitivityRank(e))&&(e=s)}!e||t.length===0||(this.exitIntentDetector=new vt(e,this.activityDetector),this.exitIntentDetector.start(()=>{for(let{campaign:i,trigger:r}of t)this.fireTrigger(i.campaignId,r)}))}evaluateScrollDepthTriggers(){let e=[];for(let i of this.campaigns)if(i.state==="armed")for(let r of i.triggers)r.config.type==="SCROLL_DEPTH"&&e.push({campaign:i,trigger:r,percentage:r.config.percentage});if(e.length===0)return;let t=null;this.scrollListener=()=>{t==null&&(t=window.setTimeout(()=>{t=null,this.checkScrollDepth(e)},200))},window.addEventListener("scroll",this.scrollListener,{passive:!0}),this.checkScrollDepth(e)}checkScrollDepth(e){let t=window.scrollY,i=document.documentElement.scrollHeight,r=window.innerHeight,s=i-r;if(s<=0)return;let o=t/s*100;for(let{campaign:a,trigger:l,percentage:c}of e)this.firedCampaigns.has(a.campaignId)||o>=c&&this.fireTrigger(a.campaignId,l)}evaluateUrlMatchTriggers(){let e=typeof window<"u"?window.location.href:"",t=H(e);for(let i of this.campaigns)if(i.state==="armed")for(let r of i.triggers){if(r.config.type!=="URL_MATCH")continue;let{pattern:s,matchType:o}=r.config,a=!1;switch(o){case"contains":a=t.includes(s);break;case"equals":a=t===H(s);break;case"regex":try{a=new RegExp(s).test(e)}catch{}break}a&&this.fireTrigger(i.campaignId,r)}}fireTrigger(e,t){this.firedCampaigns.has(e)||this.destroyed||(this.firedCampaigns.add(e),this.callback(e,t))}sensitivityRank(e){switch(e){case"low":return 1;case"medium":return 2;case"high":return 3}}matchOperator(e,t,i){switch(t){case"equals":return e===i;case"contains":return e.includes(i);case"starts_with":return e.startsWith(i);case"ends_with":return e.endsWith(i);case"regex":try{return new RegExp(i).test(e)}catch{return!1}default:return e===i}}}});var ln,wt,cn=P(()=>{"use strict";ln={BOTTOM_LEFT:{bottom:"24px",left:"24px",right:"auto",top:"auto"},BOTTOM_RIGHT:{bottom:"24px",right:"24px",left:"auto",top:"auto"},TOP_LEFT:{top:"24px",left:"24px",right:"auto",bottom:"auto"},TOP_RIGHT:{top:"24px",right:"24px",left:"auto",bottom:"auto"},TOP:{top:"0",left:"0",right:"0",bottom:"auto"},BOTTOM:{bottom:"0",left:"0",right:"0",top:"auto"},CENTER:{top:"50%",left:"50%",right:"auto",bottom:"auto"},SLIDE_LEFT:{top:"50%",left:"0",right:"auto",bottom:"auto"},SLIDE_RIGHT:{top:"50%",right:"0",left:"auto",bottom:"auto"}},wt=class{constructor(){this.container=null;this.backdropElement=null;this.showing=!1;this.countdownIntervals=[];this.onAction=null}isShowing(){return this.showing}show(e,t,i){if(this.showing||!t.content)return;this.showing=!0,this.onAction=i;let r=t.content;switch(e){case"PULSE":this.renderPulse(r);break;case"ANNOUNCER":this.renderAnnouncer(r);break;case"SAVIOR":this.renderSavior(r);break}}async hide(){this.showing&&(await this.animateOut(),this.cleanup())}destroy(){this.clearCountdowns(),this.cleanup()}renderPulse(e){let t=document.createElement("div");t.id="grain-rescue-container";
29let i=ln[e.position]||ln.BOTTOM_RIGHT,r=this.buildBackground(e.backgroundType,e.backgroundConfig);Object.assign(t.style,{position:"fixed",zIndex:String(999990),minWidth:"300px",maxWidth:"380px",borderRadius:"12px",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",padding:"20px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",overflow:"hidden",opacity:"0",transform:this.getSlideInStart(e.position),transition:"opacity 0.3s ease, transform 0.3s ease",...i,...r}),e.customCss&&(t.style.cssText+="; "+e.customCss);let s=this.resolveContainerColors(e.backgroundType,e.backgroundConfig,r);this.renderCloseButton(t),this.renderTextContent(t,e.textContent),this.renderWidgets(t,e.widgets,!1,s),document.body.appendChild(t),this.container=t,requestAnimationFrame(()=>{requestAnimationFrame(()=>{t.style.opacity="1",t.style.transform="translate(0, 0)"})})}renderAnnouncer(e){let t=document.createElement("div");t.id="grain-rescue-container";let i=e.position==="TOP"||e.position==="TOP_LEFT"||e.position==="TOP_RIGHT",r=this.buildBackground(e.backgroundType,e.backgroundConfig);Object.assign(t.style,{position:"fixed",zIndex:String(999990),left:"0",right:"0",...i?{top:"0"}:{bottom:"0"},maxHeight:"80px",padding:"12px 24px",display:"flex",alignItems:"center",justifyContent:"center",gap:"16px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",overflow:"hidden",opacity:"0",transform:i?"translateY(-100%)":"translateY(100%)",transition:"opacity 0.3s ease, transform 0.3s ease",...r}),e.customCss&&(t.style.cssText+="; "+e.customCss);let s=this.resolveContainerColors(e.backgroundType,e.backgroundConfig,r);this.renderTextContent(t,e.textContent,!0),this.renderWidgets(t,e.widgets,!0,s),this.renderCloseButton(t),document.body.appendChild(t),this.container=t,requestAnimationFrame(()=>{requestAnimationFrame(()=>{t.style.opacity="1",t.style.transform="translateY(0)"})})}renderSavior(e){let t=document.createElement("div");t.id="grain-rescue-backdrop",Object.assign(t.style,{position:"fixed",zIndex:String(999989),top:"0",left:"0",right:"0",bottom:"0",backgroundColor:"rgba(0,0,0,0.5)",opacity:"0",transition:"opacity 0.3s ease"}),t.addEventListener("click",()=>this.handleAction({type:"dismiss"})),document.body.appendChild(t),this.backdropElement=t;let i=document.createElement("div");i.id="grain-rescue-container";let r=this.buildBackground(e.backgroundType,e.backgroundConfig);Object.assign(i.style,{position:"fixed",zIndex:String(999990),top:"50%",left:"50%",transform:"translate(-50%, -50%) scale(0.95)",maxWidth:"520px",width:"90%",borderRadius:"16px",boxShadow:"0 24px 64px rgba(0,0,0,0.24)",padding:"32px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",overflow:"hidden",opacity:"0",transition:"opacity 0.3s ease, transform 0.3s ease",...r}),e.customCss&&(i.style.cssText+="; "+e.customCss);let s=this.resolveContainerColors(e.backgroundType,e.backgroundConfig,r);this.renderCloseButton(i),this.renderTextContent(i,e.textContent),this.renderWidgets(i,e.widgets,!1,s,!0),document.body.appendChild(i),this.container=i,requestAnimationFrame(()=>{requestAnimationFrame(()=>{t.style.opacity="1",i.style.opacity="1",i.style.transform="translate(-50%, -50%) scale(1)"})})}renderCloseButton(e){let t=document.createElement("button");Object.assign(t.style,{position:"absolute",top:"8px",right:"8px",background:"none",border:"none",cursor:"pointer",padding:"4px",lineHeight:"1",fontSize:"18px",color:"inherit",opacity:"0.6"}),t.textContent="\u2715",t.setAttribute("aria-label","Close"),t.addEventListener("click",i=>{i.stopPropagation(),this.handleAction({type:"dismiss"})}),e.appendChild(t)}renderTextContent(e,t,i=!1){if(!t)return;let r=document.createElement("div");if(t.headline){let s=document.createElement("div");Object.assign(s.style,{fontSize:t.headlineSize||(i?"15px":"20px"),fontWeight:"700",color:t.textColor&&t.textColor!=="auto"?t.textColor:"inherit",marginBottom:i?"0":"8px",lineHeight:"1.3"}),s.innerHTML=t.headline,r.appendChild(s)}if(t.subheadline){let s=document.createElement("div");Object.assign(s.style,{fontSize:i?"13px":"14px",fontWeight:"500",color:t.textColor&&t.textColor!=="auto"?t.textColor:"inherit",opacity:"0.85",marginBottom:i?"0":"8px",lineHeight:"1.4"}),s.innerHTML=t.subheadline,r.appendChild(s)}if(t.body&&!i){let s=document.createElement("div");Object.assign(s.style,{fontSize:t.bodySize||"14px",color:t.textColor&&t.textColor!=="auto"?t.textColor:"inherit",opacity:"0.75",lineHeight:"1.5",marginBottom:"16
29px"}),s.innerHTML=t.body,r.appendChild(s)}e.appendChild(r)}renderWidgets(e,t,i=!1,r,s=!1){if(!t||t.length===0)return;let o=document.createElement("div");Object.assign(o.style,{display:"flex",gap:"8px",...s?{flexDirection:"column"}:{flexWrap:"wrap",alignItems:i?"center":"flex-end"},...i?{flexShrink:"0"}:{}});for(let a of t)switch(a.type){case"BUTTON":o.appendChild(this.renderButton(a,r,s));break;case"COUPON":o.appendChild(this.renderCoupon(a,s));break;case"COUNTDOWN":o.appendChild(this.renderCountdown(a));break;case"IMAGE":o.appendChild(this.renderImage(a));break}e.appendChild(o)}renderButton(e,t,i=!1){let r=(e.action==="link"||e.action==="url")&&e.url,s=r?document.createElement("a"):document.createElement("button");r&&(s.href=e.url,s.target="_blank",s.rel="noopener");let o={cursor:"pointer",borderRadius:"8px",fontWeight:"600",fontFamily:"inherit",transition:"opacity 0.2s",textDecoration:"none",display:"inline-block",boxSizing:"border-box",textAlign:"center"};switch(i&&(o.width="100%",o.minHeight="42px",o.display="flex",o.alignItems="center",o.justifyContent="center"),e.size){case"small":Object.assign(o,{padding:"6px 12px",fontSize:"12px"});break;case"large":Object.assign(o,{padding:"14px 28px",fontSize:"16px"});break;default:Object.assign(o,{padding:"10px 20px",fontSize:"14px"})}switch(e.style){case"primary":Object.assign(o,{backgroundColor:t?.textColor||"#fff",color:t?.bgColor||"#2563eb",border:"none"});break;case"secondary":Object.assign(o,{backgroundColor:"rgba(255,255,255,0.2)",color:"inherit",border:"1px solid rgba(255,255,255,0.3)"});break;case"outline":Object.assign(o,{backgroundColor:"transparent",color:"inherit",border:"2px solid currentColor"});break}return Object.assign(s.style,o),s.textContent=e.text,s.addEventListener("click",a=>{switch(a.stopPropagation(),e.action){case"link":case"url":this.handleAction({type:"link",url:e.url||""});break;case"dismiss":this.handleAction({type:"dismiss"});break;case"custom":this.handleAction({type:"custom",eventName:e.text});break}}),s}renderCoupon(e,t=!1){let i=document.createElement("div");if(Object.assign(i.style,{display:"flex",flexDirection:"column",alignItems:"center",gap:"4px",...t?{width:"100%"}:{}}),e.label){let s=document.createElement("div");Object.assign(s.style,{fontSize:"12px",opacity:"0.7"}),s.textContent=e.label,i.appendChild(s)}let r=document.createElement("div");return Object.assign(r.style,{backgroundColor:"rgba(0,0,0,0.1)",padding:"8px 16px",borderRadius:"6px",fontFamily:"monospace",fontSize:"18px",fontWeight:"700",letterSpacing:"2px",cursor:"pointer",border:"2px dashed rgba(0,0,0,0.2)",boxSizing:"border-box",...t?{width:"100%",textAlign:"center"}:{}}),r.textContent=e.code,r.title=e.copyText,r.addEventListener("click",s=>{s.stopPropagation(),navigator.clipboard?.writeText(e.code).then(()=>{r.textContent="Copied!",setTimeout(()=>{r.textContent=e.code},2e3)}),this.handleAction({type:"coupon_copy",code:e.code})}),i.appendChild(r),i}renderCountdown(e){let t=document.createElement("div");Object.assign(t.style,{fontFamily:"monospace",fontSize:"24px",fontWeight:"700",textAlign:"center",padding:"8px"});let r=(e.endTime?e.endTime<1e12?e.endTime*1e3:e.endTime:null)??(e.durationSeconds?Date.now()+e.durationSeconds*1e3:null);if(!r)return t.textContent=e.expiredText,t;let s=()=>{let a=Math.max(0,r-Date.now());if(a<=0){t.textContent=e.expiredText;return}let l=Math.floor(a/36e5),c=Math.floor(a%36e5/6e4),u=Math.floor(a%6e4/1e3);if(e.format==="mm:ss"){let h=l*60+c;t.textContent=`${String(h).padStart(2,"0")}:${String(u).padStart(2,"0")}`}else t.textContent=`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}:${String(u).padStart(2,"0")}`};s();let o=window.setInterval(s,1e3);return this.countdownIntervals.push(o),t}renderImage(e){let t=document.createElement("img");return t.src=e.url,e.alt&&(t.alt=e.alt),Object.assign(t.style,{maxWidth:e.width?`${e.width}px`:"100%",maxHeight:e.height?`${e.height}px`:"auto",borderRadius:"8px",objectFit:"cover"}),t}buildBackground(e,t){if(!t)return{backgroundColor:"#ffffff",color:"#1a1a1a"};switch(e){case"SOLID":return{backgroundColor:t.color||"#ffffff",color:this.contrastColor(t.color||"#ffffff")};case"GRADIENT":{let i=t.gradientFrom||"#667eea",r=t.gradientTo||"#764ba2";return{background:`linear-gradient(${this.gradientDirection(t.gradientDirection)}, ${i}, ${r})`,color:"#ffffff"}}case"GLASS":return{backgroundColor:"rgba(255,255,255,0.15)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:"1px solid rgba(255,255,255,0.2)",color:"#ffffff"};case"PATTERN":return{backgroundColor:t.color||"#ffffff",color:this.contrastColor(t.color||"#ffffff")};default:return{backgroundColor:"#ffffff",color:"#1a1a1a"}}}resolveContainerColors(e,t,i){let r=i.color||"#1a1a1a",s="#ffffff";if(t)switch(e){case"SOLID":case"PATTERN":s=t.color||"#ffffff";break;case"GRADIENT":s=t.gradientFrom||"#667eea";break;case"GLASS":s="#1a1a1a";break}return{textColor:r,bgColor:s}}gradientDirection(e){return e?{"to-right":"to right","to-left":"to left","to-bottom":"to bottom","to-top":"to top","to-bottom-right":"to bottom right","to-bottom-left":"to bottom left","to-top-right":"to top right","to-top-left":"to top left"}[e]||e:"to right"}contrastColor(e){let t=e.replace("#","");if(t.length<6)return"#1a1a1a";let i=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),s=parseInt(t.substring(4,6),16);return(.299*i+.587*r+.114*s)/255>.5?"#1a1a1a":"#ffffff"}getSlideInStart(e){switch(e){case"BOTTOM_LEFT":case"SLIDE_LEFT":return"translateX(-100%)";case"BOTTOM_RIGHT":case"SLIDE_RIGHT":return"translateX(100%)";case"TOP_LEFT":return"translate(-100%, -20px)";case"TOP_RIGHT":return"translate(100%, -20px)";case"TOP":return"translateY(-100%)";case"BOTTOM":return"translateY(100%)";case"CENTER":default:return"translateY(20px)"}}animateOut(){return new Promise(e=>{if(!this.container){e();return}let t=()=>{this.container?.removeEventListener("transitionend",t),e()};this.container.addEventListener("transitionend",t),this.container.style.opacity="0",this.backdropElement&&(this.backdropElement.style.opacity="0"),setTimeout(e,400)})}handleAction(e){this.onAction?.(e)}clearCountdowns(){for(let e of this.countdownIntervals)clearInterval(e);this.countdownIntervals=[]}cleanup(){this.clearCountdowns(),this.container&&(this.container.remove(),this.container=null),this.backdropElement&&(this.backdropElement.remove(),this.backdropElement=null),this.showing=!1,this.onAction=null}}});var un={};Te(un,{RescueManager:()=>mi});var mi,dn=P(()=>{"use strict";sn();an();cn();mi=class{constructor(e,t){this.triggerEvaluator=null;this.campaigns=[];this.campaignStates=new Map;this.showStartTime=0;this.isDestroyed=!1;this.tracker=e,this.config=t,this.frequencyCap=new yt(t.tenantId),this.renderer=new wt}async initialize(){if(this.isDestroyed)return;let e=await this.fetchCampaigns();if(this.isDestroyed||(this.campaigns=this.parseCampaigns(e),this.campaigns.length===0))return;this.campaigns.sort((i,r)=>r.priority-i.priority);for(let i of this.campaigns){if(i.variations.length===0){i.state="capped";continue}this.frequencyCap.canShow(i.campaignId,i.frequencyCap)?i.state="armed":i.state="capped",this.campaignStates.set(i.campaignId,i.state)}let t=this.campaigns.filter(i=>i.state==="armed");t.length!==0&&(this.triggerEvaluator=new bt(t,(i,r)=>this.handleTriggerFired(i,r),this.config.activityDetector),this.triggerEvaluator.start(),this.log("Rescue initialized",{total:this.campaigns.length,armed:t.length}))}notifyEvent(e,t){this.triggerEvaluator?.notifyEvent(e,t)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.triggerEvaluator?.destroy(),this.triggerEvaluator=null,this.renderer.destroy(),this.campaigns=[],this.campaignStates.clear(),this.log("Rescue destroyed"))}handleTriggerFired(e,t){if(this.isDestroyed)return;let i=this.campaigns.find(r=>r.campaignId===e);if(!(!i||i.state!=="armed")){if(!this.frequencyCap.canShow(e,i.frequencyCap)){i.state="capped",this.campaignStates.set(e,"capped");return}if(this.renderer.isShowing()){i.state="triggered",this.campaignStates.set(e,"triggered");return}this.showCampaign(i,t)}}showCampaign(e,t){let i=this.selectVariation(e);if(!i)return;let r=e.variations.some(a=>!a.isControl),s=i.isControl&&r;e.state="shown",this.campaignStates.set(e.campaignId,"shown"),this.showStartTime=Date.now();let o={campaign_id:e.campaignId,campaign_type:e.type,variation_id:i.variationId,is_control:s,trigger_type:t.triggerType,position:i.content?.position??null,page_url:typeof window<"u"?window.location.href:""};if(s){this.tracker.trackSystemEvent("_grain_rescue_impression",o),this.frequencyCap.recordImpression(e.campaignId),this.tryShowNext();return}this.tracker.trackSystemEvent("_grain_rescue_impression",o),this.frequencyCap.recordImpression(e.campaignId),this.renderer.show(e.type,i,a=>{this.handleRenderAction(e.campaignId,i,t,a)})}async handleRenderAction(e,t,i,r){let s=Date.now()-this.showStartTime;switch(r.type){case"dismiss":await this.handleDismiss(e,t,i,s);break;case"link":this.handleConvert(e,t,i,"link",r.url,s);break;
29case"custom":this.handleConvert(e,t,i,"custom",r.eventName,s);break;case"coupon_copy":this.tracker.trackSystemEvent("_grain_rescue_coupon_copy",{campaign_id:e,variation_id:t.variationId,trigger_type:i.triggerType,coupon_code:r.code,display_duration_ms:s,page_url:typeof window<"u"?window.location.href:""});break}}async handleDismiss(e,t,i,r){this.tracker.trackSystemEvent("_grain_rescue_dismiss",{campaign_id:e,variation_id:t.variationId,trigger_type:i.triggerType,display_duration_ms:r,page_url:typeof window<"u"?window.location.href:""}),this.frequencyCap.recordDismiss(e);let s=this.campaigns.find(o=>o.campaignId===e);s&&(s.state="dismissed",this.campaignStates.set(e,"dismissed")),await this.renderer.hide(),this.tryShowNext()}async handleConvert(e,t,i,r,s,o){this.tracker.trackSystemEvent("_grain_rescue_convert",{campaign_id:e,variation_id:t.variationId,trigger_type:i.triggerType,action:r,url:s,display_duration_ms:o,page_url:typeof window<"u"?window.location.href:""}),this.frequencyCap.recordConvert(e);let a=this.campaigns.find(l=>l.campaignId===e);a&&(a.state="converted",this.campaignStates.set(e,"converted")),await this.renderer.hide(),this.tryShowNext()}tryShowNext(){if(!this.renderer.isShowing())for(let e of this.campaigns){if(e.state!=="triggered")continue;if(!this.frequencyCap.canShow(e.campaignId,e.frequencyCap)){e.state="capped",this.campaignStates.set(e.campaignId,"capped");continue}
29let t=e.triggers[0];if(t){this.showCampaign(e,t);return}}}selectVariation(e){let{variations:t}=e;if(t.length===0)return null;if(t.length===1)return t[0];let i=this.djb2(this.config.userId+e.campaignId),r=Math.abs(i)%100,s=0;for(let o of t)if(s+=o.trafficWeight,r<s)return o;return t[t.length-1]}djb2(e){let t=5381;for(let i=0;i<e.length;i++)t=(t<<5)+t+e.charCodeAt(i)|0;return t}async fetchCampaigns(){try{let e=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/rescue/campaigns`,t=await fetch(e);return t.ok?await t.json():(this.log("Failed to fetch rescue campaigns:",t.status),[])}catch(e){return this.log("Error fetching rescue campaigns:",e),[]}}parseCampaigns(e){let t=[];for(let i of e)try{let r=i.triggers.map(o=>this.parseTrigger(o)).filter(o=>o!==null);if(r.length===0)continue;let s=i.variations.map(o=>this.parseVariation(o)).filter(o=>o!==null);t.push({campaignId:i.campaignId,type:i.type,priority:i.priority,triggers:r,variations:s,fomoConfig:i.fomoConfig,frequencyCap:i.frequencyCap,state:"armed"})}catch{this.log("Failed to parse campaign:",i.campaignId)}return t}parseTrigger(e){let t=this.safeJsonParse(e.config);if(!t)return null;let i;switch(e.triggerType){case"PAGE_LOAD":i={type:"PAGE_LOAD",delay:t.delay||0};break;case"TIME_DELAY":i={type:"TIME_DELAY",delaySeconds:t.delaySeconds||0};break;case"EXIT_INTENT":i={type:"EXIT_INTENT",sensitivity:t.sensitivity||"medium"};break;case"SCROLL_DEPTH":i={type:"SCROLL_DEPTH",percentage:t.percentage||50};break;case"URL_MATCH":i={type:"URL_MATCH",pattern:t.pattern||"",matchType:t.matchType||"contains"};break;case"EVENT_RULE":i={type:"EVENT_RULE",eventName:t.eventName||"",operator:t.operator||"equals",value:t.value??null,property:t.property??null};break;default:return null}return{triggerId:e.triggerId,triggerType:e.triggerType,config:i}}parseVariation(e){let t=null;return e.content&&(t={position:e.content.position||"BOTTOM_RIGHT",backgroundType:e.content.backgroundType||"SOLID",backgroundConfig:this.safeJsonParse(e.content.backgroundConfig),textContent:this.safeJsonParse(e.content.textContent),widgets:this.parseWidgets(e.content.widgets),customCss:e.content.customCss||null}),{variationId:e.variationId,trafficWeight:e.trafficWeight,isControl:e.isControl,content:t}}parseWidgets(e){if(!e)return[];let t=this.safeJsonParse(e);return Array.isArray(t)?t:[]}safeJsonParse(e){if(!e||typeof e!="string")return null;try{return JSON.parse(e)}catch{return null}}log(...e){this.config.debug&&console.log("[Grain Rescue]",...e)}}});var hn={};Te(hn,{DebugOverlay:()=>vi});var U,yi,St,vi,pn=P(()=>{"use strict";de();Ae();gi();U=null,yi=!1,St=null,vi=class n{constructor(e){this.isDestroyed=!1;this.toolbarElement=null;this.panelElement=null;this.highlightElement=null;this.trackerHighlights=[];this.styleElement=null;this.mode="idle";this.isPanelOpen=!1;this.trackers=[];this.expandedTrackerId=null;this.mouseMoveListener=null;this.clickListener=null;this.keydownListener=null;this.erasableListeners=[];this.config=e}static async getInstance(e){return U&&!U.isDestroyed?U:(yi&&St||(yi=!0,St=(async()=>{try{return U=new n(e),await U.initialize(),U}finally{yi=!1}})()),St)}static hasInstance(){return U!==null&&!U.isDestroyed}async initialize(){this.log("Initializing debug overlay"),await this.loadTrackers(),this.injectStyles(),this.createToolbar(),this.createHighlightElement(),this.showHighlights(),this.setupKeyboardShortcuts(),this.log("Debug overlay initialized")}async loadTrackers(){try{let e=`${this.config.apiUrl}/v1/tenant/${encodeURIComponent(this.config.tenantId)}/trackers`,t=await fetch(e);t.ok&&(this.trackers=await t.json(),this.log("Loaded trackers:",this.trackers.length))}catch(e){this.log("Failed to load trackers:",e),this.trackers=[]}}injectStyles(){if(this.styleElement)return;let e=document.createElement("style");e.id="grain-debug-styles",e.textContent=`
30      /* ---- Toolbar ---- */
31      #grain-debug-toolbar {
32        position: fixed;
33        bottom: 20px;
34        right: 20px;
35        z-index: 999999;
36        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
37        display: flex;
38        align-items: center;
39        gap: 1px;
40        background: #18181b;
41        border-radius: 10px;
42        padding: 3px;
43        box-shadow: 0 2px 24px rgba(0,0,0,.18), 0 0 0 1px rgba(255,255,255,.06);
44        transition: opacity .2s, filter .2s;
45      }
46      #grain-debug-toolbar.grain-faded {
47        opacity: .25;
48        pointer-events: none;
49        filter: blur(1px);
50      }
51
52      .grain-tb-btn {
53        position: relative;
54        height: 36px;
55        border: none;
56        background: transparent;
57        color: #a1a1aa;
58        cursor: pointer;
59        display: flex;
60        align-items: center;
61        justify-content: center;
62        gap: 6px;
63        padding: 0 12px;
64        border-radius: 8px;
65        font-size: 12px;
66        font-weight: 500;
67        font-family: inherit;
68        transition: background .15s, color .15s;
69        white-space: nowrap;
70      }
71      .grain-tb-btn:hover { background: #27272a; color: #e4e4e7; }
72      .grain-tb-btn.active { background: #3f3f46; color: #fafafa; }
73
74      .grain-tb-btn svg { width: 15px; height: 15px; flex-shrink: 0; }
75      .grain-tb-btn .grain-badge {
76        position: absolute;
77        top: 3px;
78        right: 4px;
79        min-width: 14px;
80        height: 14px;
81        background: #a78bfa;
82        color: #fff;
83        font-size: 9px;
84        font-weight: 700;
85        border-radius: 7px;
86        display: flex;
87        align-items: center;
88        justify-content: center;
89        padding: 0 3px;
90        line-height: 1;
91      }
92
93      .grain-tb-sep {
94        width: 1px;
95        height: 20px;
96        background: #3f3f46;
97        flex-shrink: 0;
98      }
99
100      /* ---- Panel ---- */
101      #grain-debug-panel {
102        position: fixed;
103        bottom: 68px;
104        right: 20px;
105        width: 340px;
106        max-height: calc(100vh - 100px);
107        background: #18181b;
108        border: 1px solid #27272a;
109        border-radius: 12px;
110        box-shadow: 0 16px 48px rgba(0,0,0,.28), 0 0 0 1px rgba(255,255,255,.04);
111        z-index: 999999;
112        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
113        display: flex;
114        flex-direction: column;
115        overflow: hidden;
116        color: #e4e4e7;
117        transition: opacity .2s, filter .2s;
118      }
119      #grain-debug-panel.grain-faded {
120        opacity: .25;
121        pointer-events: none;
122        filter: blur(1px);
123      }
124
125      .grain-panel-header {
126        padding: 14px 16px;
127        display: flex;
128        align-items: center;
129        justify-content: space-between;
130        border-bottom: 1px solid #27272a;
131      }
132      .grain-panel-title {
133        font-size: 13px;
134        font-weight: 600;
135        color: #fafafa;
136        display: flex;
137        align-items: center;
138        gap: 8px;
139      }
140      .grain-panel-title .grain-dot {
141        width: 6px; height: 6px;
142        background: #22c55e;
143        border-radius: 50%;
144      }
145      .grain-panel-close {
146        background: none;
147        border: none;
148        color: #71717a;
149        cursor: pointer;
150        padding: 4px;
151        border-radius: 6px;
152        display: flex;
153        transition: color .15s, background .15s;
154      }
155      .grain-panel-close:hover { color: #e4e4e7; background: #27272a; }
156
157      /* ---- Tracker list ---- */
158      .grain-panel-body {
159        padding: 8px;
160        overflow-y: auto;
161        flex: 1;
162        scrollbar-width: thin;
163        scrollbar-color: #3f3f46 transparent;
164      }
165
166      .grain-tracker-card {
167        background: #27272a;
168        border-radius: 8px;
169        margin-bottom: 4px;
170        cursor: pointer;
171        transition: background .15s;
172        overflow: hidden;
173      }
174      .grain-tracker-card:hover { background: #303036; }
175      .grain-tracker-card.expanded { background: #303036; }
176
177      .grain-tracker-card-head {
178        padding: 10px 12px;
179        display: flex;
180        align-items: center;
181        gap: 10px;
182      }
183
184      .grain-tracker-indicator {
185        display: none;
186      }
187
188      .grain-tracker-info {
189        flex: 1;
190        min-width: 0;
191      }
192      .grain-tracker-name {
193        font-size: 12px;
194        font-weight: 600;
195        color: #fafafa;
196        white-space: nowrap;
197        overflow: hidden;
198        text-overflow: ellipsis;
199      }
200      .grain-tracker-meta {
201        font-size: 10px;
202        color: #71717a;
203        margin-top: 2px;
204        display: flex;
205        align-items: center;
206        gap: 6px;
207      }
208      .grain-tracker-type-badge {
209        font-size: 9px;
210        font-weight: 600;
211        padding: 1px 5px;
212        border-radius: 3px;
213        letter-spacing: .3px;
214      }
215      .grain-tracker-type-badge.metric { background: #1e293b; color: #7dd3fc; }
216      .grain-tracker-type-badge.conversion { background: #1c1917; color: #fdba74; }
217
218      .grain-tracker-chevron {
219        color: #52525b;
220        transition: transform .15s;
221        flex-shrink: 0;
222      }
223      .grain-tracker-card.expanded .grain-tracker-chevron { transform: rotate(90deg); }
224
225      /* ---- Tracker details ---- */
226      .grain-tracker-details {
227        padding: 0 12px 10px 30px;
228        display: none;
229      }
230      .grain-tracker-card.expanded .grain-tracker-details { display: block; }
231
232      .grain-detail-row {
233        display: flex;
234        justify-content: space-between;
235        align-items: baseline;
236        padding: 3px 0;
237        font-size: 11px;
238      }
239      .grain-detail-label { color: #71717a; }
240      .grain-detail-value {
241        color: #a1a1aa;
242        text-align: right;
243        max-width: 180px;
244        overflow: hidden;
245        text-overflow: ellipsis;
246        white-space: nowrap;
247        font-family: 'SF Mono', 'Fira Code', monospace;
248        font-size: 10px;
249      }
250      .grain-detail-value.confidence-high { color: #22c55e; }
251      .grain-detail-value.confidence-mid { color: #eab308; }
252      .grain-detail-value.confidence-low { color: #ef4444; }
253
254      .grain-detail-sep {
255        height: 1px;
256        background: #3f3f46;
257        margin: 6px 0;
258      }
259
260      .grain-tracker-actions {
261        display: flex;
262        gap: 6px;
263        margin-top: 8px;
264      }
265      .grain-tracker-action-btn {
266        flex: 1;
267        font-size: 11px;
268        font-weight: 500;
269        font-family: inherit;
270        padding: 5px 0;
271        border: none;
272        border-radius: 5px;
273        cursor: pointer;
274        transition: background .15s;
275      }
276      .grain-tracker-action-btn.locate {
277        background: #3f3f46;
278        color: #e4e4e7;
279      }
280      .grain-tracker-action-btn.locate:hover { background: #52525b; }
281      .grain-tracker-action-btn.delete {
282        background: transparent;
283        color: #f87171;
284        border: 1px solid #7f1d1d40;
285      }
286      .grain-tracker-action-btn.delete:hover { background: #7f1d1d30; }
287
288      /* ---- Empty state ---- */
289      .grain-empty-state {
290        text-align: center;
291        padding: 28px 16px;
292        color: #52525b;
293      }
294      .grain-empty-state p { margin: 4px 0; font-size: 12px; }
295      .grain-empty-state .grain-empty-hint { font-size: 11px; color: #3f3f46; }
296
297      /* ---- Panel footer ---- */
298      .grain-panel-footer {
299        padding: 10px 12px;
300        border-top: 1px solid #27272a;
301      }
302      .grain-end-btn {
303        width: 100%;
304        padding: 7px 0;
305        background: transparent;
306        border: 1px solid #3f3f46;
307        border-radius: 6px;
308        color: #71717a;
309        font-size: 11px;
310        font-weight: 500;
311        font-family: inherit;
312        cursor: pointer;
313        transition: all .15s;
314      }
315      .grain-end-btn:hover { border-color: #ef4444; color: #f87171; }
316
317      /* ---- Highlights ---- */
318      .grain-debug-highlight {
319        position: absolute;
320        pointer-events: none;
321        z-index: 999998;
322        transition: all .05s;
323      }
324      .grain-debug-highlight.pick-mode {
325        border: 2px solid #a78bfa;
326        background: rgba(167, 139, 250, .08);
327        border-radius: 3px;
328      }
329      .grain-debug-highlight.erase-mode {
330        border: 2px solid #f87171;
331        background: rgba(248, 113, 113, .08);
332        border-radius: 3px;
333      }
334
335      .grain-tracker-highlight {
336        position: absolute;
337        pointer-events: none;
338        border: 1.5px solid #a78bfa;
339        background: rgba(167, 139, 250, .05);
340        border-radius: 3px;
341        z-index: 999997;
342        transition: border-color .15s, background .15s, box-shadow .15s;
343      }
344      .grain-tracker-highlight.erasable {
345        pointer-events: auto;
346        cursor: pointer;
347        border-color: #a78bfa;
348      }
349      .grain-tracker-highlight.erasable:hover {
350        border-color: #f87171;
351        background: rgba(248, 113, 113, .12);
352        box-shadow: 0 0 0 3px rgba(248, 113, 113, .15);
353      }
354      .grain-tracker-label {
355        position: absolute;
356        top: -22px;
357        left: 0;
358        background: #18181b;
359        color: #c4b5fd;
360        padding: 2px 6px;
361        border-radius: 4px;
362        font-size: 10px;
363        font-weight: 500;
364        white-space: nowrap;
365        font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
366        border: 1px solid #3f3f46;
367      }
368
369      /* ---- Erase cursor hint ---- */
370      .grain-erase-cursor * { cursor: crosshair !important; }
371      .grain-pick-cursor * { cursor: crosshair !important; }
372
373      /* ---- Toast ---- */
374      .grain-toast {
375        position: fixed;
376        bottom: 68px;
377        right: 20px;
378        background: #18181b;
379        border: 1px solid #27272a;
380        color: #e4e4e7;
381        padding: 10px 16px;
382        border-radius: 8px;
383        font-size: 12px;
384        font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
385        box-shadow: 0 8px 24px rgba(0,0,0,.2);
386        z-index: 1000000;
387        opacity: 0;
388        transform: translateY(8px);
389        transition: opacity .2s, transform .2s;
390      }
391      .grain-toast.visible { opacity: 1; transform: translateY(0); }
392      .grain-toast.error { border-color: #7f1d1d; }
393    `,document.head.appendChild(e),this.styleElement=e}createToolbar(){if(this.toolbarElement)return;let e=document.createElement("div");e.id="grain-debug-toolbar",e.innerHTML=`
394      <button class="grain-tb-btn" data-action="panel" title="Trackers (Ctrl+Shift+G)">
395        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5"/><path d="M5 12l7-7 7 7"/></svg>
396        ${this.trackers.length>0?`<span class="grain-badge">${this.trackers.length}</span>`:""}
397      </button>
398      <div class="grain-tb-sep"></div>
399      <button class="grain-tb-btn" data-action="pick" title="Pick element">
400        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"/><path d="M13 13l6 6"/></svg>
401        Pick
402      </button>
403      <button class="grain-tb-btn" data-action="erase" title="Erase tracker">
404        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 20H7L3 16l8.5-8.5a2.83 2.83 0 014 0l4 4a2.83 2.83 0 010 4L12 23"/><path d="M6 13l4 4"/></svg>
405        Erase
406      </button>
407    `,document.body.appendChild(e),this.toolbarElement=e,e.addEventListener("click",t=>{let i=t.target.closest(".grain-tb-btn");if(!i)return;let r=i.dataset.action;r==="panel"?this.togglePanel():r==="pick"?this.toggleMode("pick"):r==="erase"&&this.toggleMode("erase")})}createPanel(){if(this.panelElement)return;let e=document.createElement("div");e.id="grain-debug-panel",e.innerHTML=this.renderPanelHTML(),document.body.appendChild(e),this.panelElement=e,this.bindPanelEvents()}renderPanelHTML(){return`
408      <div class="grain-panel-header">
409        <span class="grain-panel-title">
410          <span class="grain-dot"></span>
411          Grain Debug
412        </span>
413        <button class="grain-panel-close" title="Close (Esc)">
414          <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor">
415            <path d="M4.146 4.146a.5.5 0 01.708 0L7 6.293l2.146-2.147a.5.5 0 01.708.708L7.707 7l2.147 2.146a.5.5 0 01-.708.708L7 7.707l-2.146 2.147a.5.5 0 01-.708-.708L6.293 7 4.146 4.854a.5.5 0 010-.708z"/>
416          </svg>
417        </button>
418      </div>
419      <div class="grain-panel-body">
420        ${this.renderTrackersList()}
421      </div>
422      <div class="grain-panel-footer">
423        <button class="grain-end-btn" id="grain-end-session">End debug session</button>
424      </div>
425    `}renderTrackersList(){return this.trackers.length===0?`
426        <div class="grain-empty-state">
427          <p>No trackers yet</p>
428          <p class="grain-empty-hint">Use "Pick" to select an element</p>
429        </div>
430      `:this.trackers.map(e=>{let t=this.expandedTrackerId===e.trackerId,i=this.getTrackerMatchInfo(e),r="disabled";e.isEnabled&&(r=i.matched?"matched":"unmatched");let s="";i.confidence!==void 0&&(i.confidence>=.8?s="confidence-high":i.confidence>=.5?s="confidence-mid":s="confidence-low");let o=this.parseFingerprintDetails(e);return`
431        <div class="grain-tracker-card ${t?"expanded":""}" data-tracker-id="${e.trackerId}">
432          <div class="grain-tracker-card-head">
433            <span class="grain-tracker-indicator ${r}"></span>
434            <div class="grain-tracker-info">
435              <div class="grain-tracker-name">${this.escapeHtml(e.name)}</div>
436              <div class="grain-tracker-meta">
437                <span class="grain-tracker-type-badge ${e.type}">${e.type}</span>
438                <span>${this.escapeHtml(e.urlPattern||"all pages")}</span>
439              </div>
440            </div>
441            <svg class="grain-tracker-chevron" width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
442              <path d="M4.5 2l4 4-4 4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
443            </svg>
444          </div>
445          <div class="grain-tracker-details">
446            <div class="grain-detail-row">
447              <span class="grain-detail-label">Status</span>
448              <span class="grain-detail-value">${e.isEnabled?"Enabled":"Disabled"}</span>
449            </div>
450            <div class="grain-detail-row">
451              <span class="grain-detail-label">Match</span>
452              <span class="grain-detail-value ${s}">${i.matched?`${i.strategy} (${Math.round((i.confidence??0)*100)}%)`:"Not found"}</span>
453            </div>
454            <div class="grain-detail-row">
455              <span class="grain-detail-label">Scope</span>
456              <span class="grain-detail-value">${e.urlScope}</span>
457            </div>
458            ${o.tag?`
459              <div class="grain-detail-sep"></div>
460              <div class="grain-detail-row">
461                <span class="grain-detail-label">Element</span>
462                <span class="grain-detail-value">&lt;${this.escapeHtml(o.tag)}&gt;${o.id?"#"+this.escapeHtml(o.id):""}</span>
463              </div>
464              ${o.text?`<div class="grain-detail-row"><span class="grain-detail-label">Text</span><span class="grain-detail-value">${this.escapeHtml(o.text)}</span></div>`:""}
465              ${o.classes?`<div class="grain-detail-row"><span class="grain-detail-label">Classes</span><span class="grain-detail-value">${this.escapeHtml(o.classes)}</span></div>`:""}
466              ${o.ariaLabel?`<div class="grain-detail-row"><span class="grain-detail-label">Aria</span><span class="grain-detail-value">${this.escapeHtml(o.ariaLabel)}</span></div>`:""}
467              ${o.href?`<div class="grain-detail-row"><span class="grain-detail-label">Href</span><span class="grain-detail-value">${this.escapeHtml(o.href)}</span></div>`:""}
468            `:`
469              <div class="grain-detail-sep"></div>
470              <div class="grain-detail-row">
471                <span class="grain-detail-label">Selector</span>
472                <span class="grain-detail-value">${this.escapeHtml(e.selector.substring(0,60))}</span>
473              </div>
474            `}
475            <div class="grain-tracker-actions">
476              <button class="grain-tracker-action-btn locate" data-locate="${e.trackerId}">Locate</button>
477              <button class="grain-tracker-action-btn delete" data-delete="${e.trackerId}">Delete</button>
478            </div>
479          </div>
480        </div>
481      `}).join("")}bindPanelEvents(){this.panelElement&&(this.panelElement.querySelector(".grain-panel-close")?.addEventListener("click",()=>this.closePanel()),this.panelElement.querySelector("#grain-end-session")?.addEventListener("click",()=>this.endSession()),this.panelElement.querySelector(".grain-panel-body")?.addEventListener("click",e=>{let t=e.target,i=t.closest("[data-delete]");if(i){e.stopPropagation();let o=i.dataset.delete;this.deleteTracker(o);return}let r=t.closest("[data-locate]");if(r){e.stopPropagation();let o=r.dataset.locate,a=this.trackers.find(l=>l.trackerId===o);a&&this.scrollToTracker(a);return}let s=t.closest(".grain-tracker-card");if(s){let o=s.dataset.trackerId;this.expandedTrackerId=this.expandedTrackerId===o?null:o,this.updatePanel()}}))}getTrackerMatchInfo(e){let t=this.resolveTrackerElement(e);return t?{matched:!0,strategy:t.strategy,confidence:t.confidence}:{matched:!1}}parseFingerprintDetails(e){if(!e.fingerprint)return{};try{let t=JSON.parse(e.fingerprint);return{tag:t.tag,id:t.id,text:t.textContent?.substring(0,40),classes:t.classes?.join(", "),ariaLabel:t.ariaLabel,href:t.href}}catch{return{}}}toggleMode(e){this.mode===e?this.exitMode():this.enterMode(e)}enterMode(e){this.mode!=="idle"&&this.cleanupMode(),this.mode=e,this.toolbarElement?.classList.add("grain-faded"),this.panelElement?.classList.add("grain-faded"),this.updateToolbarButtons(),e==="pick"?(document.documentElement.classList.add("grain-pick-cursor"),this.mouseMoveListener=t=>this.handleMouseMove(t),this.clickListener=t=>this.handlePickClick(t),document.addEventListener("mousemove",this.mouseMoveListener,!0),document.addEventListener("click",this.clickListener,!0)):this.makeHighlightsErasable(),this.log(`${e} mode enabled`)}exitMode(){this.cleanupMode(),this.mode="idle",this.toolbarElement?.classList.remove("grain-faded"),this.panelElement?.classList.remove("grain-faded"),this.updateToolbarButtons(),this.log("Returned to idle")}cleanupMode(){document.documentElement.classList.remove("grain-pick-cursor","grain-erase-cursor"),this.mouseMoveListener&&(document.removeEventListener("mousemove",this.mouseMoveListener,!0),this.mouseMoveListener=null),this.clickListener&&(document.removeEventListener("click",this.clickListener,!0),this.clickListener=null),this.highlightElement&&(this.highlightElement.style.display="none",this.highlightElement.className="grain-debug-highlight"),this.clearErasableHighlights()}updateToolbarButtons(){this.toolbarElement&&this.toolbarElement.querySelectorAll(".grain-tb-btn").forEach(e=>{let t=e.dataset.action;e.classList.toggle("active",t===this.mode)})}handleMouseMove(e){if(this.mode!=="pick"||!this.highlightElement)return;let t=e.target;if(t.closest("#grain-debug-toolbar")||t.closest("#grain-debug-panel")){this.highlightElement.style.display="none";return}let i=t.getBoundingClientRect();this.highlightElement.style.display="block",this.highlightElement.className="grain-debug-highlight pick-mode",this.highlightElement.style.top=`${i.top+window.scrollY}px`,this.highlightElement.style.left=`${i.left+window.scrollX}px`,this.highlightElement.style.width=`${i.width}px`,this.highlightElement.style.height=`${i.height}px`}handlePickClick(e){if(this.mode!=="pick")return;let t=e.target;t.closest("#grain-debug-toolbar")||t.closest("#grain-debug-panel")||(e.preventDefault(),e.stopPropagation(),this.exitMode(),this.showCreateTrackerDialog(t))}makeHighlightsErasable(){this.trackerHighlights.length===0&&this.showHighlights();for(let e of this.trackerHighlights){e.classList.add("erasable");let t=e.dataset.trackerId;if(!t)continue;let i=()=>{this.deleteTracker(t)};e.addEventListener("click",i),this.erasableListeners.push({el:e,handler:i})}}clearErasableHighlights(){for(let{el:e,handler:t}of this.erasableListeners)e.classList.remove("erasable"),e.removeEventListener("click",t);this.erasableListeners=[]}showCreateTrackerDialog(e){let t=W(e),i=K(e),r=e.tagName.toLowerCase(),s=e.id,o=e.textContent?.trim().substring(0,50)||"",a="";s?a=`${s}_click`:o?a=o.toLowerCase().replace(/\s+/g,"_").substring(0,30)+"_click":a=`${r}_click`;let l=prompt(`Create tracker
482
483Element: <${r}>${s?"#"+s:""}
484${o?"Text: "+o+`
485`:""}
486Event name:`,a);l&&this.createTracker(l,t,i)}async createTracker(e,t,i){try{let r=`${this.config.apiUrl}/v1/tenant/${encodeURIComponent(this.config.tenantId)}/debug-sessions/${this.config.sessionId}/trackers`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,type:"metric",selector:t,fingerprint:JSON.stringify(i),urlScope:"contains",urlPattern:window.location.href})});if(!s.ok)throw new Error(`Failed: ${s.status}`);await this.loadTrackers(),this.refreshUI(),this.showToast(`Tracker "${e}" created`)}catch(r){this.log("Failed to create tracker:",r),this.showToast("Failed to create tracker",!0)}}async deleteTracker(e){let t=this.trackers.find(i=>i.trackerId===e);if(t)try{let i=`${this.config.apiUrl}/v1/tenant/${encodeURIComponent(this.config.tenantId)}/debug-sessions/${this.config.sessionId}/trackers/${encodeURIComponent(e)}`,r=await fetch(i,{method:"DELETE"});if(!r.ok)throw new Error(`Failed: ${r.status}`);await this.loadTrackers(),this.refreshUI(),this.showToast(`Deleted "${t.name}"`)}catch(i){this.log("Failed to delete tracker:",i),this.showToast("Failed to delete tracker",!0)}}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}showHighlights(){this.hideHighlights();for(let e of this.trackers)if(e.isEnabled)try{let t=this.resolveTrackerElement(e)?.element??null;if(!t)continue;let i=t.getBoundingClientRect(),r=document.createElement("div");r.className="grain-tracker-highlight",r.dataset.trackerId=e.trackerId,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`;let s=document.createElement("div");s.className="grain-tracker-label",s.textContent=e.name,r.appendChild(s),document.body.appendChild(r),this.trackerHighlights.push(r)}catch(t){this.log("Failed to highlight tracker:",e.name,t)}}hideHighlights(){for(let e of this.trackerHighlights)e.remove();this.trackerHighlights=[]}scrollToTracker(e){try{let t=this.resolveTrackerElement(e)?.element??null;t&&t.scrollIntoView({behavior:"smooth",block:"center"})}catch(t){this.log("Failed to scroll to tracker:",t)}}resolveTrackerElement(e){let t=null,i=null;if(e.fingerprint)try{t=JSON.parse(e.fingerprint),t&&typeof t=="object"&&(i=Ee(t))}catch{}if(i&&i.confidence>=.75)return i;try{let r=this.parseSelector(e.selector),s=r.type==="xpath"?this.findElementsByXPath(r.value):Array.from(document.querySelectorAll(r.value));if(s.length>0){let o=t?s.filter(a=>this.elementMatchesFingerprint(a,t)):[];return o.length>0?{element:o[0],strategy:"selector+fingerprint",confidence:o.length===1?.9:.75}:i||{element:s[0],strategy:"selector",confidence:.5}}}catch{}return i}parseSelector(e){let t=e.trim();return/^xpath\s*=/i.test(t)?{type:"xpath",value:t.replace(/^xpath\s*=/i,"").trim()}:/^css\s*=/i.test(t)?{type:"css",value:t.replace(/^css\s*=/i,"").trim()}:{type:t.startsWith("/")||t.startsWith("(")?"xpath":"css",value:t}}findElementsByXPath(e){let t=[];try{let i=document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(let r=0;r<i.snapshotLength;r++){let s=i.snapshotItem(r);s&&s.nodeType===Node.ELEMENT_NODE&&t.push(s)}}catch{return[]}return t}elementMatchesFingerprint(e,t){if(t.tag&&e.tagName.toLowerCase()!==t.tag||t.id&&e.id!==t.id||t.testId&&e.getAttribute("data-testid")!==t.testId||t.ariaLabel&&e.getAttribute("aria-label")!==t.ariaLabel||t.name&&e.getAttribute("name")!==t.name||t.textContent&&e.textContent?.trim().replace(/\s+/g," ").substring(0,100)!==t.textContent)return!1;if(t.href){let i=e.getAttribute("href");if(!i||this.normalizeComparableUrl(i)!==this.normalizeComparableUrl(t.href))return!1}if(t.classes?.length){let i=Array.from(e.classList);if(!t.classes.every(r=>i.includes(r)))return!1}return!0}normalizeComparableUrl(e){try{return new URL(e,window.location.origin).href.replace(/\/$/,"")}catch{return e.trim().replace(/\/$/,"")}}
486togglePanel(){this.isPanelOpen?this.closePanel():this.openPanel()}openPanel(){this.panelElement||this.createPanel(),this.panelElement&&(this.panelElement.style.display="flex"),this.isPanelOpen=!0}closePanel(){this.panelElement&&(this.panelElement.style.display="none"),this.isPanelOpen=!1}refreshUI(){this.updatePanel(),this.hideHighlights(),this.showHighlights(),this.updateToolbarBadge()}updatePanel(){if(!this.panelElement)return;let e=this.panelElement.querySelector(".grain-panel-body");e&&(e.innerHTML=this.renderTrackersList())}updateToolbarBadge(){if(!this.toolbarElement)return;let e=this.toolbarElement.querySelector('[data-action="panel"]');if(!e)return;let t=e.querySelector(".grain-badge");if(t)this.trackers.length>0?t.textContent=String(this.trackers.length):t.remove();else if(this.trackers.length>0){let i=document.createElement("span");i.className="grain-badge",i.textContent=String(this.trackers.length),e.appendChild(i)}}showToast(e,t=!1){document.querySelector(".grain-toast")?.remove();let i=document.createElement("div");i.className=`grain-toast${t?" error":""}`,i.textContent=e,document.body.appendChild(i),requestAnimationFrame(()=>{i.classList.add("visible")}),setTimeout(()=>{i.classList.remove("visible"),setTimeout(()=>i.remove(),200)},2500)}setupKeyboardShortcuts(){this.keydownListener=e=>{e.ctrlKey&&e.shiftKey&&e.key==="G"&&(e.preventDefault(),this.togglePanel()),e.key==="Escape"&&(this.mode!=="idle"?this.exitMode():this.isPanelOpen&&this.closePanel())},document.addEventListener("keydown",this.keydownListener)}async endSession(){try{let t=`${this.config.apiUrl}/v1/tenant/${encodeURIComponent(this.config.tenantId)}/debug-sessions/${this.config.sessionId}/end`;await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{}try{sessionStorage.removeItem("_grain_debug"),sessionStorage.removeItem("_grain_debug_session")}catch{}this.destroy();let e=new URL(window.location.href);e.searchParams.delete("grain_debug"),e.searchParams.delete("grain_session"),window.location.href=e.toString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}log(...e){this.config.debug&&console.log("[Grain Debug]",...e)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.cleanupMode(),this.hideHighlights(),this.keydownListener&&(document.removeEventListener("keydown",this.keydownListener),this.keydownListener=null),this.toolbarElement?.remove(),this.toolbarElement=null,this.panelElement?.remove(),this.panelElement=null,this.highlightElement?.remove(),this.highlightElement=null,this.styleElement?.remove(),this.styleElement=null,U=null,this.log("Debug overlay destroyed"))}}});var Oa={};Te(Oa,{GrainTag:()=>G,getInstance:()=>Et,identify:()=>Si,init:()=>xe,track:()=>wi}
486);j();j();function ae(){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 _e(n,e=2166136261){let t=e;for(let i=0;i<n.length;i++)t^=n.charCodeAt(i),t=Math.imul(t,16777619);return t>>>0}function Ie(n){return n.toString(16).padStart(8,"0")}function Cn(n,e){let t=new Date,i=t.toISOString().split("T")[0],r=[navigator.userAgent,navigator.language,screen.width,screen.height,screen.colorDepth,t.getTimezoneOffset(),navigator.hardwareConcurrency||"",navigator.maxTouchPoints||0].join("|"),s=`${n}|${i}|${e||""}|${r}`,o=_e(s,2166136261),a=_e(s,2731151600),l=_e(s,3735928559),c=_e(s,3405691582),u=Ie(o),h=Ie(a),p=Ie(l),m=Ie(c),v=(8|l>>>30&3).toString(16);return`${u}-${h.substring(0,4)}-4${h.substring(4,7)}-${v}${p.substring(1,4)}-${p.substring(4)}${m}`}var Me=class{constructor(e){this.explicitUserId=null;this.permanentId=null;this.cachedDailyId=null;this.cachedDailyDate=null;this.tenantId=e.tenantId,this.mode=e.mode,this.sessionId=ae(),this.deviceSalt=this.loadOrCreateDeviceSalt(),this.mode==="permanent"&&this.loadPermanentId()}loadOrCreateDeviceSalt(){if(typeof localStorage>"u")return null;try{let e=_(this.tenantId,"dsalt"),t=localStorage.getItem(e);return t||(t=ae(),localStorage.setItem(e,t)),t}catch{return null}}loadPermanentId(){if(!(typeof localStorage>"u"))try{let e=_(this.tenantId,"uid"),t=localStorage.getItem(e);t?this.permanentId=t:(this.permanentId=ae(),localStorage.setItem(e,this.permanentId))}catch{this.permanentId=ae()}}savePermanentId(e){if(!(typeof localStorage>"u"))try{let t=_(this.tenantId,"uid");localStorage.setItem(t,e),this.permanentId=e}catch{}}setMode(e){let t=this.mode!==e;this.mode=e,t&&e==="permanent"&&!this.permanentId&&this.loadPermanentId()}getMode(){return this.mode}setUserId(e){this.explicitUserId=e,e&&this.mode==="permanent"&&this.savePermanentId(e)}getDailyId(){let e=new Date().toISOString().split("T")[0];return this.cachedDailyId&&this.cachedDailyDate===e?this.cachedDailyId:(this.cachedDailyId=Cn(this.tenantId,this.deviceSalt),this.cachedDailyDate=e,this.cachedDailyId)}getUserId(){return this.explicitUserId?this.explicitUserId:this.mode==="permanent"?(this.permanentId||this.loadPermanentId(),this.permanentId||this.getDailyId()):this.getDailyId()}getSessionId(){return this.sessionId}hasExplicitId(){return!!this.explicitUserId}getState(){return{mode:this.mode,userId:this.getUserId(),sessionId:this.sessionId,isExplicit:this.hasExplicitId()}}clear(){if(this.explicitUserId=null,this.permanentId=null,this.sessionId=ae(),typeof localStorage<"u")try{localStorage.removeItem(_(this.tenantId,"uid"))}catch{}}};var En={apiUrl:"https://clientapis.grainql.com",tenantId:"",batchSize:50,flushInterval:5e3,retryAttempts:3,retryDelay:1e3},Le=class{constructor(e,t=!1){this.queue=[];this.flushTimer=null;this.isDestroyed=!1;this.boundHandleUnload=null;this.boundHandleVisibility=null;this.config={...En,...e},this.debug=t,this.startFlushTimer(),this.setupUnloadHandler()}log(...e){this.debug&&console.log("[Grain Tag]",...e)}startFlushTimer(){typeof window>"u"||(this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=window.setInterval(()=>{this.queue.length>0&&this.flush().catch(e=>this.log("Auto-flush error:",e))},this.config.flushInterval))}setupUnloadHandler(){typeof window>"u"||(this.boundHandleUnload=()=>{this.queue.length>0&&(this.sendWithBeacon([...this.queue]),this.queue=[])},this.boundHandleVisibility=()=>{document.visibilityState==="hidden"&&this.queue.length>0&&(this.sendWithBeacon([...this.queue]),this.queue=[])},window.addEventListener("beforeunload",this.boundHandleUnload),window.addEventListener("pagehide",this.boundHandleUnload),document.addEventListener("visibilitychange",this.boundHandleVisibility))}send(e,t){if(!this.isDestroyed&&(this.queue.push(e),this.log("Queued event:",e.eventName),t?.flush||this.queue.length>=this.config.batchSize)){let i=t?.transport??(t?.useBeacon?"beacon":"auto");i==="keepalive"?(this.sendWithKeepalive([...this.queue]),this.queue=[]):i==="beacon"?(this.sendWithBeacon([...this.queue]),this.queue=[]):this.flush().catch(r=>this.log("Flush error:",r))}}async flush(){if(this.queue.length===0)return;let e=[...this.queue];this.queue=[],await this.sendEvents(e)}async sendEvents(e){let t=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;for(let i=0;i<=this.config.retryAttempts;i++)try{let r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`HTTP ${r.status}`);this.log(`Sent ${e.length} events`);return}catch(r){if(i===this.config.retryAttempts){this.log("Failed to send events after retries:",r);return}let s=this.config.retryDelay*Math.pow(2,i);this.log(`Retry ${i+1} in ${s}ms`),await this.delay(s)}}sendWithBeacon(e){if(e.length===0)return!0;let t=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`,i=JSON.stringify(e);if(typeof navigator<"u"&&"sendBeacon"in navigator){let r=new Blob([i],{type:"application/json"});if(navigator.sendBeacon(t,r))return this.log(`Beaconed ${e.length} events`),!0}try{return fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:i,keepalive:!0}
486).catch(()=>{}),!0}catch{return!1}}sendWithKeepalive(e){if(e.length===0)return!0;let t=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`,i=JSON.stringify(e);try{return fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:i,keepalive:!0}).then(r=>{if(!r.ok){this.log(`Keepalive request failed: HTTP ${r.status}`);return}this.log(`Keepalive-sent ${e.length} events`)}).catch(r=>{this.log("Keepalive send failed:",r)}),!0}catch(r){return this.log("Keepalive send setup failed:",r),!1}}delay(e){return new Promise(t=>setTimeout(t,e))}beaconFlush(){this.queue.length>0&&(this.sendWithBeacon([...this.queue]),this.queue=[])}getQueueLength(){return this.queue.length}destroy(){this.isDestroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),typeof window<"u"&&this.boundHandleUnload&&(window.removeEventListener("beforeunload",this.boundHandleUnload),window.removeEventListener("pagehide",this.boundHandleUnload)),typeof document<"u"&&this.boundHandleVisibility&&document.removeEventListener("visibilitychange",this.boundHandleVisibility),this.boundHandleUnload=null,this.boundHandleVisibility=null,this.queue.length>0&&(this.sendWithBeacon([...this.queue]),this.queue=[])}};j();var De="1.0.0",xi=["necessary","analytics","functional"],Pe=class{constructor(e){this.state=null;this.listeners=[];this.tenantId=e.tenantId,this.mode=e.mode,this.loadState()}loadState(){if(!(typeof localStorage>"u"))try{let e=_(this.tenantId,"consent"),t=localStorage.getItem(e);t?this.state=JSON.parse(t):this.mode==="opt-out"&&(this.state={granted:!0,categories:[...xi],timestamp:Date.now(),version:De},this.saveState())}catch{}}saveState(){if(!(typeof localStorage>"u"||!this.state))try{let e=_(this.tenantId,"consent");localStorage.setItem(e,JSON.stringify(this.state))}catch{}}notifyListeners(){this.state&&this.listeners.forEach(e=>{try{e(this.state)}catch{}})}grant(e){let t=e||[...xi];this.state={granted:!0,categories:t,timestamp:Date.now(),version:De},this.saveState(),this.notifyListeners()}revoke(e){this.state?e?this.state={...this.state,categories:this.state.categories.filter(t=>!e.includes(t)),granted:this.state.categories.length>e.length,timestamp:Date.now()}:this.state={granted:!1,categories:[],timestamp:Date.now(),version:De}:this.state={granted:!1,categories:[],timestamp:Date.now(),version:De},this.saveState(),this.notifyListeners()}hasConsent(e){return this.mode==="auto"?this.state?.granted?e?this.state.categories.includes(e):!0:!1:this.mode==="opt-in"?this.state?.granted?e?this.state.categories.includes(e):!0:!1:this.mode==="opt-out"?this.state?this.state.granted?e?this.state.categories.includes(e):!0:!1:!0:!1}shouldWaitForConsent(){return this.mode==="opt-in"&&!this.state?.granted}getIdMode(){return this.mode==="auto"?this.state?.granted?"permanent":"cookieless":this.mode==="opt-in"?this.state?.granted?"permanent":"cookieless":this.mode==="opt-out"&&this.state?.granted!==!1?"permanent":"cookieless"}getState(){return this.state?{...this.state}:null}getMode(){return this.mode}onChange(e){this.listeners.push(e)}offChange(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}clear(){if(this.state=null,typeof localStorage<"u")try{localStorage.removeItem(_(this.tenantId,"consent"))}catch{}}};X();X();var Oe=class{constructor(e,t){this.currentPage=null;this.previousPage=null;this.pageViewCount=0;this.isDestroyed=!1;this.landingPage=null;this.originalPushState=null;this.originalReplaceState=null;this.boundHandleNavigation=null;this.tracker=e,this.config={stripQueryParams:!0,stripHash:!1,debug:!1,version:"1.0.0",...t},typeof window<"u"&&this.initialize()}initialize(){this.landingPage=this.getPagePath(),this.boundHandleNavigation=()=>this.handleNavigation(),this.trackPageView(),this.setupHistoryTracking(),this.config.stripHash||window.addEventListener("hashchange",this.boundHandleNavigation)}setupHistoryTracking(){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;let e=this,t=this.originalPushState,i=this.originalReplaceState;history.pushState=function(...r){t.apply(history,r),e.handleNavigation()},history.replaceState=function(...r){i.apply(history,r),e.handleNavigation()},window.addEventListener("popstate",this.boundHandleNavigation)}handleNavigation(){if(this.isDestroyed)return;this.getPagePath()!==this.currentPage&&this.trackPageView()}getPagePath(){let e=window.location.pathname;return this.config.stripQueryParams||(e+=window.location.search),!this.config.stripHash&&window.location.hash&&(e+=window.location.hash),e}trackPageView(){let e=this.tracker.hasConsent("analytics"),t=this.getPagePath();this.previousPage=this.currentPage,this.currentPage=t,this.pageViewCount++;let i={page:t,full_url:window.location.origin+window.location.pathname,timestamp:Date.now()},r=document.referrer||"",s=r?ce(r,window.location.href):"direct";if(r&&s!=="direct"){i.referrer=r;try{i.referrer_domain=new URL(r).hostname}catch{}}i.referrer_category=s,this.previousPage&&(i.previous_page=this.previousPage),this.landingPage&&(i.landing_page=this.landingPage);let o=le();o.utm_source&&(i.utm_source=o.utm_source),o.utm_medium&&(i.utm_medium=o.utm_medium),o.utm_campaign&&(i.utm_campaign=o.utm_campaign),o.utm_term&&(i.utm_term=o.utm_term),o.utm_content&&(i.utm_content=o.utm_c
486ontent),i.title=document.title,i.language=navigator.language,i.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,i.screen_resolution=`${screen.width}x${screen.height}`,i.viewport=`${window.innerWidth}x${window.innerHeight}`,e&&(i.session_id=this.tracker.getSessionId()),this.config.version&&(i.client_version=this.config.version),this.tracker.trackSystemEvent("page_view",i),this.previousPage&&this.tracker.trackSystemEvent("_grain_navigation",{from_page:this.previousPage,to_page:t,timestamp:Date.now()}),this.log("Page view tracked:",t)}log(...e){this.config.debug&&console.log("[Grain Tag Page]",...e)}getCurrentPage(){return this.currentPage}getPageViewCount(){return this.pageViewCount}destroy(){this.isDestroyed=!0,this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.boundHandleNavigation&&(window.removeEventListener("popstate",this.boundHandleNavigation),window.removeEventListener("hashchange",this.boundHandleNavigation),this.boundHandleNavigation=null)}};de();X();de();Ae();j();var ut=class{constructor(e,t){this.captured=!1;this.enabled=!1;this.tracker=e,this.config={maxSnapshotsPerDay:5,debug:!1,...t}}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}detectScrollContainer(){if(document.documentElement.scrollHeight-document.documentElement.clientHeight>50)return null;let t=["#pageContent","#pageContainer","[data-scroll-container]",".scroll-container",".main-content",'[role="main"]'],i=[];for(let a of t){let l=document.querySelector(a);l instanceof HTMLElement&&i.push(l)}let r=document.querySelectorAll("div, section, main, article");for(let a of r){if(!(a instanceof HTMLElement)||i.includes(a))continue;let l=window.getComputedStyle(a),c=l.overflow==="auto"||l.overflow==="scroll"||l.overflowY==="auto"||l.overflowY==="scroll",u=l.overflow==="hidden"||l.overflowY==="hidden";!c&&!u||a.scrollHeight<=a.clientHeight||a.getBoundingClientRect().height<window.innerHeight*.5||i.push(a)}let s=null,o=0;for(let a of i){let l=a.scrollHeight-a.clientHeight,c=a.scrollTop>0?1e5:0,u=l+c;u>o&&(o=u,s=a)}return s}buildSelector(e){if(e===document.documentElement)return"html";if(e===document.body)return"body";if(e.id)return`#${e.id}`;let t=[],i=e;for(;i&&i!==document.body&&i!==document.documentElement;){let r=i.tagName.toLowerCase();if(i.id){t.unshift(`#${i.id}`);break}if(i.parentElement&&Array.from(i.parentElement.children).filter(o=>o.tagName===i.tagName).length>1&&(r+=`:nth-child(${Array.from(i.parentElement.children).indexOf(i)+1})`),t.unshift(r),i=i.parentElement,t.length>=5)break}return t.join(" > ")}expandForSnapshot(e){let t=this.buildSelector(e),i=e.id||e.className.split(" ")[0]||e.tagName.toLowerCase(),r=[],s=e.parentElement;for(;s&&s!==document.documentElement;){let c=window.getComputedStyle(s);(c.overflow==="hidden"||c.overflowY==="hidden")&&r.push(this.buildSelector(s)),s=s.parentElement}for(let c of[document.documentElement,document.body]){let u=window.getComputedStyle(c);(u.overflow==="hidden"||u.overflowY==="hidden")&&r.push(c===document.documentElement?"html":"body")}let o=`${t} { height: auto !important; max-height: none !important; overflow: visible !important; overflow-y: visible !important; }`;for(let c of r)o+=`
487${c} { overflow: visible !important; overflow-y: visible !important; }`;let a=document.createElement("style");a.id="grain-snapshot-expand",a.textContent=o,document.head.appendChild(a),e.offsetHeight;let l=e.scrollHeight;return this.log("Expanded scroll container via <style>, fullPageHeight:",l),{fullPageHeight:l,scrollContainerId:i,restoreFn:()=>{a.remove(),this.log("Removed expansion <style> tag")}}}async capture(){if(!this.enabled||this.captured||!this.canUpload())return null;try{this.log("Waiting for page to settle before capturing DOM snapshot..."),await new Promise(c=>setTimeout(c,3e3)),this.log("Capturing DOM snapshot...");let e=this.detectScrollContainer(),t=null;e&&(this.log("Detected scroll container:",e.id||e.className||e.tagName),t=this.expandForSnapshot(e));let r=(await Promise.resolve().then(()=>(tn(),en))).snapshot(document,{maskAllInputs:!0,maskTextFn:c=>c.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
487/g,"*****"),inlineStylesheet:!0,blockClass:"grain-no-snapshot"});t&&t.restoreFn();let s={},o={},a={};this.buildElementMaps(document.documentElement,s,o,a);let l={snapshot:r,xpathMap:s,cssMap:o,fingerprintMap:a,timestamp:Date.now(),pageUrl:H(window.location.href),deviceType:Re(),viewportSize:{width:window.innerWidth,height:window.innerHeight},sessionId:this.tracker.getSessionId(),...t&&{fullPageHeight:t.fullPageHeight,scrollContainerId:t.scrollContainerId,isScrollContainer:!0}};return this.captured=!0,this.log("Snapshot captured successfully"),await this.upload(l),l}catch(e){return this.log("Snapshot capture failed:",e),null}}buildElementMaps(e,t,i,r,s=1){let o=e.__sn?.id||s;if(e instanceof HTMLElement&&(t[o]=W(e),i[o]=ue(e),this.isTrackableElement(e))){let l=K(e);r[o]=JSON.stringify(l)}let a=s+1;for(let l of e.children)a=this.buildElementMaps(l,t,i,r,a);return a}isTrackableElement(e){let t=e.tagName.toLowerCase();if(["button","a","input","select","textarea"].includes(t)||e.getAttribute("role")||e.getAttribute("data-grain-id")||e.getAttribute("data-testid")||e.getAttribute("onclick")||e.getAttribute("data-action"))return!0;try{if(window.getComputedStyle(e).cursor==="pointer")return!0}catch{}return!1}async upload(e){let t=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/snapshot`,i={rrwebSnapshot:e.snapshot,xpathMap:e.xpathMap,cssMap:e.cssMap,fingerprintMap:e.fingerprintMap,viewportWidth:e.viewportSize.width,viewportHeight:e.viewportSize.height};e.isScrollContainer&&e.fullPageHeight&&(i.fullPageHeight=e.fullPageHeight,i.scrollContainerId=e.scrollContainerId,i.isScrollContainer=!0);let r={sessionId:e.sessionId,pageUrl:e.pageUrl,snapshot:JSON.stringify(i),timestamp:e.timestamp,deviceType:e.deviceType};try{let s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`Upload failed: ${s.status}`);this.recordUpload(e.pageUrl),this.log("Snapshot uploaded successfully")}catch(s){this.log("Snapshot upload failed:",s)}}canUpload(){if(typeof localStorage>"u")return!0;try{let e=H(window.location.href),t=new Date().toISOString().split("T")[0],i=_(this.config.tenantId,"snapshots"),r=localStorage.getItem(i),s=r?JSON.parse(r):[],o=Date.now()-2*24*60*60*1e3;s=s.filter(c=>c.timestamp>o);let a=s.filter(c=>c.date===t);return a.length>=this.config.maxSnapshotsPerDay?(this.log("Daily snapshot limit reached"),!1):a.some(c=>this.stripQueryParams(c.url)===this.stripQueryParams(e))?(this.log("URL already captured today"),!1):!0}catch{return!0}}recordUpload(e){if(!(typeof localStorage>"u"))try{let t=new Date().toISOString().split("T")[0],i=_(this.config.tenantId,"snapshots"),r=localStorage.getItem(i),s=r?JSON.parse(r):[];s.push({url:e,date:t,timestamp:Date.now()});let o=Date.now()-2*24*60*60*1e3;s=s.filter(a=>a.timestamp>o),localStorage.setItem(i,JSON.stringify(s))}catch{}}stripQueryParams(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e.split("?")[0]}}log(...e){this.config.debug&&console.log("[Grain Tag Snapshot]",...e)}reset(){this.captured=!1}};var Ce=class Ce{constructor(){this.lastActivityTime=Date.now();this.isPageVisible=!0;this.boundActivityHandler=null;this.boundVisibilityHandler=null;typeof window<"u"&&this.initialize()}initialize(){this.boundActivityHandler=this.debounce(()=>{this.lastActivityTime=Date.now()},500),this.boundVisibilityHandler=()=>{this.isPageVisible=document.visibilityState==="visible",this.isPageVisible&&(this.lastActivityTime=Date.now())},Ce.ACTIVITY_EVENTS.forEach(e=>{document.addEventListener(e,this.boundActivityHandler,{passive:!0})}),document.addEventListener("visibilitychange",this.boundVisibilityHandler)}debounce(e,t){let i=null;return(...r)=>{i&&clearTimeout(i),i=window.setTimeout(()=>e(...r),t)}}isActive(e){return this.isPageVisible&&Date.now()-this.lastActivityTime<e}isVisible(){return this.isPageVisible}getIdleTime(){return Date.now()-this.lastActivityTime}destroy(){this.boundActivityHandler&&(Ce.ACTIVITY_EVENTS.forEach(e=>{document.removeEventListener(e,this.boundActivityHandler)}),this.boundActivityHandler=null),this.boundVisibilityHandler&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}};Ce.ACTIVITY_EVENTS=["mousemove","mousedown","keydown","scroll","touchstart","click"];var dt=Ce,ht=class{constructor(e,t={}){this.sectionDurations=new Map;this.lastScrollPosition=0;this.lastFilterReason="";this.activity=e,this.config={idleThreshold:3e4,maxSectionDuration:9e3,minScrollDistance:100,debug:!1,...t}}shouldTrack(){return this.activity.isVisible()?this.activity.isActive(this.config.idleThreshold)?!0:(this.lastFilterReason="user_idle",!1):(this.lastFilterReason="page_hidden",!1)}shouldTrackSection(e,t){return Math.abs(t-this.lastScrollPosition)>=this.config.minScrollDistance?(this.lastScrollPosition=t,this.sectionDurations.delete(e),{shouldTrack:!0,reason:"scroll_reset",resetAttention:!0}
487):(this.sectionDurations.get(e)||0)>=this.config.maxSectionDuration?{shouldTrack:!1,reason:"max_duration_reached",resetAttention:!1}:{shouldTrack:!0,reason:"ok",resetAttention:!1}}updateSectionDuration(e,t){let i=this.sectionDurations.get(e)||0;this.sectionDurations.set(e,i+t)}resetSection(e){this.sectionDurations.delete(e)}getLastFilterReason(){return this.lastFilterReason}getAttentionData(){let e=typeof window<"u"?window.scrollY:0,t=typeof document<"u"?document.documentElement.scrollHeight:0,i=typeof window<"u"?window.innerHeight:0;return{scrollDepthPx:e,scrollDepthPercent:t>i?Math.round(e/(t-i)*100):0,visibleElements:this.getVisibleElements(),totalAttentionMs:Array.from(this.sectionDurations.values()).reduce((r,s)=>r+s,0),idleMs:this.activity.getIdleTime()}}getVisibleElements(){if(typeof document>"u")return[];let e=[],t=window.innerHeight;return document.querySelectorAll("section, article, main, [data-section], [data-grain-section]").forEach(r=>{let s=r.getBoundingClientRect(),o=Math.max(0,s.top),a=Math.min(t,s.bottom),l=Math.max(0,a-o),c=s.height>0?Math.round(l/s.height*100):0;if(c>0){let u=r.id||r.getAttribute("data-section")||r.getAttribute("data-grain-section");if(u){let h=`section_${u}`;e.push({xpath:`//*[@id="${u}"]`,visibilityPercent:c,attentionMs:this.sectionDurations.get(h)||0})}}}),e}destroy(){this.sectionDurations.clear()}};gi();var pt=class{constructor(e,t){this.registeredTrackers=new Map;this.mutationObserver=null;this.initialized=!1;this.tracker=e,this.config=t}async initialize(){if(this.initialized){this.log("Already initialized");return}try{this.log("Fetching trackers from backend...");let e=await this.fetchTrackers();if(e.length===0){this.log("No trackers configured"),this.initialized=!0;return}this.log(`Found ${e.length} tracker(s):`,e.map(t=>t.name)),e.forEach(t=>{t.isEnabled&&this.registerTracker(t)}),this.startMutationObserver(),this.initialized=!0,this.reportTrackerHealth(),this.log("Custom tracker initialization complete")}catch(e){this.log("Failed to initialize custom trackers:",e),this.initialized=!0}}async fetchTrackers(){let e=`${this.config.apiUrl}/v1/tenant/${encodeURIComponent(this.config.tenantId)}/trackers`,t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch trackers: ${t.status} ${t.statusText}`);return t.json()}registerTracker(e){try{if(!this.shouldRunOnCurrentUrl(e)){this.log(`Tracker "${e.name}" skipped (URL scope: ${e.urlScope}, pattern: ${e.urlPattern})`);return}let t=this.findElements(e);t.length===0?this.log(`Tracker "${e.name}" registered but no elements found yet (selector: ${e.selector})`):this.log(`Tracker "${e.name}" found ${t.length} element(s)`);let i=this.createTrackerListener(e);t.forEach(r=>{r.addEventListener("click",i)}),this.registeredTrackers.set(e.trackerId,{definition:e,listener:i,elements:t})}catch(t){this.log(`Failed to register tracker "${e.name}":`,t)}}findElements(e){let t=null,i=null;if(e.fingerprint)try{t=JSON.parse(e.fingerprint),t&&typeof t=="object"&&(i=Ee(t))}catch{}let r=e.selector;try{let s=this.parseSelector(r),o=s.type==="xpath"?this.findElementsByXPath(s.value):Array.from(document.querySelectorAll(s.value));if(i&&i.confidence>=.75)return[i.element];if(o.length>0){let a=t?o.filter(l=>this.elementMatchesFingerprint(l,t)):[];return a.length===1?(this.log(`Tracker "${e.name}" narrowed selector fallback with fingerprint`,{totalMatches:o.length}),a):i?(this.log(`Tracker "${e.name}" using selector fallback after weak fingerprint match`,{strategy:i.strategy,confidence:i.confidence,selectorMatches:o.length,narrowedMatches:a.length}),a.length>1?a:[i.element]):o}return i?[i.element]:[]}catch(s){return this.log(`Invalid selector "${r}":`,s),i?[i.element]:[]}}elementMatchesFingerprint(e,t){if(t.tag&&e.tagName.toLowerCase()!==t.tag||t.id&&e.id!==t.id||t.testId&&e.getAttribute("data-testid")!==t.testId||t.ariaLabel&&e.getAttribute("aria-label")!==t.ariaLabel||t.name&&e.getAttribute("name")!==t.name||t.textContent&&e.textContent?.trim().replace(/\s+/g," ").substring(0,100)!==t.textContent)return!1;if(t.href){let i=this.normalizeComparableHref(e);if(!i||i!==this.normalizeComparableUrl(t.href))return!1}if(t.classes?.length){let i=Array.from(e.classList);if(!t.classes.every(r=>i.includes(r)))return!1}return!0}normalizeComparableHref(e){let t=e.getAttribute("href");return t?this.normalizeComparableUrl(t):null}normalizeComparableUrl(e){try{return new URL(e,window.location.origin).href.replace(/\/$/,"")}catch{return e.trim().replace(/\/$/,"")}}parseSelector(e){let t=e.trim();return/^xpath\s*=/i.test(t)?{type:"xpath",value:t.replace(/^xpath\s*=/i,"").trim()}:/^css\s*=/i.test(t)?{type:"css",value:t.replace(/^css\s*=/i,"").trim()}:{type:this.isXPath(t)?"xpath":"css",value:t}}isXPath(e){return e.startsWith("/")||e.startsWith("(")||e.includes("::")||/\b(ancestor|descendant|following|preceding|parent|child|attribute)\b/.test(e)}findElementsByXPath(e){let t=[];try{let i=document.evaluate(e,document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(let r=0;r<i.snapshotLength;r++){let s=i.snapshotItem(r);s&&s.nodeType===Node.ELEMENT_NODE&&t.push(s)}}catch(i){this.log(`XPath evaluation failed for "${e}":`,i)}return t}createTrackerListener(e){return t=>{let i=t.target,s=t.currentTarget??i;if(!s)return;this.log(`Tracker "${e.name}" fired on element:`,{tag:s.tagName,id:s.id,class:s.className});let o={tracker_id:e.trackerId,tracker_name:e.name,tracker_type:e.type.toLowerCase(),element_tag:s.tagName.toLowerCase(),element_id:s.id||void 0,element_class:s.className||void 0,element_text:s.textContent?.trim().substring(0,100)||void 0,element_href:s.href||void 0,page_url:window.location.href,page_path:window.location.pathname};this.config.version&&(o.client_version=this.config.version);let a=e.name.toLowerCase().replace(/\s+/g,"_"),c=s.closest("a[href]")?{flush:!0,transport:"keepalive"}:void 0;this.tracker.trackEvent(a,o,c)}}shouldRunOnCurrentUrl(e){switch(e.urlScope?.toLowerCase()){case"all":return!0;case"contains":{if(!e.urlPattern||e.urlPattern==="*")return!0;let i=this.normalizeUrl(window.location.href),r=this.normalizeUrl(e.urlPattern);return i.includes(r)}case"prefix":{if(!e.urlPattern||e.urlPattern==="*")return!0;let i=this.normalizeUrl(window.location.href),r=this.normalizeUrl(e.urlPattern);return i.startsWith(r)}case"equals":{if(!e.urlPattern||e.urlPattern==="*")return!0;let i=this.normalizeUrl(window.location.href),r=this.normalizeUrl(e.urlPattern);return i===r}default:return!0}}normalizeUrl(e){let t=e.trim();return t=t.replace(/^https?:\/\//i,""),t=t.split("?")[0].split("#")[0].trim(),t=t.replace(/^www\./i,""),!t||t==="/"?"*":(t.endsWith("/")||(t+="/"),t)}startMutationObserver(){if(typeof MutationObserver>"u"){this.log("MutationObserver not supported");return}this.mutationObserver=new MutationObserver(e=>{e.forEach(()=>
487{this.registeredTrackers.forEach(t=>{this.reattachTracker(t)})})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("MutationObserver started")}reattachTracker(e){try{let i=this.findElements(e.definition).filter(r=>!e.elements.includes(r));i.length>0&&(this.log(`Attaching tracker "${e.definition.name}" to ${i.length} new element(s)`),i.forEach(r=>{r.addEventListener("click",e.listener)}),e.elements.push(...i))}catch(t){this.log(`Failed to reattach tracker "${e.definition.name}":`,t)}}reportTrackerHealth(){if(!this.registeredTrackers||this.registeredTrackers.size===0)return;let e=[],t=0,i=0;for(let[,r]of this.registeredTrackers){let s=r.definition,o={matched:!1};if(s.fingerprint)try{let a=JSON.parse(s.fingerprint),l=Ee(a);l&&(o={matched:!0,matchStrategy:l.strategy,confidence:l.confidence})}catch{}!o.matched&&r.elements.length>0&&(o={matched:!0,matchStrategy:"legacy_selector",confidence:.5}),o.matched?t++:i++,e.push({trackerId:s.trackerId,name:s.name,...o})}this.tracker.trackEvent("_grain_tracker_health",{page_url:window.location.href,trackers:JSON.stringify(e),total:e.length,matched:t,unmatched:i})}destroy(){this.registeredTrackers.forEach(e=>{e.elements.forEach(t=>{t.removeEventListener("click",e.listener)})}),this.registeredTrackers.clear(),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.initialized=!1,this.log("Custom tracker manager destroyed")}getRegisteredTrackers(){return Array.from(this.registeredTrackers.values()).map(e=>e.definition)}log(...e){this.config.debug&&console.log("[Grain Tag Custom Trackers]",...e)}};var Ca=["email","phone","name","ip","address","ssn","credit_card","password"],Ea=new Set(["send_to","client_id","cookie_domain","cookie_expires","cookie_flags","cookie_path","cookie_update","is_legacy_converted","is_legacy_loaded","allow_display_features","allow_ad_personalization_signals","gtm.uniqueEventId","gtm.start"]);function ka(n,e){try{let t=[],i=2;for(let r=0;r<n.length;r++){let s=JSON.stringify(n[r]),o=(r>0?1:0)+s.length;if(i+o>e)return{json:`[${t.join(",")}]`,truncated:!0};t.push(s),i+=o}return{json:`[${t.join(",")}]`,truncated:!1}}catch{}return{json:"[]",truncated:!0}}function ft(n,e="",t=0){let i={};for(let[r,s]of Object.entries(n)){let o=e?`${e}.${r}`:r;if(s!=null)if(Array.isArray(s)){if(s.length===0)continue;if(s.every(l=>l===null||typeof l!="object"))i[o]=s.map(String).join(",");else{i[`${o}._count`]=s.length;let l=Math.min(s.length,3);for(let c=0;c<l;c++){let u=s[c];if(u!==null&&typeof u=="object"&&!Array.isArray(u)){let h=ft(u,`${o}.${c}`,t+1);Object.assign(i,h)}else u!=null&&(i[`${o}.${c}`]=u)}if(s.length>3){let{json:c,truncated:u}=ka(s,1e3);i[`${o}._json`]=c,u&&(i[`${o}._truncated`]=!0)}}}else if(typeof s=="object")if(t>=4)try{let a=JSON.stringify(s);a.length<=1e3?i[o]=a:(i[o]=a.substring(0,1e3),i[`${o}._truncated`]=!0)}catch{}else{let a=ft(s,o,t+1);Object.assign(i,a)}else i[o]=s}return i}var gt=class{constructor(e,t){this.connectors=[];this.patternCache=new Map;this.processedIndex=0;this.pushProcessed=new Set;this.recentEvents=new Map;this.pollTimer=null;this.originalPush=null;this.ourPush=null;this.pushOverrideActive=!1;this.isDestroyed=!1;this.tracker=e,this.config=t,t.connectors&&t.connectors.length>0&&(this.connectors=[...t.connectors].filter(i=>i.enabled).sort((i,r)=>i.priority-r.priority),this.log("Connectors loaded:",this.connectors.map(i=>i.id))),typeof window<"u"&&this.initialize()}initialize(){let e=window;Array.isArray(e.dataLayer)||(e.dataLayer=[],this.log("Created new dataLayer array"));let t=e.dataLayer;this.log("DataLayer has",t.length,"existing entries"),this.attachPushOverride(t),this.processExistingEntries(),this.pollTimer=setInterval(()=>this.poll(),2e3),this.log("DataLayer tracking initialized, connectors:",this.connectors.length>0?this.connectors.map(i=>i.id):"none (legacy mode)")}attachPushOverride(e){this.originalPush=e.push.bind(e),this.log("Attaching push override, current dataLayer.length:",e.length,"processedIndex:",this.processedIndex);let t=this;this.ourPush=function(...i){let r=e.length,s;try{s=t.originalPush(...i)}catch{s=Array.prototype.push.apply(e,i)}if(!t.pushOverrideActive)return s;for(let o=0;o<i.length;o++)try{let a=i[o];t.log("Push override intercepted entry at index",r+o,"\u2192",a?.event??a?.["1"]??"(no event key)"),t.processEntry(i[o],r+o)}catch(a){t.log("Error processing dataLayer entry:",a)}return t.processedIndex=e.length,s},e.push=this.ourPush,this.pushOverrideActive=!0}destroy(){if(this.isDestroyed=!0,this.pollTimer!==null&&(clearInterval(this.pollTimer),this.pollTimer=null),this.originalPush){try{let e=this.getDataLayer();e.push===this.ourPush&&(e.push=this.originalPush)}catch{}this.originalPush=null,this.ourPush=null}this.recentEvents.clear(),this.pushProcessed.clear(),this.patternCache.clear(),this.log("DataLayer manager destroyed")}getDataLayer(){let e=window;return Array.isArray(e.dataLayer)?e.dataLayer:[]}processExistingEntries(){let e=this.getDataLayer(),t=this.processedIndex,i=e.length-t;for(this.log("processExistingEntries: scanning",i,"entries from index",t,"to",e.length-1);this.processedIndex<e.length;){try{this.processEntry(e[this.processedIndex],this.processedIndex)}catch(r){this.log("Error processing existing dataLayer entry:",r)}this.processedIndex++}this.log("processExistingEntries: done, processedIndex now",this.processedIndex)}poll(){if(this.isDestroyed)return;let e=this.getDataLayer(),t=this.ourPush!=null&&e.push!==this.ourPush;e.length<this.processedIndex&&(this.log("Poll: dataLayer appears replaced or truncated \u2014 resetting processedIndex",{oldProcessedIndex:this.processedIndex,newDataLayerLength:e.length}),this.processedIndex=0,this.pushProcessed.clear());let i=e.length-this.processedIndex;(t||i>0)&&this.log("Poll:",{dataLayerLength:e.length,processedIndex:this.processedIndex,pendingEntries:i,pushReplaced:t,pushOverrideActive:this.pushOverrideActive,isArray:Array.isArray(e)}),t&&this.pushOverrideActive&&(this.log("Push override was replaced by another script \u2014 falling back to polling"),this.pushOverrideActive=!1),i>0&&(this.log("Poll processing",i,"new entries (index",this.processedIndex,"\u2192",e.length-1,")"),this.processExistingEntries()),this.pushProcessed.clear()}processEntry(e,t){if(this.isDestroyed){this.log("processEntry: skipped (destroyed), index:",t);return}if(!e||typeof e!="object"){this.log("processEntry: skipped (not an object), index:",t,"type:",typeof e);return}if(t<this.processedIndex){this.log("processEntry: skipped (below watermark), index:",t,"processedIndex:",this.processedIndex);return}if(this.pushProcessed.has(t)){this.log("processEntry: skipped (already processed by pu
487sh), index:",t);return}this.pushProcessed.add(t);let i=this.classifyEntry(e);if(!i){this.log("processEntry: skipped (unclassifiable), index:",t,"keys:",Object.keys(e).join(","));return}if(this.log("processEntry: classified",{index:t,origin:i.origin,eventName:i.eventName}),i.origin==="gtm"){this.log("processEntry: skipped (gtm internal)",i.eventName);return}if(i.origin==="gtag"){this.log("processEntry: skipped (gtag transport)",i.eventName);return}if(this.connectors.length>0){this.log("processEntry: routing to connector pipeline",i.eventName),this.processWithConnectors(i,t);return}if(this.log("processEntry: legacy mode for",i.eventName),i.eventName==="page_view"){this.log("processEntry: skipped (legacy page_view)");return}if(this.isDuplicate(i.eventName)){this.log("processEntry: skipped (dedup within",200,"ms)",i.eventName);return}let r=this.stripMetadata(i.properties),s=ft(r);s._dl_source="dataLayer",s._dl_origin=i.origin,s._dl_index=t,s._dl_timestamp=Date.now();let o=this.extractEcommerceFingerprint(i.properties);o&&(s._dl_ecom_fingerprint=o),this.tracker.track(i.eventName,s),this.log("Tracked dataLayer event (legacy):",i.eventName,"properties:",Object.keys(s).length,"keys")}updateConnectors(e){this.connectors=[...e].filter(t=>t.enabled).sort((t,i)=>t.priority-i.priority),this.patternCache.clear(),this.log("Connectors updated:",this.connectors.map(t=>t.id))}processWithConnectors(e,t){let i=e.eventName;if(this.isDuplicate(i)){this.log("Connector dedup: skipping duplicate",i);return}let r=!1;for(let s of this.connectors)if(!s.catch_all_unhandled&&!s.exclude_patterns.some(o=>this.wildcardMatch(o,i))&&s.include_patterns.some(o=>this.wildcardMatch(o,i))){this.executeConnector(s,e,t),r=!0;break}if(!r){let s=this.connectors.find(o=>o.catch_all_unhandled);s&&this.executeConnector(s,e,t)}}executeConnector(e,t,i){let r=this.stripMetadata(t.properties),s=ft(r),o=this.filterDimensions(s,e.include_dimensions,e.exclude_dimensions),{properties:a,skip:l}=this.applyModifiers(o,e.modifiers,e.id);if(l){this.log("Connector modifier skipped event:",t.eventName,e.id);return}let c=this.applyNameTransform(t.eventName,e.event_name_transform);a._dl_source="dataLayer",a._dl_origin=t.origin,a._dl_connector=e.id,a._dl_index=i,a._dl_timestamp=Date.now();let u=this.extractEcommerceFingerprint(t.properties);u&&(a._dl_ecom_fingerprint=u),this.tracker.track(c,a),this.log(`Connector [${e.id}] tracked:`,c)}getCompiledPattern(e){let t=this.patternCache.get(e);if(!t){let i=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");t=new RegExp("^"+i.replace(/\*/g,"(.*)")+"$"),this.patternCache.set(e,t)}return t}wildcardMatch(e,t){return this.getCompiledPattern(e).test(t)}filterDimensions(e,t,i){let r={...e};if(t.length>0){let s={};for(let[o,a]of Object.entries(r))t.some(l=>this.wildcardMatch(l,o))&&(s[o]=a);r=s}if(i.length>0){let s={};for(let[o,a]of Object.entries(r))i.some(l=>this.wildcardMatch(l,o))||(s[o]=a);r=s}return r}applyNameTransform(e,t){if(!t)return e;let i=t.split("|").map(r=>r.trim());for(let r of i){let s=r.split("\u2192").map(u=>u.trim());if(s.length!==2)continue;let[o,a]=s,c=this.getCompiledPattern(o).exec(e);if(c){let u=a;u=u.replace(/\$0/g,c[0]);for(let h=1;h<c.length;h++)u=u.replace(new RegExp(`\\$${h}`,"g"),c[h]);return u}}return e}applyModifiers(e,t,i){let r={...e};for(let s of t)if(s.startsWith("dedup:")){let o=s.slice(6),a=this.getNestedProp(r,o);a!==void 0&&(r._dedup_key=`${i}:${a}`)}else if(s.startsWith("min_duration:")){let o=parseInt(s.slice(13),10),a=r.duration;if(typeof a=="number"&&a<o)return{properties:r,skip:!0}}else if(s==="pii_strip")for(let o of Object.keys(r))Ca.some(a=>o.toLowerCase().includes(a))&&delete r[o];else s==="revenue_tracking"&&(r._revenue_tracking=!0);return{properties:r,skip:!1}}getNestedProp(e,t){let i=t.split("."),r=e;for(let s of i){if(r==null||typeof r!="object")return;r=r[s]}return r}classifyEntry(e){if("0"in e&&typeof e[0]=="string"){if(e[0]!=="event")return null;let i=e[1];if(typeof i!="string"||!i||i==="undefined")return null;let r=e[2]!==null&&typeof e[2]=="object"?e[2]:{};return{origin:"gtag",eventName:i,properties:r}}if("event"in e&&typeof e.event=="string"&&e.event.trim()!==""){let t=e.event.trim();if(t.startsWith("gtm."))return{origin:"gtm",eventName:t,properties:{}};let i={};for(let[r,s]of Object.entries(e))r!=="event"&&(i[r]=s);return{origin:"integration",eventName:t,properties:i}}return null}isDuplicate(e){let t=Date.now(),i=this.recentEvents.get(e);if(i!==void 0&&t-i<200)return!0;
487if(this.recentEvents.set(e,t),this.recentEvents.size>100){let r=t-400;for(let[s,o]of this.recentEvents)o<r&&this.recentEvents.delete(s)}return!1}stripMetadata(e){let t={};for(let[i,r]of Object.entries(e))Ea.has(i)||(t[i]=r);return t}extractEcommerceFingerprint(e){try{if(Array.isArray(e.items)){let i=e.items.map(r=>String(r.item_id??r.id??"")).filter(Boolean).sort();if(i.length>0)return i.join(",")}let t=e.ecommerce;if(t&&typeof t=="object"){for(let i of Object.values(t))if(i&&typeof i=="object"){let r=i,s=r.products??r.items;if(Array.isArray(s)){let o=s.map(a=>String(a.id??a.item_id??"")).filter(Boolean).sort();if(o.length>0)return o.join(",")}}}}catch{}return null}log(...e){this.config.debug&&console.log("[Grain Tag DataLayer]",...e)}};j();var rn=30*24*60*60*1e3,xa=24*60*60*1e3;function Ta(n,e){let t=e+n,i=2166136261;for(let r=0;r<t.length;r++)i^=t.charCodeAt(r),i=i*16777619>>>0;return i.toString(36)}function nn(){return Math.floor((Math.random()*2-1)*xa)}var mt=class{constructor(e){this.key=_(e,"seen_events"),this.salt=this.loadOrCreateSalt(e),this.events=this.load()}record(e){let t=Ta(e,this.salt),i=Date.now(),r=this.events[t],s;if(r===void 0)s="first";else if(i-r>rn)s="reactivated";else return"returning";return this.events[t]=i+nn(),this.persist(),s}loadOrCreateSalt(e){let t=_(e,"ev_salt");if(typeof localStorage>"u")return"";try{let i=localStorage.getItem(t);if(i)return i;let r=Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2);return localStorage.setItem(t,r),r}catch{return""}}load(){if(typeof localStorage>"u")return{};try{let e=localStorage.getItem(this.key);if(e){let t=JSON.parse(e);if(Array.isArray(t)){let s={};for(let o of t)typeof o=="string"&&(s[o]=Date.now()+nn());return s}if(typeof t!="object"||t===null)return{};let i=Date.now(),r={};for(let s of Object.keys(t)){let o=t[s];typeof o=="number"&&i-o<=rn&&(r[s]=o)}return r}}catch{}return{}}persist(){if(!(typeof localStorage>"u"))try{localStorage.setItem(this.key,JSON.stringify(this.events))}catch{}}};var G=class{constructor(e){this.pageTracker=null;this.heatmapTracker=null;this.snapshotManager=null;this.activityDetector=null;this.attentionManager=null;this.customTrackerManager=null;this.dataLayerManager=null;this.debugOverlay=null;this.rescueManager=null;this.isDestroyed=!1;this.boundUnloadHandler=null;this.sessionStartTime=Date.now();this.eventCount=0;this.interactionCount=0;this.consent={grant:e=>{this.consentManager.grant(e),this.log("Consent granted")},revoke:e=>{this.consentManager.revoke(e),this.log("Consent revoked")},status:()=>this.consentManager.getState()};this.config=Ci(e),this.consentManager=new Pe({tenantId:this.config.tenantId,mode:this.config.consentMode}),this.identity=new Me({tenantId:this.config.tenantId,mode:this.consentManager.getIdMode()}),this.sentEvents=new mt(this.config.tenantId),this.transport=new Le({apiUrl:this.config.apiUrl,tenantId:this.config.tenantId,batchSize:this.config.batchSize,flushInterval:this.config.flushInterval,retryAttempts:this.config.retryAttempts,retryDelay:1e3},this.config.debug),this.consentManager.onChange(t=>{this.identity.setMode(this.consentManager.getIdMode()),t.granted&&this.trackSystemEvent("_grain_consent_changed",{granted:!0,categories:t.categories,timestamp:Date.now()})}),typeof window<"u"&&this.initialize(),this.log("GrainTag initialized",{tenantId:this.config.tenantId,version:this.config.version,debug:this.config.debug})}async initialize(){if(this.trackSessionStart(),this.activityDetector=new dt,this.attentionManager=new ht(this.activityDetector,{debug:this.config.debug}),this.config.enablePageViews&&(this.pageTracker=new Oe(this,{tenantId:this.config.tenantId,debug:this.config.debug,version:this.config.version})),this.config.enableHeatmaps&&(this.heatmapTracker=new Ne(this,{debug:this.config.debug})),this.config.enableSnapshots&&(this.snapshotManager=new ut(this,{tenantId:this.config.tenantId,apiUrl:this.config.apiUrl,debug:this.config.debug}),this.checkSnapshotConfig()),this.customTrackerManager=new pt(this,{apiUrl:this.config.apiUrl,tenantId:this.config.tenantId,debug:this.config.debug,version:this.config.version}),this.config.enableDataLayer&&(this.dataLayerManager=new gt(this,{debug:this.config.debug})),typeof window<"u"&&(document.readyState==="complete"?this.customTrackerManager.initialize():window.addEventListener("load",()=>{this.customTrackerManager?.initialize()})),this.config.enableRescue){let e=async()=>
487{if(!this.isDestroyed)try{let{RescueManager:t}=await Promise.resolve().then(()=>(dn(),un));if(this.isDestroyed)return;this.rescueManager=new t(this,{apiUrl:this.config.apiUrl,tenantId:this.config.tenantId,userId:this.identity.getUserId(),activityDetector:this.activityDetector,debug:this.config.debug}),await this.rescueManager.initialize()}catch(t){this.log("Failed to initialize rescue module:",t)}};document.readyState==="complete"?e():window.addEventListener("load",()=>e())}Ei(this.config)&&this.initializeDebugMode(),this.setupUnloadHandler()}async checkSnapshotConfig(){if(!this.snapshotManager){this.log("No snapshot manager - skipping config check");return}this.log("Fetching snapshot configuration from backend...");try{let e=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`,t=this.identity.getUserId();this.log("Config request:",{url:e,userId:t});let i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:t,currentUrl:typeof window<"u"?window.location.href:void 0,immediateKeys:[],globalKeys:[],properties:{}})});if(!i.ok){this.log("Failed to fetch client config:",i.status),this.config.enableSnapshots&&(this.log("Enabling snapshots via local config (fallback)"),this.snapshotManager.enable(),setTimeout(()=>{this.log("Attempting snapshot capture (fallback mode)..."),this.snapshotManager?.capture()},2e3));return}let r=await i.json();this.log("Config response:",r);let s=r.configurations?.enableHeatmapSnapshot==="true";this.log("enableHeatmapSnapshot:",r.configurations?.enableHeatmapSnapshot,"parsed as:",s),s?(this.snapshotManager.enable(),this.log("Snapshots enabled via remote config"),this.log("Snapshot manager state:",{enabled:this.snapshotManager.isEnabled(),captured:this.snapshotManager.captured}),this.log("Scheduling snapshot capture in 2 seconds..."),setTimeout(()=>{this.log("Attempting to capture snapshot now..."),this.snapshotManager?.capture()},2e3)):this.log("Snapshots disabled via remote config")}catch(e){this.log("Error fetching client config:",e),this.config.enableSnapshots&&(this.log("Enabling snapshots via local config (error fallback)"),this.snapshotManager.enable(),setTimeout(()=>{this.log("Attempting snapshot capture (error fallback mode)..."),this.snapshotManager?.capture()},2e3))}}async initializeDebugMode(){let e=ki();if(!e)return;if(!await this.verifyDebugSession(e)){this.log("Debug session verification failed");return}try{let{DebugOverlay:i}=await Promise.resolve().then(()=>(pn(),hn));this.debugOverlay=await i.getInstance({sessionId:e,tenantId:this.config.tenantId,apiUrl:this.config.apiUrl,debug:this.config.debug}),this.log("Debug mode enabled")}catch(i){this.log("Failed to initialize debug overlay:",i)}}async verifyDebugSession(e){try{let t=`${this.config.apiUrl}/v1/tenant/${encodeURIComponent(this.config.tenantId)}/debug-sessions/verify`,i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,domain:window.location.hostname})});return i.ok?(await i.json()).valid===!0:!1}catch{return!1}}setupUnloadHandler(){this.boundUnloadHandler=()=>{this.trackSessionEnd(),this.transport.beaconFlush()},window.addEventListener("beforeunload",this.boundUnloadHandler),window.addEventListener("pagehide",this.boundUnloadHandler)}trackSessionStart(){let e=this.consentManager.hasConsent("analytics"),t={session_id:this.identity.getSessionId(),timestamp:this.sessionStartTime};if(typeof window<"u"){t.landing_page=window.location.pathname;let i=document.referrer||"",r=i?ce(i,window.location.href):"direct";if(i&&r!=="direct"){t.referrer=i;try{t.referrer_domain=new URL(i).hostname}catch{}}t.referrer_category=r;let s=le();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),e&&(t.screen_resolution=`${screen.width}x${screen.height}`,t.viewport=`${window.innerWidth}x${window.innerHeight}`,t.language=navigator.language,t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone)}t.occurrence=this.sentEvents.record("_grain_session_start"),this.trackSystemEvent("_grain_session_start",t)}trackSessionEnd(){let e=Date.now()-this.sessionStartTime;this.trackSystemEvent("_grain_session_end",{session_id:this.identity.getSessionId(),session_duration:Math.floor(e/1e3),event_count:this.eventCount,interaction_count:this.interactionCount,timestamp:Date.now()})}track(e,t,i){if(this.isDestroyed)return;let r={eventName:e,properties:t,timestamp:Date.now()},s=Ii(r,{tenantId:this.config.tenantId,identity:this.identity,consent:this.consentManager,sentEvents:this.sentEvents});this.transport.send(s,i),this.eventCount++,this.interactionCount++,this.log("Tracked event:",e)}trackEvent(e,t,i){this.track(e,t,i)}trackSystemEvent(e,t,i){if(this.isDestroyed)return;let r=this.consentManager.hasConsent("analytics"),s=this.identity.getMode()==="cookieless",o={...t};if(typeof window<"u"){o.device||(o.device=Lt()),o.browser||(o.browser=Dt()),o.os||(o.os=Pt());let c=Mt(this.config.tenantId);c&&(o.first_touch_source||(o.first_touch_source=c.source),o.first_touch_medium||(o.first_touch_medium=c.medium),o.first_touch_campaign||(o.first_touch_campaign=c.campaign),o.first_touch_referrer_category||(o.first_touch_referrer_category=c.referrer_category))}s||(o._minimal=!r,o._consent_status=r?"granted":"pending"),e==="page_view"&&(o.occurrence=this.sentEvents.record(e));let a={eventName:e,userId:this.identity.getUserId(),properties:o};this.transport.send(a,i),this.eventCount++,["page_view","_grain_heatmap_click","_grain_rage_click","_grain_dead_click","_grain_navigation"].includes(e)&&this.interactionCount++}identify(e){this.identity.setUserId(e),this.log("User identified:",e)}hasConsent(e){return this.consentManager.hasConsent(e)}getSessionId(){return this.identity.getSessionId()}isReady(){return!this.isDestroyed&&typeof window<"u"}async flush(){await this.transport.flush()}log(...e){this.config.debug&&console.log("[Grain Tag]",...e)}updateDataLayerConnectors(e){this.dataLayerManager&&this.dataLayerManager.updateConnectors(e)}
487destroy(){this.isDestroyed||(this.trackSessionEnd(),this.isDestroyed=!0,this.boundUnloadHandler&&(window.removeEventListener("beforeunload",this.boundUnloadHandler),window.removeEventListener("pagehide",this.boundUnloadHandler),this.boundUnloadHandler=null),this.pageTracker?.destroy(),this.heatmapTracker?.destroy(),this.activityDetector?.destroy(),this.attentionManager?.destroy(),this.customTrackerManager?.destroy(),this.dataLayerManager?.destroy(),this.rescueManager?.destroy(),this.debugOverlay?.destroy(),this.transport.destroy(),this.log("GrainTag destroyed"))}};var Pa={grant:()=>{},revoke:()=>{},status:()=>null};function Ra(){return{track:()=>{},identify:()=>{},consent:Pa,flush:()=>Promise.resolve(),destroy:()=>{},isReady:()=>!1,updateDataLayerConnectors:()=>{}}}var bi=typeof window<"u",A=null,ke=[],Ct=!1;function xe(n){if(!bi)return Ra();if(A)return console.warn("[Grain Tag] Already initialized. Use getInstance() to access the existing instance."),A;if(A=new G(n),ke.length>0){for(let e of ke)e.type==="track"?A.track(e.args[0],e.args[1]):e.type==="identify"&&A.identify(e.args[0]);ke.length=0}return A}function Et(){return A}function wi(n,e){if(A){A.track(n,e);return}bi&&(Ct||(console.warn("[Grain Tag] track() called before init(). Events will be queued and sent after initialization."),Ct=!0),ke.push({type:"track",args:[n,e]}))}function Si(n){if(A){A.identify(n);return}bi&&(Ct||(console.warn("[Grain Tag] identify() called before init(). Calls will be queued and sent after initialization."),Ct=!0),ke.push({type:"identify",args:[n]}))}typeof window<"u"&&window.__GRAIN_CONFIG__&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>xe()):setTimeout(()=>{Et()||xe()},0));typeof window<"u"&&(window.GrainTag={init:xe,getInstance:Et,track:wi,identify:Si,GrainTag:G});return vn(Oa);})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.