!function(e){!function(e){"use strict";var t,i,r,n,s,o,a,c,u,d,l,g,p,v,h,w,m,f,y,S=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},b=(e,t,i)=>(S(e,t,"read from private field"),i?i.call(e):t.get(e)),I=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},E=(e,t,i,r)=>(S(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),C=(e,t,i)=>(S(e,t,"access private method"),i);if(false){if("undefined"!=typeof navigator&&"ReactNative"===navigator.product&&"undefined"==typeof crypto)throw new Error("React Native does not have a built-in secure random generator. If you don’t need unpredictable IDs use `nanoid/non-secure`. For secure IDs, import `react-native-get-random-values` before Nano ID.");if("undefined"!=typeof msCrypto&&"undefined"==typeof crypto)throw new Error("Import file with `if (!window.crypto) window.crypto = window.msCrypto` before importing Nano ID to fix IE 11 support");if("undefined"==typeof crypto)throw new Error("Your browser does not have secure random generator. If you don’t need unpredictable IDs, you can use nanoid/non-secure.")}let D=(e=21)=>{let t="",i=crypto.getRandomValues(new Uint8Array(e));for(;e--;){let r=63&i[e];if(36>r)t+=r.toString(36);else if(62>r)t+=(r-26).toString(36).toUpperCase();else if(63>r)t+="_";else t+="-"}return t};const P="_grDebugMode",T=new class{isDebugEnabled(){return!!window.sessionStorage.getItem(P)}startDebug(){window.sessionStorage.setItem(P,"true")}},V=new class{get isLoggingEnabled(){return T.isDebugEnabled()}log(...e){this.displayLog("log",...e)}info(...e){this.displayLog("info",...e)}error(...e){if(e[0]instanceof Error)e.push(e[0].stack);this.displayLog("error",...e)}warn(...e){this.displayLog("warn",...e)}displayLog(e,...t){if(this.isLoggingEnabled)console[e](...t)}};function k(e){const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]+)`));if(t)return t[2]}function U(e,t,i=""){const r=new Date;r.setTime(r.getTime()+365*24*60*60*1e3),document.cookie=`${e}=${t}; expires=${r.toUTCString()}; path=/; ${i?`domain=${i}`:""}`}function _(e){const t=new RegExp(`[?&]${e}=([^&#]*)`).exec(window.location.href);return t?decodeURI(t[1]):null}function x(e){return!!e&&"object"==typeof e}function A(e,t){const i={...e};for(const r of Object.keys(t))if(e.hasOwnProperty(r)&&x(e[r])&&x(t[r])&&!Array.isArray(e[r]))i[r]=A(e[r],t[r]);else i[r]=t[r];return i}var L=(e=>(e["SetDomain"]="setDomain",e["SetListToken"]="setListToken",e["SetUserId"]="setUserId",e["SetEvent"]="setEvent",e["SetCookie"]="setCookie",e["SetAutoFunnelData"]="setAutoFunnelData",e["Push"]="push",e["SetCustomServiceWorkerPath"]="setCustomSwPath",e["ViewItem"]="viewItem",e["ViewCategory"]="viewCategory",e["LikeItem"]="likeItem",e["UnlikeItem"]="unlikeItem",e["WishListItem"]="wishlistItem",e["Purchase"]="orderPlaced",e["CartUpdate"]="cartUpdate",e["ShopifyAbandonedCart"]="shopifyAbandonedCart",e["SaveEvent"]="saveEvent",e["FlushEvents"]="flushEvents",e["SetUserDevice"]="setUserDevice",e["SetUserLocation"]="setUserLocation",e["SetVisitUrlPath"]="setVisitUrlPath",e["SetLastActivityDate"]="setLastActivityDate",e["SetIsNewVisitor"]="setIsNewVisitor",e["SetHasUserVisitPage"]="setHasUserVisitPage",e["SetRawEvent"]="setRawEvent",e["ImportScript"]="importScript",e["DelayScript"]="delayScript",e["InitScript"]="initScript",e))(L||{}),O=(e=>(e["UserEventSaved"]="userEventSaved",e["WebPushConsentAccepted"]="webPushConsentAccepted",e["WebPushCustomConsentRejected"]="webPushCustomConsentRejected",e["WebPushNativeConsentRejected"]="webPushNativeConsentRejected",e))(O||{});const N=10;class B{constructor(){this._cvar=[]}setTrackerUrl(e){this.trackerUrl=e}markAsEnabled(e){this.isEnabled=e}setUserId(e){this.uid=e}setCustomVariable(e,t,i){if(!this._cvar[e])this._cvar[e]=[];this._cvar[e].push(t),this._cvar[e].push(i)}setGenerationTime(){var e;if(this.gt_ms)return;const t=null==(e=performance.getEntriesByType("navigation")[0])?void 0:e.toJSON();if(t)this.gt_ms=Math.floor(t.responseEnd-t.requestStart)}trackEvent(e,t,i,r){this.trackPageView(Object.assign({e_c:e,e_a:t,e_n:i,...r&&{e_v:r}}))}getCustomVariable(){return JSON.stringify(Object.assign({},this._cvar))}static getScreenResolution(){return`${screen.width??N}x${screen.height??N}`}static encodeUrlParam(e){return`${encodeURIComponent(e[0])}=${encodeURIComponent(e[1])}`}getFullTrackerUrl(e){const t=new Date;return Object.entries({...e,...document.referrer&&{urlRef:document.referrer},url:window.location.href,uid:this.uid,_cvar:this.getCustomVariable(),h:t.getHours(),m:t.getMinutes(),s:t.getSeconds(),res:B.getScreenResolution(),gt_ms:this.gt_ms}).reduce(((e,t)=>void 0===t[1]?e:`${e}&${B.encodeUrlParam(t)}`),this.trackerUrl)}trackPageView(e){if(e||this.isEnabled)if(this.setGenerationTime(),window.fetch)fetch(this.getFullTrackerUrl(e),{method:"GET",mode:"no-cors"}).catch((e=>{V.error("Error while sending tracking data:",e)}));else new Image(1,1).src=this.getFullTrackerUrl(e)}}var F=(e=>(e["UuidHasBeenSet"]="grUuidHasBeenSet",e["PopupsRendererCustomUrl"]="grPopupsRendererCustomUrl",e))(F||{});class R{constructor(){I(this,t,new Proxy({},{get(e,t){if(t in e)return e[t];else return e[t]=[],e[t]}}))}addEvent(e,i){b(this,t)[e].push(i)}drainEvents(e){const i=b(this,t)[e];return b(this,t)[e]=[],i}getEvents(e){return b(this,t)[e]}hasDelayedEvents(e){return b(this,t)[e].length>0}}t=new WeakMap,i=new WeakMap,r=new WeakMap;const W=new class{constructor(){I(this,i,{}),I(this,r,new R)}publish(e,...t){var n;if(null==(n=b(this,i)[e])?void 0:n.length)b(this,i)[e].forEach((i=>{i(...t),V.log(`Event ${e} published with arguments'`,...t)}));else b(this,r).addEvent(e,t)}subscribe(e,t,n={}){const{preventEventDraining:s,ignoreQueuedEvents:o}=n;if(!b(this,i)[e])b(this,i)[e]=[];if(b(this,r).hasDelayedEvents(e)&&!o)if(s)b(this,r).getEvents(e).forEach((e=>t(...e)));else b(this,r).drainEvents(e).forEach((e=>t(...e)));b(this,i)[e].push(t)}unsubscribe(e,t){var r;const n=null==(r=b(this,i)[e])?void 0:r.indexOf(t);if(n>-1)b(this,i)[e].splice(n,1)}removeListeners(e){delete b(this,i)[e]}};var $,j,M=(e=>(e["DeviceType"]="debug_device_type",e["Location"]="debug_location",e["VisitUrlPath"]="debug_visit_url_path",e["BrowserStorageLastActivityDate"]="debug_browser_storage_last_activity_date",e["NewVisitor"]="debug_new_visitor",e["HasUserVisitPage"]="debug_has_user_visit_page",e["Events"]="debug_events",e))(M||{});function z(){const e=e=>{const t=sessionStorage.getItem(e);if(t){if([M.DeviceType,M.VisitUrlPath,M.Location].includes(e))return t;if(e===M.BrowserStorageLastActivityDate){const e=new Date(t);return isNaN(e.getTime())?void 0:e}if([M.NewVisitor,M.HasUserVisitPage,M.Events].includes(e))try{return JSON.parse(t)}catch(i){V.error(`Invalid debug data for: ${e}`)}}};return{enabled:true,data:{[M.DeviceType]:e(M.DeviceType),[M.BrowserStorageLastActivityDate]:e(M.BrowserStorageLastActivityDate),[M.Location]:e(M.Location),[M.NewVisitor]:e(M.NewVisitor),[M.VisitUrlPath]:e(M.VisitUrlPath),[M.HasUserVisitPage]:e(M.HasUserVisitPage),[M.Events]:e(M.Events)}}}function J(e,t,i){const r=ge.debugObject;ge.debugObject={...r,data:{...null==r?void 0:r.data,[e]:t}},sessionStorage.setItem(e,i||String(t))}function q(e){var t,i;return null==(i=null==(t=ge.debugObject)?void 0:t.data)?void 0:i[e]}function G(e,t){return ge.isDebug?t:e}(j=$||($={}))["PageVisit"]="visit",j["Popup"]="popup",j["ViewItem"]="view_item",j["ViewCategory"]="view_category",j["WishlistItem"]="wishlist_item",j["LikeItem"]="like_item",j["UnlikeItem"]="unlike_item",j["OrderPlaced"]="order_placed",j["Cart"]="cart_update",void(j["ShopifyAbandonedCart"]="shopify_webhook_abandoned_cart");let H=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=this.constructor.name}};class K extends H{constructor(e){super(e)}}const X={cartToken:"string",urlToken:"string",visitorEmail:"string"},Y=["cartToken","urlToken"];var Z,Q,ee,te,ie,re,ne,se,oe;(oe=Z||(Z={}))["Inline"]="inline",void(oe["Popup"]="popup"),(se=Q||(Q={}))["Hq"]="Hq",void(se["Us"]="Us"),void((ee||(ee={}))["UserAid"]="X-Aid"),(ne=te||(te={}))["Active"]="active",void(ne["Inactive"]="inactive"),(re=ie||(ie={}))["ReactSendWebPush"]="react_web_webpush",re["ReactCollectWebPushConsent"]="react_web_collect_webpush_subscription",re["FilterWebUrl"]="filter_web_url",re["FilterWebSubscribers"]="filter_web_subscriber",re["FilterLocation"]="filter_web_geolocation",re["FilterDevice"]="filter_web_device",re["FilterReturningVisitor"]="filter_web_returning_visitor",re["ConditionProductViewed"]="await_web_view_item_event",re["ConditionCategoryViewed"]="await_web_view_category_event",re["ConditionWebPushConsent"]="await_web_webpush_subscribe",re["ConditionProductLiked"]="await_web_like_item_event",re["TransferToBackend"]="react_backend_transfer",re["AwaitScroll"]="await_scroll",void(re["ShowPopup"]="react_popup"),n=new WeakMap;const ae=new class{constructor(){I(this,n,{[$.LikeItem]:[],[$.OrderPlaced]:[],[$.UnlikeItem]:[],[$.ViewCategory]:[],[$.ViewItem]:[],[$.WishlistItem]:[],[$.PageVisit]:[],[$.Popup]:[],[$.Cart]:[]})}getEvents(e){return Promise.resolve(b(this,n)[e])}getAllEvents(){return Promise.resolve(Object.values(b(this,n)).flat(1))}getAllECommerceEvents(){return Promise.resolve([...b(this,n)[$.ViewItem],...b(this,n)[$.ViewCategory],...b(this,n)[$.LikeItem],...b(this,n)[$.UnlikeItem],...b(this,n)[$.WishlistItem],...b(this,n)[$.OrderPlaced],...b(this,n)[$.Cart]])}getAllPopupEvents(){return Promise.resolve([...b(this,n)[$.Popup]])}saveEvent(e){return b(this,n)[e.eventType].push(e),Promise.resolve()}};var ce=(e=>(e["v2"]="v2",e["af"]="af",e["wp"]="wp",e["we"]="we",e["ec"]="ec",e))(ce||{}),ue=(e=>(e["v2"]="GRV2",e["af"]="GRAF",e["wp"]="GRWP",e["we"]="GRWE",e["ec"]="GREC",e))(ue||{});const de={[ce.af]:"autoFunnel",[ce.ec]:"ecommerce",[ce.v2]:"tracking",[ce.we]:"webEvents",[ce.wp]:"webPush"};s=new WeakSet,o=e=>de[e];const le=new class{constructor(){I(this,s)}setScriptInitialized(e){const t=C(this,s,o).call(this,e);window.__grIntegrationConfig[t].isModuleInitialized=true}isScriptInitialized(e){var t,i;const r=C(this,s,o).call(this,e);return(null==(i=null==(t=null==window?void 0:window.__grIntegrationConfig)?void 0:t[r])?void 0:i.isModuleInitialized)??false}},ge=new class{constructor(){this.scriptModuleManager=le}initialize(e){const{xsid:t,grid:i,clientLatestGrid:r,domain:n,aid:s,useNOStorage:o,useBetterSubscriberIdentification:a,isServedFromCustomDomain:c,scriptsDomain:u,scriptsVersion:d,tracking:l,isDebugMode:g,uuuid:p}=e;if(g)T.startDebug();window.__grIntegrationConfig=window.__grIntegrationConfig||{cData:{aid:s,grid:i,domain:n,useNOStorage:o,useBetterSubscriberIdentification:a,isServedFromCustomDomain:c,clientLatestGrid:r,uuuid:p},visitor:{email:null,eComId:null,xsid:t},tracking:{isModuleInitialized:false,isEnabled:l},webEvents:{isModuleInitialized:false,visitorApplicationEndpoint:null,automationJourneyGraphs:[],popupGraphs:[]},webPush:{isModuleInitialized:false,customSwPath:null,wpid:null,pushDomain:null,promptEndpoint:null},analyticsData:{scriptsDomain:u,scriptsVersion:d},ecommerce:{isModuleInitialized:false},autoFunnel:{isModuleInitialized:false},eventBus:W,temporaryEventsStorage:ae,debug:g?z():void 0,delayedScripts:{},scriptTypesInitialized:new Set}}canUseBackendForSubscriberIdentification(){return window.__grIntegrationConfig.cData.useBetterSubscriberIdentification}getUserAid(){return window.__grIntegrationConfig.cData.aid}getClientLatestGrid(){return window.__grIntegrationConfig.cData.clientLatestGrid}getUserAnalyticsDomain(){return window.__grIntegrationConfig.cData.domain}getUserUuid(){return window.__grIntegrationConfig.cData.uuuid}enablePopupDevMode(){window.__grIntegrationConfig.setCustomPopupRendererUrl=e=>{window.sessionStorage.setItem(F.PopupsRendererCustomUrl,e)}}getPopupRendererCustomUrl(){return window.sessionStorage.getItem(F.PopupsRendererCustomUrl)}setCustomSwPath(e){if("string"!=typeof e)throw new Error("Path type must be string");if(!e.match(/gr_sw_main.js|service-worker\/service-worker.js$/))throw new Error("Invalid sw file name");window.__grIntegrationConfig.webPush.customSwPath=e}getCustomSwPath(){var e;return null==(e=window.__grIntegrationConfig)?void 0:e.webPush.customSwPath}isTrackingEnabled(){return window.__grIntegrationConfig.tracking.isEnabled}isTrackingScriptServedFromCustomDomain(){return window.__grIntegrationConfig.cData.isServedFromCustomDomain}set visitorEmail(e){window.__grIntegrationConfig.visitor.email=e}get visitorEmail(){return window.__grIntegrationConfig.visitor.email}get pushWpid(){return window.__grIntegrationConfig.webPush.wpid}set pushWpid(e){window.__grIntegrationConfig.webPush.wpid=e}set pushDomain(e){window.__grIntegrationConfig.webPush.pushDomain=e}get pushDomain(){return window.__grIntegrationConfig.webPush.pushDomain}set pushPromptEndpoint(e){window.__grIntegrationConfig.webPush.promptEndpoint=e}get pushPromptEndpoint(){return window.__grIntegrationConfig.webPush.promptEndpoint}get eventBus(){return window.__grIntegrationConfig.eventBus}get canUseBackendStorageForEvents(){return window.__grIntegrationConfig.cData.useNOStorage}get webConnectScriptCdnUrl(){return window.__grIntegrationConfig.analyticsData.scriptsDomain}get webConnectCurrentScriptsVersion(){return window.__grIntegrationConfig.analyticsData.scriptsVersion}get isDebug(){var e,t;return!!(null==(t=null==(e=window.__grIntegrationConfig)?void 0:e.debug)?void 0:t.enabled)}set debugObject(e){window.__grIntegrationConfig.debug=e}get debugObject(){var e;return null==(e=window.__grIntegrationConfig)?void 0:e.debug}get delayedScripts(){var e;return(null==(e=window.__grIntegrationConfig)?void 0:e.delayedScripts)||{}}set delayedScripts(e){window.__grIntegrationConfig.delayedScripts=e}set visitorApplicationEndpoint(e){window.__grIntegrationConfig.webEvents.visitorApplicationEndpoint=e}get visitorApplicationEndpoint(){return window.__grIntegrationConfig.webEvents.visitorApplicationEndpoint}get userEventsStorageApplicationUrl(){return window.__grIntegrationConfig.ecommerce.webEventsSearchApplicationEndpoint}set userEventsStorageApplicationUrl(e){window.__grIntegrationConfig.ecommerce.webEventsSearchApplicationEndpoint=e}get temporaryEventsStorage(){return window.__grIntegrationConfig.temporaryEventsStorage}get automationJourneyGraphs(){return window.__grIntegrationConfig.webEvents.automationJourneyGraphs}get popupGraphs(){return window.__grIntegrationConfig.webEvents.popupGraphs}get visitorXsid(){return window.__grIntegrationConfig.visitor.xsid}},pe=204,ve=new class{retrieveXsid(){return((e,t)=>{const i=e.isTextResponse??(null==t?void 0:t.isTextResponse);return fetch(e,{...t,headers:{...null==t?void 0:t.headers,...(null==t?void 0:t.omitAidHeader)?{}:{[ee.UserAid]:ge.getUserAid()}}}).then((async e=>{if(e.ok){if(e.status===pe)return;return i?e.text():e.json()}const t=await e.text();return Promise.reject({statusCode:e.status,message:t})}))})(new URL("retrieveXsid",ge.getUserAnalyticsDomain()).href,{isTextResponse:true,omitAidHeader:true,credentials:"include"})}},he=new Map,we=(e,t)=>{if(!Array.isArray(e))switch(typeof e){case"string":e=[e];break;case"undefined":e=[];break;default:throw new TypeError(`Expected '${t}' to be a string or an array, but got a type of '${typeof e}'`)}return e.filter((e=>{if("string"!=typeof e){if(void 0===e)return false;throw new TypeError(`Expected '${t}' to be an array of strings, but found a type of '${typeof e}' in the array`)}return true}))};function me(e,t,i){return((e,t,i,r)=>{if(e=we(e,"inputs"),0===(t=we(t,"patterns")).length)return[];t=t.map((e=>((e,t)=>{t={caseSensitive:false,...t};const i=e+JSON.stringify(t);if(he.has(i))return he.get(i);const r="!"===e[0];if(r)e=e.slice(1);e=(e=>{if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")})(e).replace(/\\\*/g,"[\\s\\S]*");const n=new RegExp(`^${e}$`,t.caseSensitive?"":"i");return n.negated=r,he.set(i,n),n})(e,i)));const{allPatterns:n}=i||{},s=[];for(const o of e){let e;const i=[...t].fill(false);for(const[r,n]of t.entries())if(n.test(o))if(i[r]=true,e=!n.negated,!e)break;if(!(false===e||void 0===e&&t.some((e=>!e.negated))||n&&i.some(((e,i)=>!e&&!t[i].negated))))if(s.push(o),r)break}return s})(e,t,i,true).length>0}var fe,ye,Se,be,Ie,Ee,Ce,De,Pe,Te,Ve,ke,Ue,_e,xe,Ae,Le,Oe,Ne,Be,Fe,Re,We,$e,je,Me,ze,Je,qe,Ge,He,Ke,Xe,Ye,Ze,Qe,et,tt,it,rt;(rt=fe||(fe={}))["ShowWhenCondition"]="showWhenCondition",rt["VisitorsCondition"]="visitors",rt["DeviceCondition"]="device",rt["LocationCondition"]="location",rt["ECommerceCondition"]="ecommerce",rt["TriggerFrequency"]="frequency",rt["PreventDisplay"]="preventDisplay",void(rt["DateRange"]="dateRange"),(it=ye||(ye={}))["Mobile"]="mobile",it["Tablet"]="tablet",void(it["Desktop"]="desktop"),(tt=Se||(Se={}))["All"]="all",tt["New"]="new",void(tt["Returning"]="returning"),void((be||(be={}))["All"]="all"),(et=Ie||(Ie={}))["ConditionsLogicSeparator"]="conditionsLogicSeparator",void(et["ECommerceConditions"]="ecommerceConditions"),(Qe=Ee||(Ee={}))["Amount"]="amount",void(Qe["Date"]="date"),(Ze=Ce||(Ce={}))["And"]="and",void(Ze["Or"]="or"),(Ye=De||(De={}))["Exactly"]="exactly",Ye["LessThan"]="lessThan",void(Ye["MoreThan"]="moreThan"),(Xe=Pe||(Pe={}))["LastDays"]="lastDays",void(Xe["DateRange"]="dateRange"),(Ke=Te||(Te={}))["AnyProduct"]="any",Ke["AnyCategory"]="any",Ke["AnyProductLiked"]="any",Ke["AnyProductInPlacedOrder"]="any",Ke["AnyCategoryInPlacedOrder"]="any",Ke["AnyProductInUpdatedCart"]="any",void(Ke["AnyCategoryInUpdatedCart"]="any"),(He=Ve||(Ve={}))["PastEvents"]="filter",void(He["FutureEvents"]="await"),(Ge=ke||(ke={}))["Category"]="category",void(Ge["Product"]="product"),void((Ue||(Ue={}))["Product"]="product"),(qe=_e||(_e={}))["ViewProductOrCategory"]="productOrCategoryView",qe["LikeProduct"]="likeItem",qe["OrderPlaced"]="orderPlaced",void(qe["CartUpdated"]="cartUpdated"),(Je=xe||(xe={}))["Percent"]="percent",void(Je["Selector"]="selector"),(ze=Ae||(Ae={}))["Instantly"]="instantly",ze["Delay"]="delay",ze["Exit"]="exit",ze["Scroll"]="scroll",ze["Inactivity"]="inactivity",void(ze["Click"]="click"),(Me=Le||(Le={}))["AfterSubmit"]="submit",Me["AfterClose"]="close",void(Me["AfterTimes"]="timesAmount"),(je=Oe||(Oe={}))["Always"]="always",je["Session"]="session",void(je["EveryDays"]="everyDays"),($e=Ne||(Ne={}))["Exactly"]="equal",$e["LessThan"]="lessThan",void($e["MoreThan"]="moreThan"),(We=Be||(Be={}))["Exactly"]="equal",We["LessThan"]="lessThan",void(We["MoreThan"]="moreThan"),(Re=Fe||(Fe={}))[Re["InvalidCssSelector"]=1]="InvalidCssSelector",Re[Re["EmptyCssSelector"]=2]="EmptyCssSelector",Re[Re["CssSelectorTooLong"]=3]="CssSelectorTooLong",Re[Re["CssInvalidType"]=4]="CssInvalidType",Re[Re["InvalidTimeoutProperty"]=5]="InvalidTimeoutProperty",Re[Re["ShowWhenScrollPercentInvalidValueType"]=6]="ShowWhenScrollPercentInvalidValueType",Re[Re["ShowWhenScrollPercentValueOutOfBound"]=7]="ShowWhenScrollPercentValueOutOfBound",Re[Re["VisitorTriggerEmpty"]=8]="VisitorTriggerEmpty",Re[Re["VisitorTriggerInvalidProperty"]=9]="VisitorTriggerInvalidProperty",Re[Re["DevicesTriggerEmpty"]=10]="DevicesTriggerEmpty",Re[Re["DevicesTriggerInvalidValue"]=11]="DevicesTriggerInvalidValue",Re[Re["FrequencyEmptyTrigger"]=12]="FrequencyEmptyTrigger",Re[Re["FrequencyTriggerInvalidName"]=13]="FrequencyTriggerInvalidName",Re[Re["FrequencyTriggerNDaysInvalidPropertyValue"]=14]="FrequencyTriggerNDaysInvalidPropertyValue",Re[Re["FrequencyTriggerNDaysEmptyValue"]=15]="FrequencyTriggerNDaysEmptyValue",Re[Re["PreventDisplayTriggerInvalidName"]=16]="PreventDisplayTriggerInvalidName",Re[Re["PreventDisplayTriggerAfterTimesNoValue"]=17]="PreventDisplayTriggerAfterTimesNoValue",Re[Re["PreventDisplayTriggerAfterTimesInvalidValue"]=18]="PreventDisplayTriggerAfterTimesInvalidValue",Re[Re["DateRangeInvalidFromDate"]=19]="DateRangeInvalidFromDate",Re[Re["DateRangeInvalidToDate"]=20]="DateRangeInvalidToDate",Re[Re["DateRangeDateFromAfterDateTo"]=21]="DateRangeDateFromAfterDateTo",Re[Re["DateRangeToBeforeCurrentTime"]=22]="DateRangeToBeforeCurrentTime",Re[Re["LocationEmptyTrigger"]=23]="LocationEmptyTrigger",Re[Re["LocationInvalidType"]=24]="LocationInvalidType",Re[Re["LackOfLogicSeparator"]=25]="LackOfLogicSeparator",Re[Re["LackOfTriggerConditions"]=26]="LackOfTriggerConditions",Re[Re["InvalidTriggerConditions"]=27]="InvalidTriggerConditions",Re[Re["NoProductOrCategorySelected"]=28]="NoProductOrCategorySelected",Re[Re["ProductInvalidType"]=29]="ProductInvalidType",Re[Re["CategoryInvalidType"]=30]="CategoryInvalidType",Re[Re["AmountInvalidConditionName"]=31]="AmountInvalidConditionName",Re[Re["AmountInvalidConditionValueType"]=32]="AmountInvalidConditionValueType",Re[Re["DateInvalidConditionName"]=33]="DateInvalidConditionName",Re[Re["DateLastDaysInvalidConditionValue"]=34]="DateLastDaysInvalidConditionValue",Re[Re["DateDateRangeInvalidConditionValue"]=35]="DateDateRangeInvalidConditionValue",Re[Re["DateDateRangeFromInvalidValue"]=36]="DateDateRangeFromInvalidValue",Re[Re["DateDateRangeToInvalidValue"]=37]="DateDateRangeToInvalidValue",Re[Re["DateDateRangeDateFromAfterDateTo"]=38]="DateDateRangeDateFromAfterDateTo",Re[Re["PopupTriggerInvalidName"]=39]="PopupTriggerInvalidName",Re[Re["PopupTriggerLackOfValuesInLikeItemTrigger"]=40]="PopupTriggerLackOfValuesInLikeItemTrigger",Re[Re["PopupTriggerLikeItemInvalidValues"]=41]="PopupTriggerLikeItemInvalidValues",Re[Re["PopupTriggerOrderPlacedNoConditions"]=42]="PopupTriggerOrderPlacedNoConditions",Re[Re["PopupTriggerOrderPlacedInvalidProducts"]=43]="PopupTriggerOrderPlacedInvalidProducts",Re[Re["PopupTriggerOrderPlacedInvalidCategories"]=44]="PopupTriggerOrderPlacedInvalidCategories",Re[Re["PopupTriggerCartUpdatedNoConditions"]=45]="PopupTriggerCartUpdatedNoConditions",Re[Re["PopupTriggerCartUpdatedInvalidProducts"]=46]="PopupTriggerCartUpdatedInvalidProducts",Re[Re["PopupTriggerCartUpdatedInvalidCategories"]=47]="PopupTriggerCartUpdatedInvalidCategories",Re[Re["PopupTriggerPriceValueConditionInvalidComparator"]=48]="PopupTriggerPriceValueConditionInvalidComparator",Re[Re["PopupTriggerPriceValueConditionInvalidValue"]=49]="PopupTriggerPriceValueConditionInvalidValue",Re[Re["PopupTriggerProductsAmountValueConditionInvalidComparator"]=50]="PopupTriggerProductsAmountValueConditionInvalidComparator",Re[Re["PopupTriggerProductsAmountValueConditionInvalidValue"]=51]="PopupTriggerProductsAmountValueConditionInvalidValue",void(Re[Re["PopupTriggerInvalidTriggerType"]=52]="PopupTriggerInvalidTriggerType");class nt extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=this.constructor.name}}class st extends nt{constructor(){super("Failed to parse data from JSON string")}}var ot=(e=>(e["visitorUuid"]="gaVisitorUuid",e["visitorValuable"]="gaIsValuable",e["VisitorEmail"]="gaVisitorEId",e["VisitorResubscribed"]="gaVisitorResubscribed",e["NotificationConsentStatus"]="gaNotificationConsent",e["NotificationConsentAcceptedFromPrompt"]="gaWpnConAcc",e["NotificationConsentCustomPromptRejectedDEPRECATED"]="gaWpnConRej-{promptId}",e["NotificationConsentCustomPromptRejected"]="gaWpnConRej-promptId",e))(ot||{}),at=(e=>(e[e["OneYear"]=31536e6]="OneYear",e[e["TwoWeeks"]=12096e5]="TwoWeeks",e))(at||{}),ct=(e=>(e["Show"]="show",e["Close"]="close",e["Submit"]="submit",e))(ct||{}),ut=(e=>(e["One"]="1.0",e))(ut||{}),dt=(e=>(e["Web"]="web",e["Mobile"]="mobile",e))(dt||{});const lt=new class{constructor(){this.timer=Date.now()}getCurrentVisitOnPageTime(){return Date.now()-this.timer}};var gt=(e=>(e[e["Mobile"]=480]="Mobile",e[e["Tablet"]=768]="Tablet",e))(gt||{});const pt=Symbol("DeviceService");class vt{constructor(e){if(new.target===vt&&e!==pt)throw new Error(`Invalid ${new.target.name} constructor`)}detectDeviceTypeByScreenWidth(e){var t;const{availWidth:i,availHeight:r}=screen;let n=null==(t=screen.orientation)?void 0:t.type;if(!n)n=window.matchMedia("(orientation: landscape)").matches?"landscape":"portrait";const s=n.match(/landscape/)?r:i;if(gt.Mobile>=s)return ye.Mobile;else if(s>gt.Mobile&>.Tablet>=s)return ye.Tablet;return e?ye.Tablet:ye.Desktop}isDesktopDevice(){return this.getDeviceType()===ye.Desktop}getDeviceType(){const{userAgentData:e}=window.navigator;if(e){const{mobile:t}=e;if(t)return this.detectDeviceTypeByScreenWidth(true);else return ye.Desktop}return this.detectDeviceTypeByScreenWidth()}getBrowserLanguage(){const{language:e}=window.navigator;if(e.match(/\w{2}-\w{2}/))return e.split("-")[0].toLowerCase();else return e.toLowerCase()}getUserOs(){const{userAgentData:e}=window.navigator;if(e)return e.platform.toLowerCase();else return this.getOsFromUserAgent()}getOsFromUserAgent(){let e="unknown";const{userAgent:t}=navigator,i=t.toLowerCase();if(i.includes("win"))e="windows";if(i.includes("mac"))e="macos";if(i.includes("x11"))e="unix";if(i.includes("linux"))e="Linux";if(i.includes("android"))e="android";if(/iphone|ipad|ipod/.test(i))e="ios";return e}}const ht=new vt(pt),wt=new class{encodeEmail(e){return btoa(e)}decode(e){return atob(e)}isEncodedString(e){try{return atob(e),true}catch{return false}}validateEmail(e){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(e)}};class mt extends Error{constructor(e){super(e)}static create(...[e,t]){switch(e){case"email":return new mt(`Provided string ${t} is not valid email address`);default:void V.error(`Unsupported value: ${e}`)}}}class ft{constructor({e}={}){if(e)this.e=wt.encodeEmail(e)}static createFromContextData(e){try{if(wt.isEncodedString(e.e))e.e=wt.decode(e.e);return ft.validate(e),new ft(e)}catch(t){if(t instanceof mt)return V.error(t),ft.createBlank();throw t}}static createBlank(){return new ft}static validate(e){if("e"in e&&!wt.validateEmail(e.e))throw mt.create("email",e.e)}toJSON(){return{...this}}}class yt{constructor(e){I(this,a,void 0),this.eventType=e,E(this,a,null),this.eventId=null,this.aid=ge.getUserAid(),this.grid=ge.getClientLatestGrid(),this.time=lt.getCurrentVisitOnPageTime(),this.context=ft.createBlank(),this.uuid=k(ot.visitorUuid),this.url=window.location.href,this.occurredOn=new Date,this.tags=[]}get externalUid(){return b(this,a)}toJSON(){return{eventId:this.eventId,aid:this.aid,grid:this.aid,uuid:this.uuid,externalUid:this.externalUid,context:this.context.toJSON(),time:this.time,url:this.url,tags:this.tags,eventType:this.eventType,occurredOn:this.occurredOn.toUTCString()}}toString({normalized:e}={}){if(e)return JSON.stringify(this.normalizeForExternalStorage());else return JSON.stringify(this.toJSON())}normalize(){const{eventId:e,...t}=this.toJSON();return t}getBaseNormalizedEvent(){return{version:ut.One,user_uuid:ge.getUserUuid(),time:this.time,tags:this.tags,occurred_on:this.occurredOn.toISOString(),url:this.url,app:{lang:ht.getBrowserLanguage(),device:ht.getDeviceType(),os:ht.getUserOs()},channel:dt.Web,visitor:{uuid:this.uuid,external_id:this.externalUid,xsid:ge.visitorXsid}}}}a=new WeakMap;class St extends yt{constructor(e,t,i=ft.createBlank()){super($.Popup),this.popupEvent=e,this.popupId=t,this.context=i}toJSON(){return{...super.toJSON(),popupId:this.popupId,popupEvent:this.popupEvent}}normalizeForExternalStorage(){return{...this.getBaseNormalizedEvent(),event:{version:"1.0",name:$.Popup}}}}class bt extends yt{toJSON(){return{...super.toJSON(),data:this.data}}normalizeForExternalStorage(){return{...this.getBaseNormalizedEvent(),event:{version:this.eventVersion,name:this.eventType,data:this.data}}}}class It extends yt{constructor(e){super($.ShopifyAbandonedCart),this.data=e}toJSON(){return{...super.toJSON(),data:this.data}}normalizeForExternalStorage(){return{...this.getBaseNormalizedEvent(),event:{version:"1.0",name:$.ShopifyAbandonedCart,data:this.data}}}}const Et=class e{constructor(e){I(this,c,void 0),E(this,c,e)}static create(t){return new e(t)}validate(e){return Object.entries(b(this,c)).reduce(((t,[i,r])=>{if(false===t)return t;if(null==e[i]&&r._isOptional)return t;else return r.call(e,e[i])}),true)}stringifySchemaShape(){var t;return C(t=e,u,d).call(t,b(this,c))}trim(e,t=b(this,c)){var i;const r={};for(const[n,s]of Object.entries(e))if("object"==typeof s&&null!==s){if(n in t){const e=null==(i=t[n])?void 0:i.valueShape;if(Array.isArray(s))if(e)r[n]=s.map((t=>this.trim(t,e)));else r[n]=s;else r[n]=this.trim(s,e)}}else if(n in t)r[n]=s;return r}static string(){return Dt((e=>"string"==typeof e),(()=>"string"))}static number(){return Dt((e=>"number"==typeof e),(()=>"number"))}static boolean(){return Dt((e=>"boolean"==typeof e),(()=>"boolean"))}static dateString(){return Dt((e=>{if("string"!=typeof e)return false;else return!Number.isNaN(new Date(e).getTime())}),(()=>"date string"))}static object(t){return Dt((i=>{if(!t||"object"!=typeof t)return false;else return e.create(t).validate(i)}),(()=>C(this,u,d).call(this,t)),t)}static array(t){return Dt((i=>{if(!Array.isArray(i))return false;if("function"==typeof t)return i.every((e=>t(e)));const r=e.create(t);return i.every((e=>r.validate(e)))}),(()=>`[${C(this,u,d).call(this,t)}]`),"function"==typeof t?void 0:t)}};c=new WeakMap,u=new WeakSet,d=e=>{const t={};if("function"==typeof e)return e.getValueType();else for(const[i,r]of Object.entries(e))t[i]=r.getValueType();try{return JSON.stringify(t).replaceAll('\\"','"')}catch{return"Failed to parse validation shape"}},I(Et,u);let Ct=Et;function Dt(e,t,i){if(e.optional=()=>(e._isOptional=true,e),e.getValueType=t,i)e.valueShape=i;return e}const Pt={id:Ct.string(),sku:Ct.string().optional(),name:Ct.string().optional(),vendor:Ct.string().optional(),price:Ct.string().optional(),currency:Ct.string().optional()},Tt=Ct.array({id:Ct.string(),name:Ct.string().optional()}).optional(),Vt={id:Ct.string()},kt={shop:Ct.object({...Vt}).optional(),product:Ct.object({...Pt}),categories:Tt},Ut={product:Ct.object({...Pt}),categories:Tt,quantity:Ct.number()},_t=Ct.create({...kt}),xt=Ct.create({shop:Ct.object({...Vt}).optional(),id:Ct.string(),name:Ct.string().optional()}),At=Ct.create({...kt}),Lt=Ct.create({...kt}),Ot=Ct.create({...kt}),Nt=Ct.create({orderId:Ct.string(),cartId:Ct.string().optional(),price:Ct.number(),currency:Ct.string(),products:Ct.array(Ut)}),Bt=Ct.create({price:Ct.number(),cartId:Ct.string(),cartUrl:Ct.string(),currency:Ct.string(),products:Ct.array(Ut)});class Ft extends Error{constructor(e){super(`Data doesn't match required schema: ${e}`)}}class Rt extends yt{constructor(e=ft.createBlank()){super($.PageVisit),this.context=e}normalizeForExternalStorage(){return{...this.getBaseNormalizedEvent(),event:{version:"1.0",name:this.eventType}}}}const Wt={[$.ViewItem]:_t,[$.ViewCategory]:xt,[$.WishlistItem]:At,[$.LikeItem]:Lt,[$.UnlikeItem]:Ot,[$.OrderPlaced]:Nt,[$.Cart]:Bt},$t={[$.ViewItem]:class extends bt{constructor(e,t){super($.ViewItem),this.data=e,this.context=t,this.eventVersion="1.0"}normalizeForExternalStorage(){const e=super.normalizeForExternalStorage();return e.event.data.product.price=parseFloat(e.event.data.product.price),e.time=lt.getCurrentVisitOnPageTime(),e}},[$.ViewCategory]:class extends bt{constructor(e,t){super($.ViewCategory),this.data=e,this.context=t,this.eventVersion="1.0"}normalizeForExternalStorage(){const e=super.normalizeForExternalStorage();return e.time=lt.getCurrentVisitOnPageTime(),e}},[$.WishlistItem]:class extends bt{constructor(e,t){super($.WishlistItem),this.data=e,this.context=t,this.eventVersion="1.0"}},[$.LikeItem]:class extends bt{constructor(e,t){super($.LikeItem),this.data=e,this.context=t,this.eventVersion="1.0"}normalizeForExternalStorage(){const e=super.normalizeForExternalStorage();return e.event.data.product.price=parseFloat(e.event.data.product.price),e}},[$.UnlikeItem]:class extends bt{constructor(e,t){super($.UnlikeItem),this.data=e,this.context=t,this.eventVersion="1.0"}normalizeForExternalStorage(){const e=super.normalizeForExternalStorage();return e.event.data.product.price=parseFloat(e.event.data.product.price),e}},[$.OrderPlaced]:class extends bt{constructor(e,t){super($.OrderPlaced),this.data=e,this.context=t,this.eventVersion="1.0"}},[$.Cart]:class extends bt{constructor(e,t){super($.Cart),this.data=e,this.context=t,this.eventVersion="1.0"}}},jt=class e{static getPageVisitEvent(){return new Rt}static getPopupEvent({popupId:e,popupEventName:t}){return new St(t,e)}static getPopupSubmitEvent(e){return new St(ct.Submit,e)}static getPopupShowEvent(e){return new St(ct.Show,e)}static getPopupCloseEvent(e){return new St(ct.Close,e)}static getViewItemEvent(t,i){var r;return C(r=e,l,g).call(r,$.ViewItem,t,i)}static getWishlistItemEvent(t,i){var r;return C(r=e,l,g).call(r,$.WishlistItem,t,i)}static getLikeItemEvent(t,i){var r;return C(r=e,l,g).call(r,$.LikeItem,t,i)}static getUnlikeItemEvent(t,i){var r;return C(r=e,l,g).call(r,$.UnlikeItem,t,i)}static getViewCategoryEvent(t,i){var r;return C(r=e,l,g).call(r,$.ViewCategory,t,i)}static getOrderPlacedEvent(t,i){var r;return C(r=e,l,g).call(r,$.OrderPlaced,t,i)}static getCartUpdateEvent(t,i){var r;return C(r=e,l,g).call(r,$.Cart,t,i)}static getShopifyIntegrationAbandonedCartEvent(e){try{return(e=>{if("object"!=typeof e||null===e)throw new K("Invalid data parameter type");else{const t=Object.entries(X),i=Object.keys(e);if(!Y.every((e=>i.includes(e))))throw new K("Lack of required parameters");if(!t.every((([t,i])=>!e[t]||typeof e[t]===i)))throw new K("Properties have invalid type")}return true})(e),new It((t=e,i=Object.keys(X),Object.entries(t).reduce(((e,[t,r])=>{if(i.includes(t))e[t]=r;return e}),{})))}catch(r){return V.error(r),null}var t,i}};l=new WeakSet,g=(e,t,i)=>{const r=Wt[e],n=$t[e];if(!r||!n)throw new Error("Event type not supported in event factory");if(!r.validate(t))throw new Ft(r.stringifySchemaShape());return new n(r.trim(t),i)},I(jt,l);let Mt=jt;const zt=Symbol("StorageService");class Jt{constructor(e){if(new.target===Jt&&e!==zt)throw new Error(`Invalid ${new.target.name} constructor`)}async isNewVisitor(){return!(await this.getLastActivityDate())}getLastActivityDate(){return this.getLastActivityDateFromBrowserStorage()}getLastActivityDateFromBrowserStorage(){var e;const t=k(ot.visitorUuid),i=localStorage.getItem("gaLocalStorageVisitKey");let r;try{r=JSON.parse(i)}catch{throw new st}if(null==r?void 0:r[t])return Promise.resolve(new Date(null==(e=r[t])?void 0:e.lastActivity));else return null}saveUserActivity(){ge.eventBus.publish(L.SaveEvent,{sendToBackend:true,saveToLocal:false},ft.createBlank(),$.PageVisit,null),this.saveUserActivityToBrowserStorage()}saveUserActivityToBrowserStorage(){const e={[k(ot.visitorUuid)]:{lastActivity:Mt.getPageVisitEvent().occurredOn.toUTCString()}};try{window.localStorage.setItem("gaLocalStorageVisitKey",JSON.stringify(e))}catch{throw new st}}}const qt=new Jt(zt),Gt=Symbol("DebugStorageService");class Ht extends Jt{constructor(e){if(super(),new.target===Ht&&e!==Gt)throw new Error(`Invalid ${new.target.name} constructor`)}getLastActivityDate(){var e;const t=q(M.BrowserStorageLastActivityDate);if(isNaN(null==(e=null==t?void 0:t.getTime)?void 0:e.call(t)))return super.getLastActivityDate();else return Promise.resolve(t)}setLastActivityDate(e){const t=new Date(e);if(isNaN(t.getTime()))return V.error("Incorrect dateString for last activity date. Try again with isoString."),null;J(M.BrowserStorageLastActivityDate,t,t.toISOString())}isNewVisitor(){const e=q(M.NewVisitor);if(void 0===e)return super.isNewVisitor();else return Promise.resolve(e)}setIsNewVisitor(e){J(M.NewVisitor,e,String(e))}}const Kt=new Ht(Gt);function Xt(){return G(qt,Kt)}var Yt=(e=>(e["Always"]="always",e["OnceEveryDays"]="xDays",e["Session"]="everySession",e))(Yt||{});const Zt=1e3*60*60*24,Qt=Symbol("SessionService");class ei{constructor(e){if(new.target===ei&&e!==Qt)throw new Error(`Invalid ${new.target.name} constructor`)}hasUserVisitedPage(){return this.getSessionVisitData().count>1}saveUserVisit(){const e=this.getSessionVisitData()||{count:0};sessionStorage.setItem("gaUserPageSessionVisit",JSON.stringify({...e,count:e.count+1}))}getSessionVisitData(){return JSON.parse(sessionStorage.getItem("gaUserPageSessionVisit"))}}const ti=new ei(Qt),ii=Symbol("DebugSessionService");class ri extends ei{constructor(e){if(super(),new.target===ri&&e!==ii)throw new Error(`Invalid ${new.target.name} constructor`)}hasUserVisitedPage(){const e=q(M.HasUserVisitPage);if(void 0===e)return super.hasUserVisitedPage();else return e}setHasUserVisitedPage(e){J(M.HasUserVisitPage,e)}}const ni=new ri(ii);function si(){return G(ti,ni)}const oi=Symbol("VisitService");class ai{constructor(e){if(new.target===ai&&e!==oi)throw new Error(`Invalid ${new.target.name} constructor`)}async validateFrequencyProperty(e,t=0){if(e===Yt.Session)return!si().hasUserVisitedPage();else if(e===Yt.OnceEveryDays){const e=await Xt().getLastActivityDate();if(e)return((e,t)=>{const i=new Date(e+t*Zt),r=new Date(i.getFullYear(),i.getMonth(),i.getDate(),0,0,0);return Date.now()>=Date.parse(r.toString())})(e.getTime(),t)}return true}async validateVisitorsProperty(e){const t=await Xt().isNewVisitor();switch(e){case Se.New:return t;case Se.Returning:return!t;default:return true}}validateUrlPath(e="*"){const t=window.location.pathname;return this.validatePath(e,t)}validatePath(e,t){return me(t,e)}}const ci=new ai(oi),ui=Symbol("DebugVisitService");class di extends ai{constructor(e){if(super(),new.target===di&&e!==ui)throw new Error(`Invalid ${new.target.name} constructor`)}validateUrlPath(e="*"){const t=q(M.VisitUrlPath);if(void 0===t)return super.validateUrlPath(e);else return super.validatePath(e,t)}setVisitPathUrl(e){if("string"!=typeof e)return V.error("Invalid url path type. Try again with string variable"),null;J(M.VisitUrlPath,e)}}const li=new di(ui),gi=Symbol("DebugDeviceService");class pi extends vt{constructor(e){if(super(),new.target===pi&&e!==gi)throw new Error(`Invalid ${new.target.name} constructor`)}getDeviceType(){const e=q(M.DeviceType);if(!e)return super.getDeviceType();if(!Object.values(ye).includes(e))return V.error("Incorrect debug device type. Check if device is correct. Instead of that we will use normal values"),super.getDeviceType();else return e}setDeviceType(e){J(M.DeviceType,e)}}const vi=new pi(gi),hi=Symbol("LocationService");class wi{constructor(e){if(new.target===wi&&e!==hi)throw new Error(`Invalid ${new.target.name} constructor`)}getVisitorCountryCode(){const{domain:e}=window.__grIntegrationConfig.cData;return fetch(`${e}web-user-data/country`).then((e=>e.text()))}}const mi=new wi(hi),fi=Symbol("DebugLocationService");class yi extends wi{constructor(e){if(super(),new.target===yi&&e!==fi)throw new Error(`Invalid ${new.target.name} constructor`)}getVisitorCountryCode(){const e=q(M.Location);if(!e)return super.getVisitorCountryCode();else return Promise.resolve(e)}setVisitorCountryCode(e){if("string"!=typeof e)return V.error("Incorrect debug country code value"),null;J(M.Location,e)}}const Si=new yi(fi);class bi{static sendJSON(e,t,i=true){const r=i?JSON.stringify({...JSON.parse(t),[ee.UserAid]:ge.getUserAid()}):t;navigator.sendBeacon(e,new Blob([r],{type:"application/json"}))}}const Ii=[$.OrderPlaced,$.Cart,$.LikeItem,$.UnlikeItem,$.WishlistItem,$.ViewItem,$.ViewCategory],Ei=[$.Cart,$.LikeItem,$.UnlikeItem,$.OrderPlaced,$.ViewCategory,$.ViewItem];p=new WeakSet,v=()=>new URL(`u/${ge.getUserUuid()}/e/${dt.Web}/handle/`,ge.userEventsStorageApplicationUrl).href;const Ci=new class{constructor(){I(this,p)}async addPopupEventToStorage(e){throw new Error("Not implemented")}async getPopupActivityData(e){throw new Error("Not implemented")}async saveEventsToStorage(e){if(ge.userEventsStorageApplicationUrl&&ge.getUserUuid()){const t=e.filter((e=>Ii.includes(e.event.name)));if(t.length>0)bi.sendJSON(C(this,p,v).call(this),JSON.stringify(t),false)}else V.error("Attempt to send web events to search was made without search application endpoint or uuuid!")}async sendEventsToMetricsInc(e){const t=e.filter((e=>Ei.includes(e.event.name)));if(t.length>0){const e=JSON.stringify({events:t.map((e=>({eventType:e.event.name}))),url:window.location.origin}),i=new URL("/a/ue",ge.getUserAnalyticsDomain()).href;bi.sendJSON(i,e)}}};var Di=(e=>(e["Events"]="gr_webconnect",e["VisitorJourneys"]="gr_visitor_journeys",e["ServiceWorkerCallbacks"]="gr_sw_callbacks",e))(Di||{});const Pi={gr_webconnect:1,gr_visitor_journeys:2,gr_sw_callbacks:1};var Ti=(e=>(e["UserActivityEvents"]="user_activity_events",e))(Ti||{}),Vi=(e=>(e["EventType"]="eventType",e["VisitorUuid"]="visitorUuid",e["EventTypeWithVisitor"]="eventType, visitorUuid",e))(Vi||{});let ki,Ui;const _i=new WeakMap,xi=new WeakMap,Ai=new WeakMap,Li=new WeakMap,Oi=new WeakMap;let Ni={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return xi.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Ai.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return Fi(e[t])},set:(e,t,i)=>(e[t]=i,true),has(e,t){if(e instanceof IDBTransaction&&("done"===t||"store"===t))return true;else return t in e}};function Bi(e){if("function"==typeof e)return function(e){if(e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype))return function(t,...i){const r=e.call(Ri(this),t,...i);return Ai.set(r,t.sort?t.sort():[t]),Fi(r)};if((Ui||(Ui=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e))return function(...t){return e.apply(Ri(this),t),Fi(_i.get(this))};else return function(...t){return Fi(e.apply(Ri(this),t))}}(e);if(e instanceof IDBTransaction)!(e=>{if(xi.has(e))return;const t=new Promise(((t,i)=>{const r=()=>{e.removeEventListener("complete",n),e.removeEventListener("error",s),e.removeEventListener("abort",s)},n=()=>{t(),r()},s=()=>{i(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",n),e.addEventListener("error",s),e.addEventListener("abort",s)}));xi.set(e,t)})(e);if(t=e,(ki||(ki=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some((e=>t instanceof e)))return new Proxy(e,Ni);else return e;var t}function Fi(e){if(e instanceof IDBRequest)return(e=>{const t=new Promise(((t,i)=>{const r=()=>{e.removeEventListener("success",n),e.removeEventListener("error",s)},n=()=>{t(Fi(e.result)),r()},s=()=>{i(e.error),r()};e.addEventListener("success",n),e.addEventListener("error",s)}));return t.then((t=>{if(t instanceof IDBCursor)_i.set(t,e)})).catch((()=>{})),Oi.set(t,e),t})(e);if(Li.has(e))return Li.get(e);const t=Bi(e);if(t!==e)Li.set(e,t),Oi.set(t,e);return t}const Ri=e=>Oi.get(e),Wi=["get","getKey","getAll","getAllKeys","count"],$i=["put","add","delete","clear"],ji=new Map;function Mi(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(ji.get(t))return ji.get(t);const i=t.replace(/FromIndex$/,""),r=t!==i,n=$i.includes(i);if(!(i in(r?IDBIndex:IDBObjectStore).prototype)||!(n||Wi.includes(i)))return;const s=async function(e,...t){const s=this.transaction(e,n?"readwrite":"readonly");let o=s.store;if(r)o=o.index(t.shift());return(await Promise.all([o[i](...t),n&&s.done]))[0]};return ji.set(t,s),s}var zi;zi=Ni,void(Ni={...zi,get(e,t,i){return Mi(e,t)||zi.get(e,t,i)},has(e,t){return!!Mi(e,t)||zi.has(e,t)}});const Ji=new class{openEventsDatabaseConnection(e){return this.openConnection(Di.Events,Pi[Di.Events],e)}openAutomationJourneysDatabaseConnection(e){return this.openConnection(Di.VisitorJourneys,Pi[Di.VisitorJourneys],e)}openServiceWorkerCallbacksDatabaseConnection(e){return this.openConnection(Di.ServiceWorkerCallbacks,Pi[Di.ServiceWorkerCallbacks],e)}async openConnection(e,t,i){const r=await((e,t,{blocked:i,upgrade:r,blocking:n,terminated:s}={})=>{const o=indexedDB.open(e,t),a=Fi(o);if(r)o.addEventListener("upgradeneeded",(e=>{r(Fi(o.result),e.oldVersion,e.newVersion,Fi(o.transaction),e)}));if(i)o.addEventListener("blocked",(e=>i(e.oldVersion,e.newVersion,e)));return a.then((e=>{if(s)e.addEventListener("close",(()=>s()));if(n)e.addEventListener("versionchange",(e=>n(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a})(e,t,{blocked(e,t,i){V.error(`Connection to old db version: ${t} not closed. Version ${e} not available`,i)},upgrade(e,t,r){V.log(`New db version ${r} detected, upgrading from ${t}`),i(t,r,e)},terminated(){V.log("Closing db connection")},blocking(e,t,i){V.log(`Current connection od db version ${e} is blocking connection to version ${t}.`,i),r.close()}});return r}};Ji.openServiceWorkerCallbacksDatabaseConnection.bind(Ji),Ji.openAutomationJourneysDatabaseConnection.bind(Ji);const qi=Symbol("BrowserEventsStorageService");h=new WeakSet,w=(e,t,i)=>{if(0===e&&1===t)!(e=>{if(!e.objectStoreNames.contains(Ti.UserActivityEvents))try{const t=e.createObjectStore(Ti.UserActivityEvents,{keyPath:"id",autoIncrement:true});t.createIndex(Vi.EventType,"eventType",{unique:false}),t.createIndex(Vi.VisitorUuid,"uuid",{unique:false}),t.createIndex(Vi.EventTypeWithVisitor,["eventType","uuid"])}catch(t){V.error("Error while initializing/upgrading database",t)}})(i)};let Gi=class e{constructor(t){if(I(this,h),new.target===e&&t!==qi)throw new Error(`Invalid ${new.target.name} constructor`)}async saveEvent(e){const t=e instanceof yt?e.normalize():e;try{const e=(await Ji.openEventsDatabaseConnection(C(this,h,w))).transaction(Ti.UserActivityEvents,"readwrite"),i=e.objectStore(Ti.UserActivityEvents),r=await i.add(t);return await e.done,r}catch(i){V.error("Error while saving event to database",i)}}async getEvents(e){const t=k(ot.visitorUuid);try{const i=(await Ji.openEventsDatabaseConnection(C(this,h,w))).transaction(Ti.UserActivityEvents,"readwrite"),r=i.objectStore(Ti.UserActivityEvents).index(Vi.EventTypeWithVisitor),n=await r.getAll([e,t]);return await i.done,n}catch(i){V.error("Error while reading from database",i)}}async updateEvent(e,t){const i=(await Ji.openEventsDatabaseConnection(C(this,h,w))).transaction(Ti.UserActivityEvents,"readwrite").objectStore(Ti.UserActivityEvents),r=await i.get(e);if(r){const e=A(r,t);await i.put(e)}}async getPopupECommerceEvents(e){const t=k(ot.visitorUuid),i=(await Ji.openEventsDatabaseConnection(C(this,h,w))).transaction(Ti.UserActivityEvents,"readwrite").store.index(Vi.VisitorUuid),r=[];let n=await i.openCursor(IDBKeyRange.only(t));for(;n;){const{value:t}=n;if(e(t))r.push(t);n=await n.continue()}return r}};const Hi=new Gi(qi),Ki=Symbol("DebugBrowserEventsStorageService");class Xi extends Gi{constructor(e){if(super(),new.target===Xi&&e!==Ki)throw new Error(`Invalid ${new.target.name} constructor`)}async getPopupECommerceEvents(e){const t=q(M.Events)||[];if(!t.length)return super.getPopupECommerceEvents(e);else return t.filter(e)}async getEvents(e){const t=k(ot.visitorUuid),i=q(M.Events)||[];if(!i.length)return super.getEvents(e);else return i.filter((({eventType:i,uuid:r})=>i===e&&r===t))}async saveEvent(e){const t=e instanceof yt?e.toJSON():e,i=[...q(M.Events)||[],t];try{const e=JSON.stringify(i);return J(M.Events,i,e),Math.random()}catch(r){V.error(`Can't parse new debug events. Try again.`)}}}const Yi=new Xi(Ki);function Zi(){return G(Hi,Yi)}const Qi={[$.PageVisit]:Mt.getPageVisitEvent,[$.ViewItem]:Mt.getViewItemEvent,[$.WishlistItem]:Mt.getWishlistItemEvent,[$.LikeItem]:Mt.getLikeItemEvent,[$.UnlikeItem]:Mt.getUnlikeItemEvent,[$.ViewCategory]:Mt.getViewCategoryEvent,[$.OrderPlaced]:Mt.getOrderPlacedEvent,[$.Cart]:Mt.getCartUpdateEvent,[$.Popup]:Mt.getPopupEvent},er=2e3;m=new WeakMap,f=new WeakSet,y=function(){b(this,m).forEach((([e,t])=>{if(e===$.ViewCategory||e===$.ViewItem)Hi.updateEvent(t,{time:lt.getCurrentVisitOnPageTime()}).catch((e=>{V.error("Failed to update event data",e)}))}))};const tr=new class{constructor(){I(this,f),I(this,m,void 0),this.eventToSend=[],E(this,m,[])}async push(e,t,...[i,r]){if(void 0===e.saveToLocal||e.saveToLocal){const n=this.getEvent(i,r,t);if(n){const t=await Zi().saveEvent(n);if(n.eventId=String(t),b(this,m).push([i,t]),ae.saveEvent(n),!e.preventRenotify)ge.eventBus.publish(O.UserEventSaved,n)}else return V.warn(`Invalid event params`,i,r),void 0}if(e.sendToBackend)this.eventToSend.push([i,r,lt.getCurrentVisitOnPageTime(),t])}flush(){if(this.eventToSend.length){const e=this.eventToSend.map((([e,t,i,r])=>{const n=this.getEvent(e,t,r);if(n)return n.time=i,n.normalizeForExternalStorage();else return null})).filter(Boolean);if(e.length){if(ge.canUseBackendStorageForEvents)Ci.saveEventsToStorage(e);Ci.sendEventsToMetricsInc(e)}}this.eventToSend=[]}getEvent(e,t,i){const r=Qi[e];try{return"function"==typeof r?r(t,ft.createFromContextData(i)):null}catch(n){V.error("Failed to create user event",n)}}startUpdatingStoredEvents(){setInterval((()=>{C(this,f,y).call(this)}),er)}},ir=new class{isScriptDelayed(e){return Object.keys(ge.delayedScripts).includes(e)}delay(e){if(!this.isScriptDelayed(e))ge.delayedScripts={...ge.delayedScripts,[e]:void 0}}storeDelayedScriptParams(e,t){if(this.isScriptDelayed(e))ge.delayedScripts={...ge.delayedScripts,[e]:t}}initScript(e){var t;const i=ge.delayedScripts[e];if(i){ge.delayedScripts=Object.fromEntries(Object.entries(ge.delayedScripts).filter((([t])=>t!==e)));const r=ue[e];null==(t=null==window?void 0:window[r])?void 0:t.init(...i)}}},rr=new class{setCookie({expiresIn:e,domain:t="",value:i,name:r}){const n=this.getExpirationTimeString(e);document.cookie=`${r}=${i}; expires=${n}; path=/; ${t?`domain=${t}`:""}`}getExpirationTimeString(e){if(e instanceof Date)return e.toUTCString();const t=new Date;return t.setTime(t.getTime()+e),t.toUTCString()}getCookie(e){const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]+)`));if(t)return t[2]}removeUuidCookieSessionInfo(){window.sessionStorage.removeItem(F.UuidHasBeenSet)}},nr=16,sr="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.11.0/sha256.min.js",or=new class{async sha256(e){try{const t=(new TextEncoder).encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map((e=>e.toString(nr).padStart(2,"0"))).join("")}catch(i){V.error("Failed to encrypt visitor e, using fallback lib",i);try{return await(t=sr,new Promise(((e,i)=>{const r=Object.assign(document.createElement("script"),{src:t});document.head.append(r),r.addEventListener("load",(()=>{e()}),{once:true}),r.addEventListener("error",(e=>{i(e)}),{once:true})}))),window.sha256(e)}catch(r){return V.error("Failed to encrypt visitor e with fallback lib",r),atob(e)}}var t}},ar=new class{async saveVisitorEmail(e){const t=await or.sha256(e);rr.setCookie({name:ot.VisitorEmail,value:t,expiresIn:at.OneYear})}async hasVisitorEmailBeenChanged(e){const t=await or.sha256(e),i=rr.getCookie(ot.VisitorEmail);if(!i)return false;else return t!==i}};class cr extends class{setDomain(e){if(!e||"auto"===e)this.cookieDomain=(()=>{const e=new Date,t=location.hostname.split(".").reverse(),i=[],r=`gaDomain-${D(6)}`,n=D(6);let s="";for(e.setTime(e.getTime()+60*1e3),i.push(t.shift());t.length>0;){if(s=i.reverse().join("."),document.cookie=`${r}=${n}; expires=${e.toUTCString()}; domain=.${s}; path=/`,k(r)===n)return s;i.push(t.shift())}return location.hostname})();else this.cookieDomain=e}setListToken(e){this.listToken=e}}{constructor(e,t,i,r){super(),this.cookieDomain="",this.listToken="",this.email="",this.uuid=document.cookie.replace(/(?:(?:^|.*;\s*)gaVisitorUuid\s*\=\s*([^;]*).*$)|^.*$/,"$1")||"",this.valuable=Number(document.cookie.replace(/(?:(?:^|.*;\s*)gaIsValuable\s*\=\s*([^;]*).*$)|^.*$/,"$1")||0),this.gr_x=_("gr_x")||"",this.gr_s=_("gr_s")||"",this.gr_m=_("gr_m")||"",this.tracking=new B,this.wasPageVisitEventSaved=false,this.onEventPush=(...[e,t,i,r])=>{tr.push(e,t,i,r)},this.onEventFlush=()=>{tr.flush()},this.onImportScript=async(e,...t)=>{if(Object.values(ce).includes(e)){const{webConnectScriptCdnUrl:i,webConnectCurrentScriptsVersion:r}=ge,n=new URL(`${e}.${r}.umd.js`,i);import(n.href).then((()=>{window[ue[e]].init(...t)}))}else V.error(`Invalid script name ${e}`)},this.onDomainSet=e=>{this.setDomain(e)},this.onListTokenSet=e=>{this.setListToken(e)},this.onSetUserId=async(e,t)=>{if("string"!=typeof e)throw new Error(`User email should be a string`);this.assureDomainIsSet(),this.assureUuidIsSet(),await this.setUserId(e,t)},this.onSetEvent=(e,t)=>{this.assureDomainIsSet(),this.assureUuidIsSet(),this.tracking.setUserId(this.serialize()),this.setEvent(e,t)},this.onSetCookie=(e,t)=>{U(e,t,this.cookieDomain)},this.onPush=()=>{this.push()},this.onSetCustomServiceWorkerPath=e=>{ge.setCustomSwPath(e)},this.createDefaultEventsAndSave=()=>{if("hidden"===document.visibilityState){if(!this.wasPageVisitEventSaved)Xt().saveUserActivity(),this.wasPageVisitEventSaved=true;ge.eventBus.publish(L.FlushEvents)}},this.xsid=i||"",this.tracking.setCustomVariable(1,"grid",t),this.tracking.setCustomVariable(2,"aid",r),this.tracking.setTrackerUrl(`${e}index.php?ver=3`),this.tracking.markAsEnabled(ge.isTrackingEnabled()),this.tracking.setUserId(this.serialize())}async initialize(){if(!this.xsid&&!this.valuable&&ge.isTrackingScriptServedFromCustomDomain())this.xsid=await ve.retrieveXsid();this.attachListeners(),tr.startUpdatingStoredEvents()}attachListeners(){const{eventBus:e}=ge;e.subscribe(L.SetDomain,this.onDomainSet),e.subscribe(L.SetListToken,this.onListTokenSet),e.subscribe(L.SetUserId,this.onSetUserId),e.subscribe(L.SetEvent,this.onSetEvent),e.subscribe(L.SetCookie,this.onSetCookie),e.subscribe(L.Push,this.onPush),e.subscribe(L.SetCustomServiceWorkerPath,this.onSetCustomServiceWorkerPath),e.subscribe(L.ImportScript,this.onImportScript),e.subscribe(L.SetVisitUrlPath,this.onSetVisitUrlPath),e.subscribe(L.SetLastActivityDate,this.onSetLastActivityDate),e.subscribe(L.SetIsNewVisitor,this.onSetIsNewVisitor),e.subscribe(L.SetHasUserVisitPage,this.onSetHasUserVisitPage),e.subscribe(L.SetUserDevice,this.onSetDevice),e.subscribe(L.SetUserLocation,this.onSetUserLocation),e.subscribe(L.SetRawEvent,this.onSetRawEvent),e.subscribe(L.SaveEvent,this.onEventPush),e.subscribe(L.FlushEvents,this.onEventFlush),e.subscribe(L.DelayScript,this.onScriptDelay),e.subscribe(L.InitScript,this.onScriptInit)}assureDomainIsSet(){if(!this.cookieDomain)this.onDomainSet("auto")}assureUuidIsSet(e=false){if(!this.uuid||e){const t=this.generateUuid(e);window.sessionStorage.setItem(F.UuidHasBeenSet,"true"),this.uuid=t}}setValuability(){if(this.gr_x&&this.gr_s)this.setIsValuable();if(this.email||this.xsid)this.setIsValuable()}assureEventsAreCreatedAndSaved(){document.addEventListener("visibilitychange",this.createDefaultEventsAndSave)}generateUuid(e=false){let t=k("gaVisitorUuid");if(!t||e)t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),U("gaVisitorUuid",t,this.cookieDomain);return t}async setUserId(e,t){if(e&&ge.isTrackingEnabled()){if(ge.visitorEmail=e,await ar.hasVisitorEmailBeenChanged(e))this.assureUuidIsSet(true);this.email=e,this.listToken=t||this.listToken,this.setIsValuable(),this.push(),await ar.saveVisitorEmail(e)}}setEvent(e,t){if(void 0===t)this.tracking.trackEvent("custom","fire",e);else this.tracking.trackEvent("custom","fire",e,JSON.stringify(t))}push(){this.tracking.setUserId(this.serialize()),this.tracking.trackPageView()}setIsValuable(){if(ge.isTrackingEnabled())this.valuable=1,U("gaIsValuable","1",this.cookieDomain)}serialize(){return JSON.stringify({uuid:this.uuid,email:this.email,xsid:this.xsid,list_token:this.listToken,gr_x:this.gr_x,gr_s:this.gr_s,gr_m:this.gr_m,valuable:this.valuable,domain:this.cookieDomain})}onSetVisitUrlPath(e){const t=G(ci,li);if(t instanceof di)t.setVisitPathUrl(e)}onSetLastActivityDate(e){const t=Xt();if(t instanceof Ht)t.setLastActivityDate(e)}onSetIsNewVisitor(e){const t=Xt();if(t instanceof Ht)t.setIsNewVisitor(e)}onSetHasUserVisitPage(e){const t=si();if(t instanceof ri)t.setHasUserVisitedPage(e)}onSetDevice(e){const t=G(ht,vi);if(t instanceof pi)t.setDeviceType(e)}onSetUserLocation(e){const t=G(mi,Si);if(t instanceof yi)t.setVisitorCountryCode(e)}onSetRawEvent(e){const t=Zi();if(t instanceof Xi)t.saveEvent(e)}onScriptDelay(e){ir.delay(e)}onScriptInit(e){ir.initScript(e)}}e.init=e=>{const t=JSON.parse(e),{grid:i,clientLatestGrid:r,aid:n,uuuid:s,xsid:o,isServedFromCustomDomain:a,scriptVersion:c,scriptDomain:u,useBackendSubscriberIdentification:d,useBackendStorage:l,trackingUrl:g,tracking:p,isDebugMode:v}=t,h=window["__GetResponseAnalyticsObject"]||"GrTracking";if((()=>{if([Array.from,"".endsWith,"".startsWith,[].entries].some((e=>!e.toString().includes("[native code]"))))V.warn("Modification of native JavaScript object/methods detected, WebConnect might not work correctly!")})(),ge.initialize({xsid:o,aid:n,grid:i,uuuid:s,clientLatestGrid:r,domain:g,useNOStorage:"true"===l,useBetterSubscriberIdentification:"true"===d,isServedFromCustomDomain:"true"===a,scriptsDomain:u,scriptsVersion:c,tracking:"true"===p,isDebugMode:"true"===v}),ge.scriptModuleManager.isScriptInitialized(ce.v2))return;ge.scriptModuleManager.setScriptInitialized(ce.v2);const w=new cr(g,i,o,n);function m(e,t){window[h](e,t)}w.initialize().then((()=>{var e;if(Array.isArray(null==(e=window[h])?void 0:e.q))window[h].q.forEach(((e,t)=>{if("push"!==e[0])ge.eventBus.publish(e[0],e[1],e[2]),delete window[h].q[t]}));window[h]=(e,t,i)=>{ge.eventBus.publish(e,t,i)},w.assureDomainIsSet(),w.assureUuidIsSet(),w.setValuability(),ge.eventBus.publish(L.Push),w.assureEventsAreCreatedAndSaved()})),window.gaSetUserId=e=>{m(L.SetUserId,e)},window.gaPush=()=>{m(L.Push)}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}((e="undefined"!=typeof globalThis?globalThis:e||self).GRV2={})}(this);