File: //wordpress/plugins/jetpack/latest/jetpack_vendor/automattic/woocommerce-analytics/build/591.js
"use strict";(self.webpackChunk_automattic_woocommerce_analytics=self.webpackChunk_automattic_woocommerce_analytics||[]).push([[591],{591:(e,i,t)=>{var n=t(37),s=t.n(n);const o="woocommerceanalytics_session",a=/^[a-z_][a-z0-9_]*$/,r=s()("wc-analytics:api-client");class d{eventQueue=[];debounceTimer=null;isInitialized=!1;init=()=>{this.isInitialized||(r("API client initialized"),window.addEventListener("beforeunload",this.flush),window.addEventListener("pagehide",this.flush),this.isInitialized=!0)};addEvent=(e,i={})=>{if(!this.isInitialized)return void r("API client not initialized, skipping event: %s",e);r('Recording event via API: "%s" with props %o',e,i);const t={event_name:e,properties:i};this.eventQueue.push(t),r("Event added to queue: %s (queue size: %d)",e,this.eventQueue.length),this.debouncedSend(),this.eventQueue.length>=10&&this.flush()};debouncedSend=()=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout(()=>{this.flush()},1e3)};sendEventsViaBeacon=e=>{if("undefined"==typeof navigator||!navigator.sendBeacon)return r("Beacon API not available"),!1;try{const i=JSON.stringify(e),t=new Blob([i],{type:"application/json"});return navigator.sendBeacon(window.wcAnalytics.trackEndpoint,t)}catch(e){return r("Beacon API failed: %o",e),!1}};flush=()=>{if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],window.wcAnalytics?.trackEndpoint?this.sendEventsViaBeacon(e)?r("Sent %d events via Beacon API",e.length):(r("Failed to send events via Beacon API, falling back to fetch with keepalive"),this.sendEvents(e)):r("Track endpoint not available")};sendEvents=async e=>{if(0!==e.length)try{r("Sending %d events to API",e.length);const i=await fetch(window.wcAnalytics.trackEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0,credentials:"same-origin"});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);const t=await i.json();r("API response received: %o",t)}catch(i){r("Failed to send events to API: %o",i),this.eventQueue.unshift(...e)}}}var c=t(771);function h(e){const i=`; ${document.cookie}`.split(`; ${e}=`);return 2===i.length&&i.pop()?.split(";").shift()||null}const l=s()("wc-analytics:analytics");class u{constructor(e,{eventQueue:i=[],commonProps:t={},features:n={},pages:s={}}){this.isInitialized=!1,this.sessionManager=e,this.apiClient=new d,this.eventQueue=i,this.commonProps=t,this.features=n,this.pages=s}init=()=>{if(!this.isInitialized){if(this.features.proxy&&this.apiClient.init(),this.features.sessionTracking){c.K.addConsentChangeListener(this.handleConsentChange),this.sessionManager.init();const{sessionId:e,landingPage:i,isEngaged:t,isNewSession:n}=this.sessionManager;this.features.proxy||(this.commonProps={...this.commonProps,session_id:e,landing_page:i,is_engaged:t}),n?this.maybeRecordSessionStartedEvent():this.maybeRecordEngagementEvent(),this.recordEvent("page_view")}this.maybeSetAnonId(),this.processEventQueue(),this.initListeners(),this.isInitialized=!0}};initListeners=()=>{this.pages.isAccountPage&&t.e(252).then(t.bind(t,252)).then(({initListeners:e})=>{e(this.recordEvent)})};processEventQueue=()=>{for(const e of this.eventQueue)this.recordEvent(e.eventName,e.props)};recordEvent=(e,i={})=>{if(!c.K.hasAnalyticsConsent())return void l("Skipping event recording due to lack of statistics consent: %s",e);if("string"!=typeof e||!a.test(e))return void l("Skipping event recording because event name is not valid");const t={...this.commonProps,...i};this.features.ch?t.ch=1:delete t.ch,this.features.proxy?(this.addClientProperties(t),this.apiClient.addEvent(e,t)):this.fireDirectPixel(e,t),this.isInitialized&&this.maybeRecordEngagementEvent()};fireDirectPixel=(e,i)=>{window._wca?(l('Recording event via _wca: "%s" with props %o',e,i),i._en=`woocommerceanalytics_${e}`,window._wca.push(i)):l("Skipping event recording because _wca is not defined")};addClientProperties=e=>{const i=new Date;e._ts=i.getTime(),e._tz=i.getTimezoneOffset()/60;const t=window.navigator,n=window.screen;e._lg=t.language,e._pf=navigator?.platform,e._ht=n.height,e._wd=n.width;const s=void 0!==window.pageXOffset?window.pageXOffset:(document.documentElement||document.body).scrollLeft,o=void 0!==window.pageYOffset?window.pageYOffset:(document.documentElement||document.body).scrollTop;e._sx=void 0!==s?s:0,e._sy=void 0!==o?o:0,void 0!==document.location&&(e._dl=document.location.toString()),void 0!==document.referrer&&(e._dr=document.referrer)};maybeRecordSessionStartedEvent=()=>{this.features.sessionTracking&&this.sessionManager.isNewSession&&this.sessionManager.sessionId&&this.recordEvent("session_started")};maybeRecordEngagementEvent=()=>{this.features.sessionTracking&&!this.sessionManager.isEngaged&&this.sessionManager.sessionId&&(this.sessionManager.setEngaged(),this.recordEvent("session_engagement"))};handleConsentChange=e=>{e?this.sessionManager.sessionId||this.sessionManager.init():this.sessionManager.clearSession()};maybeSetAnonId(){if(!h("tk_ai")){const e=function(){let e;if(window.crypto&&window.crypto.getRandomValues)e=new Uint8Array(18),window.crypto.getRandomValues(e);else for(let i=0;i<18;++i)e[i]=Math.floor(256*Math.random());return btoa(String.fromCharCode(...e))}(),i=new Date(Date.now()+31536e6).toUTCString();document.cookie=`tk_ai=${e}; path=/; secure; samesite=strict; expires=${i}`}}}class g{sessionId=null;landingPage=null;isEngaged=!1;isNewSession=!1;isInitialized=!1;init=()=>{this.isInitialized||(this.loadOrCreateSession(),this.isInitialized=!0)};loadOrCreateSession(){const e=this.getSessionCookie();e&&e.session_id?(this.sessionId=e.session_id,this.landingPage=e.landing_page||null,this.isEngaged=e.is_engaged||!1,this.isNewSession=!1):this.createNewSession()}createNewSession(){this.isNewSession=!0;const e={session_id:this.generateRandomUuid(),landing_page:JSON.stringify(window.wcAnalytics?.breadcrumbs||[]),expires:this.getSessionExpirationTime()};this.setSessionCookie(e)&&(this.sessionId=e.session_id,this.landingPage=e.landing_page,this.isEngaged=!1)}getSessionCookie(){const e=h(o);if(!e)return null;try{return JSON.parse(decodeURIComponent(e))}catch(e){return console.error("Error parsing session cookie",e),null}}setSessionCookie(e){const i=encodeURIComponent(JSON.stringify(e)),t=e.expires||this.getSessionExpirationTime();return document.cookie=`${o}=${i}; expires=${t}; path=/; secure; samesite=strict`,h(o)===i}getSessionExpirationTime(){const e=Date.now()+18e5,i=new Date;i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0);const t=Math.min(e,i.getTime());return new Date(t).toUTCString()}generateRandomUuid(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const i=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return[i.slice(0,8),i.slice(8,12),i.slice(12,16),i.slice(16,20),i.slice(20,32)].join("-")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const i=Math.floor(16*Math.random());return("x"===e?i:i%4+8).toString(16)})}setEngaged(){if(this.isEngaged)return;const e=this.getSessionCookie();e&&e.session_id&&(e.is_engaged=!0,this.setSessionCookie(e)),this.isEngaged=!0}clearSession(){document.cookie=`${o}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; secure; samesite=strict`,this.sessionId=null,this.landingPage=null,this.isEngaged=!1,this.isNewSession=!1,this.isInitialized=!1}}!function(){const e=new g;new u(e,{eventQueue:window.wcAnalytics.eventQueue,commonProps:window.wcAnalytics.commonProps,features:window.wcAnalytics.features,pages:window.wcAnalytics.pages}).init()}()}}]);