1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="a0ae97ed-020f-6bf2-f060-a469efcee1d1")}catch(e){}}(); 2(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,524045,t=>{"use strict";var e,i,r;(r=e||(e={})).PAGE_VIEW="page_view",r.PAGE_CLICK="page_click",r.BUTTON_CLICK="button_click",r.VIDEO_PLAY="video_play",r.FORM_SUBMIT="form_submit",r.EMAIL_VERIFICATION="email_verification",r.LOGIN="login",r.SIGNUP="signup",r.PRODUCT_VIEW="product_view",r.ADD_TO_CART="add_to_cart",r.PURCHASE="purchase",r.AUDIT_APPROVED="audit_approved",r.CUSTOM="custom",(i||(i={})).USD="USD";let n="https://attribution.getu.ai/attribution/api",a=[e.PURCHASE,e.LOGIN,e.SIGNUP,e.FORM_SUBMIT,e.EMAIL_VERIFICATION,e.AUDIT_APPROVED],o={email:["email","e-mail","mail","user_email","email_address"],name:["name","full_name","fullname","username","display_name"],first_name:["first_name","firstname","fname","given_name"],last_name:["last_name","lastname","lname","surname","family_name"],phone:["phone","telephone","mobile","phone_number","tel"],company_name:["company","company_name","organization","org","business"],title:["title","job_title","position","role","job"]};function s(){return Math.floor(Date.now()/1e3)}let l=["adgroup_id","ad_group_id","adgroupid","adset_id","tt_adgroup_id","adgroup"],u=["ad_id","adid","creative_id","creative","tt_ad_id"],c=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"],d=/^\d{7,15}$/;function g(t,e){let i=e.toLowerCase();for(let e of Object.keys(t))if(e.toLowerCase()===i){for(let i of t[e])if(i&&""!==i.trim())return i.trim()}}function h(t){let e=function(t){let e={};try{let i=new URL(t),r=new Set;i.searchParams.forEach((t,e)=>{r.add(e)}),r.forEach(t=>{let r=i.searchParams.getAll(t);e[t]=r.filter(t=>null!=t&&""!==t)})}catch(t){}return e}(t),i={};for(let t of l){let r=g(e,t);if(void 0!==r){/^\{.+\}$/.test(r)?(i.adgroup_id=r,i.adgroup_id_source="valuetrack"):(i.adgroup_id=r,i.adgroup_id_source="explicit");break}}if(!i.adgroup_id)for(let t of g(e,"utm_term")?e[Object.keys(e).find(t=>"utm_term"===t.toLowerCase())]:[]){let e=(t||"").trim();if(d.test(e)){i.adgroup_id=e,i.adgroup_id_source="utm_term_numeric";break}}for(let t of u){let r=g(e,t);if(void 0!==r){/^\{.+\}$/.test(r)?(i.ad_id=r,i.ad_id_source="valuetrack"):(i.ad_id=r,i.ad_id_source="explicit");break}}if(!i.ad_id)for(let t of g(e,"utm_content")?e[Object.keys(e).find(t=>"utm_content"===t.toLowerCase())]:[]){let e=(t||"").trim();if(d.test(e)){i.ad_id=e,i.ad_id_source="utm_content_numeric";break}}for(let t of c){let r=g(e,t);if(r&&""!==r.trim()){i.click_id=r.trim(),i.click_id_source=t;break}}return i}function m(){try{let t="__localStorage_test__";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch{return!1}}async function _(t,e=3,i=1e3){let r;for(let n=0;n<=e;n++)try{return await t()}catch(a){if(r=a,n===e)throw r;let t=i*Math.pow(2,n);await new Promise(e=>setTimeout(e,t))}throw r}class p{constructor(t=!0){this.enabled=t}debug(t,...e){this.enabled&&console.debug&&console.debug(`[GetuAI Debug] ${t}`,...e)}info(t,...e){this.enabled&&console.info&&console.info(`[GetuAI Info] ${t}`,...e)}warn(t,...e){this.enabled&&console.warn&&console.warn(`[GetuAI Warn] ${t}`,...e)}error(t,...e){this.enabled&&console.error&&console.error(`[GetuAI Error] ${t}`,...e)}}function f(){return navigator.userAgent||""}function y(){return document.referrer||""}function w(){return window.location.href}function S(){if("u"<typeof window)return"";try{let t=window.location;return t&&"string"==typeof t.href?t.href:""}catch{return""}}let k=S()||null,v=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"];function E(t){if(!t)return!1;try{let e=new URL(t);if(v.some(t=>{let i=e.searchParams.get(t);return null!==i&&""!==i.trim()}))return!0;let i=h(t);return!!(i.adgroup_id||i.ad_id||i.click_id)}catch{return!1}}function I(){return document.title||""}function b(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function T(t,e){try{let i=new URL(t);return Object.entries(e).forEach(([t,e])=>{e&&!i.searchParams.has(t)&&i.searchParams.set(t,e)}),i.toString()}catch(e){return t}}function D(t,e=["utm_source","utm_medium","utm_campaign"]){let i={};
2return e.forEach(e=>{t[e]&&(i[e]=t[e])}),i}let A="ga_anon_id",P="ga_anon_id",U="anon_";function C(){if("u">typeof crypto&&"function"==typeof crypto.randomUUID)return U+crypto.randomUUID().replace(/-/g,"");let t="";for(let e=0;e<32;e++)t+=Math.floor(16*Math.random()).toString(16);return U+t}class O{constructor(t){this.logger=t}get(t){try{if(!m())return this.logger.warn("LocalStorage not supported"),null;let e=localStorage.getItem(t);if(null===e)return null;return JSON.parse(e)}catch(t){return this.logger.error("Error reading from localStorage:",t),null}}set(t,e){try{if(!m())return void this.logger.warn("LocalStorage not supported");localStorage.setItem(t,JSON.stringify(e))}catch(t){this.logger.error("Error writing to localStorage:",t),this.handleQuotaExceeded()}}remove(t){try{m()&&localStorage.removeItem(t)}catch(t){this.logger.error("Error removing from localStorage:",t)}}clear(){try{m()&&localStorage.clear()}catch(t){this.logger.error("Error clearing localStorage:",t)}}handleQuotaExceeded(){try{let t=Object.keys(localStorage).filter(t=>t.startsWith("attribution_"));if(t.length>0){t.sort((t,e)=>{let i=this.get(t),r=this.get(e);return(i?.expiresAt||0)-(r?.expiresAt||0)});let e=Math.ceil(.2*t.length);t.slice(0,e).forEach(t=>{this.remove(t)}),this.logger.info(`Cleaned up ${e} old attribution records`)}}catch(t){this.logger.error("Error during quota cleanup:",t)}}}class K{constructor(t){this.dbName="attribution_events",this.dbVersion=1,this.storeName="events",this.db=null,this.logger=t}async init(){return"indexedDB"in window?new Promise((t,e)=>{let i=indexedDB.open(this.dbName,this.dbVersion);i.onerror=()=>{this.logger.error("Failed to open IndexedDB:",i.error),e(i.error)},i.onsuccess=()=>{this.db=i.result,this.logger.info("IndexedDB initialized successfully"),t()},i.onupgradeneeded=t=>{let e=t.target.result;if(!e.objectStoreNames.contains(this.storeName)){let t=e.createObjectStore(this.storeName,{keyPath:"id",autoIncrement:!0});t.createIndex("timestamp","timestamp",{unique:!1}),t.createIndex("sent","sent",{unique:!1}),t.createIndex("queued_at","queued_at",{unique:!1})}}}):void this.logger.warn("IndexedDB not supported")}async addEvent(t){if(!this.db)throw Error("IndexedDB not initialized");return new Promise((e,i)=>{let r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName),n={...t,queued_at:Date.now(),sent:!1},a=r.add(n);a.onsuccess=()=>{this.logger.debug("Event added to IndexedDB queue"),e()},a.onerror=()=>{this.logger.error("Failed to add event to IndexedDB:",a.error),i(a.error)}})}async getUnsentEvents(t=100){return this.db?new Promise((e,i)=>{let r=this.db.transaction([this.storeName],"readonly").objectStore(this.storeName).index("sent").getAll(IDBKeyRange.only(!1),t);r.onsuccess=()=>{e(r.result.map(t=>{let{queued_at:e,sent:i,...r}=t;return r}))},r.onerror=()=>{this.logger.error("Failed to get unsent events:",r.error),i(r.error)}}):[]}async markEventsAsSent(t){if(this.db&&0!==t.length)return new Promise((e,i)=>{let r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName),n=0,a=!1;t.forEach(o=>{let s=r.get(o);s.onsuccess=()=>{if(s.result){let o={...s.result,sent:!0},l=r.put(o);l.onsuccess=()=>{++n!==t.length||a||e()},l.onerror=()=>{a=!0,this.logger.error("Failed to mark event as sent:",l.error),i(l.error)}}else++n!==t.length||a||e()},s.onerror=()=>{a=!0,this.logger.error("Failed to get event for marking as sent:",s.error),i(s.error)}})})}async cleanupOldEvents(t=6048e5){if(!this.db)return;let e=Date.now()-t;return new Promise((t,i)=>{let r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).index("queued_at").openCursor(IDBKeyRange.upperBound(e));r.onsuccess=()=>{let e=r.result;e?(e.delete(),e.continue()):(this.logger.info("Old events cleanup completed"),t())},r.onerror=()=>{this.logger.error("Failed to cleanup old events:",r.error),i(r.error)}})}async getQueueSize(){return this.db?new Promise((t,e)=>{let i=this.db.transaction([this.storeName],"readonly").objectStore(this.storeName).count();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{this.logger.error("Failed to get queue size:",i.error),e(i.error)}}):0}async clear(){if(this.db)return new Promise((t,e)=>{let i=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).clear();i.onsuccess=()=>{this.logger.info("IndexedDB queue cleared"),t()},i.onerror=()=>{this.logger.error("Failed to clear IndexedDB queue:",i.error),e(i.error)}})}}class R{constructor(t){this.UTM_STORAGE_KEY="attribution_utm_data",this.SESSION_STORAGE_KEY="attribution_session",this.SESSION_COOKIE_KEY="_getuai_session",this.ATTRIB_COOKIE_KEY="_getuai_attrib",this.USER_ID_KEY="getuai_user_id",this.PENDING_EVENTS_KEY="getuai_pending_events_v1",this.USER_TRAITS_KEY="getuai_user_traits",this.USER_ID_COOKIE_
2EXPIRES=365,this.ATTRIB_COOKIE_EXPIRES=30,this.SESSION_COOKIE_EXPIRES=1,this.cookieDomain=null,this.logger=t,this.localStorage=new O(t),this.indexedDB=new K(t)}setCookieDomain(t){this.cookieDomain=t,this.logger.debug(t?`ðª Cookie domain set to ${t} (cross-subdomain sharing enabled)`:"ðª Cookie domain not set â using host-only cookies")}setUserId(t){if(!t||""===t.trim())return void this.logger.warn("Cannot set empty user ID");let e=t.trim();try{this.setCookie(this.USER_ID_KEY,e,{days:this.USER_ID_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug(`ð¤ User ID stored in cookie: ${e}`)}catch(t){this.logger.error("Failed to store user ID in cookie:",t)}try{"u">typeof localStorage&&(localStorage.setItem(this.USER_ID_KEY,e),this.logger.debug(`ð¤ User ID stored in localStorage: ${e}`))}catch(t){this.logger.error("Failed to store user ID in localStorage:",t)}}getUserId(){let t=null;try{t=this.getCookie(this.USER_ID_KEY)}catch(t){this.logger.debug("Failed to get user ID from cookie:",t)}if(t){try{"u">typeof localStorage&&localStorage.getItem(this.USER_ID_KEY)!==t&&localStorage.setItem(this.USER_ID_KEY,t)}catch(t){}return t}try{if("u">typeof localStorage){let t=localStorage.getItem(this.USER_ID_KEY);if(t)return t}}catch(t){this.logger.debug("Failed to get user ID from localStorage:",t)}return null}removeUserId(){try{this.deleteCookie(this.USER_ID_KEY),this.logger.debug("ð¤ User ID removed from cookie")}catch(t){this.logger.error("Failed to remove user ID from cookie:",t)}try{"u">typeof localStorage&&(localStorage.removeItem(this.USER_ID_KEY),this.logger.debug("ð¤ User ID removed from localStorage"))}catch(t){this.logger.error("Failed to remove user ID from localStorage:",t)}}getAnonymousId(){try{let t=this.getCookie(A);if(t&&t.startsWith(U)){try{localStorage.setItem(P,t)}catch{}return t}}catch(t){this.logger.debug("anonymous_id cookie read failed",t)}try{let t="u">typeof localStorage?localStorage.getItem(P):null;if(t&&t.startsWith(U))return this.setAnonymousId(t),t}catch(t){this.logger.debug("anonymous_id localStorage read failed",t)}let t=C();return this.setAnonymousId(t),this.logger.info(`ð Generated new anonymous_id: ${t}`),t}setAnonymousId(t){if(!t||!t.startsWith(U))return void this.logger.warn(`Refusing to set malformed anonymous_id: ${t}`);try{this.setCookie(A,t,{days:365,domain:this.cookieDomain})}catch(t){this.logger.error("anonymous_id cookie write failed",t)}try{"u">typeof localStorage&&localStorage.setItem(P,t)}catch(t){this.logger.error("anonymous_id localStorage write failed",t)}}rotateAnonymousId(){let t=C();return this.setAnonymousId(t),this.logger.info(`ð Rotated anonymous_id: ${t}`),t}setCookie(t,e,i={}){try{let r="number"==typeof i?{days:i}:i,n=r.days??this.USER_ID_COOKIE_EXPIRES,a=new Date;a.setTime(a.getTime()+24*n*36e5);let o=r.secure??("u">typeof location&&"https:"===location.protocol),s=r.domain??this.cookieDomain,l=[`${t}=${encodeURIComponent(e)}`,`expires=${a.toUTCString()}`,"path=/","SameSite=Lax"];return s&&l.push(`domain=${s}`),o&&l.push("Secure"),document.cookie=l.join(";"),!0}catch(t){return this.logger.error("Failed to set cookie:",t),!1}}getCookie(t){try{let e=t+"=",i=document.cookie.split(";");for(let t=0;t<i.length;t++){let r=i[t];for(;" "===r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(e))return decodeURIComponent(r.substring(e.length,r.length))}return null}catch(t){return this.logger.error("Failed to get cookie:",t),null}}deleteCookie(t){try{document.cookie=`${t}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`,this.cookieDomain&&(document.cookie=`${t}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;domain=${this.cookieDomain};`)}catch(t){this.logger.error("Failed to delete cookie:",t)}}
2async init(){await this.indexedDB.init()}getPendingEvents(){try{let t=this.localStorage.get(this.PENDING_EVENTS_KEY);if(!Array.isArray(t))return[];return t}catch(t){return this.logger.debug("Failed to read pending events:",t),[]}}appendPendingEvents(t){if(t&&0!==t.length)try{let e=[...this.getPendingEvents(),...t].slice(-500);this.localStorage.set(this.PENDING_EVENTS_KEY,e)}catch(t){this.logger.debug("Failed to append pending events:",t)}}removePendingEventsByIds(t){if(t&&0!==t.length)try{let e=this.getPendingEvents();if(0===e.length)return;let i=new Set(t),r=e.filter(t=>!i.has(t.event_id));0===r.length?this.localStorage.remove(this.PENDING_EVENTS_KEY):this.localStorage.set(this.PENDING_EVENTS_KEY,r)}catch(t){this.logger.debug("Failed to remove pending events:",t)}}clearPendingEvents(){try{this.localStorage.remove(this.PENDING_EVENTS_KEY)}catch(t){this.logger.debug("Failed to clear pending events:",t)}}storeUTMData(t){try{let e=this.getUTMData(),i={utm_source:"",utm_medium:"",utm_campaign:"",utm_term:"",utm_content:"",timestamp:Date.now()},r={firstTouch:e?.firstTouch||i,lastTouch:e?.lastTouch||i,touchpoints:e?.touchpoints||[],...t,expiresAt:Date.now()+2592e6};this.writeAttribution(r),this.logger.debug("UTM data stored successfully:",{firstTouch:r.firstTouch,lastTouch:r.lastTouch,touchpointsCount:r.touchpoints.length,expiresAt:new Date(r.expiresAt).toISOString()})}catch(t){this.logger.error("Failed to store UTM data:",t)}}getUTMData(){let t=this.readAttributionFromCookie();if(t&&t.expiresAt&&t.expiresAt>Date.now())return t;t&&this.deleteCookie(this.ATTRIB_COOKIE_KEY);let e=this.localStorage.get(this.UTM_STORAGE_KEY);return e&&e.expiresAt&&e.expiresAt>Date.now()?e:(e&&this.localStorage.remove(this.UTM_STORAGE_KEY),null)}storeSession(t){try{let e=JSON.stringify(t);this.setCookie(this.SESSION_COOKIE_KEY,e,{days:this.SESSION_COOKIE_EXPIRES,domain:this.cookieDomain})}catch(t){this.logger.debug("Failed to store session in cookie:",t)}this.localStorage.set(this.SESSION_STORAGE_KEY,t)}getSession(){try{let t=this.getCookie(this.SESSION_COOKIE_KEY);if(t)return JSON.parse(t)}catch(t){this.logger.debug("Failed to parse session cookie:",t)}return this.localStorage.get(this.SESSION_STORAGE_KEY)}migrateLegacyStorage(){try{if(!this.getCookie(this.SESSION_COOKIE_KEY)){let t=this.localStorage.get(this.SESSION_STORAGE_KEY);t&&(this.setCookie(this.SESSION_COOKIE_KEY,JSON.stringify(t),{days:this.SESSION_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug("âï¸ Migrated legacy session to cookie"))}}catch(t){this.logger.debug("Session migration skipped:",t)}try{if(!this.getCookie(this.ATTRIB_COOKIE_KEY)){let t=this.localStorage.get(this.UTM_STORAGE_KEY);t&&t.expiresAt&&t.expiresAt>Date.now()&&(this.writeAttribution(t),this.logger.debug("âï¸ Migrated legacy attribution data to cookie"))}}catch(t){this.logger.debug("Attribution migration skipped:",t)}try{if(this.cookieDomain){let t=this.getCookie(this.USER_ID_KEY),e="u">typeof localStorage?localStorage.getItem(this.USER_ID_KEY):null;!t&&e&&(this.setCookie(this.USER_ID_KEY,e,{days:this.USER_ID_COOKIE_EXPIRES,domain:this.cookieDomain}),this.logger.debug("âï¸ Migrated legacy user ID to cross-subdomain cookie"))}}catch(t){this.logger.debug("User ID migration skipped:",t)}}writeAttribution(t){this.localStorage.set(this.UTM_STORAGE_KEY,t);let e=Math.max(1,Math.ceil(Math.max(0,t.expiresAt-Date.now())/864e5)),i=encodeURIComponent(JSON.stringify(t));if(i.length>3800){let r={...t,touchpoints:(t.touchpoints||[]).slice(-20)};(i=encodeURIComponent(JSON.stringify(r))).length>3800&&(i=encodeURIComponent(JSON.stringify({...r,touchpoints:[]}))),this.logger.debug("Attribution cookie payload trimmed to fit size limit"),this.setCookie(this.ATTRIB_COOKIE_KEY,decodeURIComponent(i),{days:e,domain:this.cookieDomain});return}this.setCookie(this.ATTRIB_COOKIE_KEY,JSON.stringify(t),{days:e,domain:this.cookieDomain})}readAttributionFromCookie(){try{let t=this.getCookie(this.ATTRIB_COOKIE_KEY);if(!t)return null;return JSON.parse(t)}catch(t){return this.logger.debug("Failed to parse attribution cookie:",t),null}}async queueEvent(t){try{await this.indexedDB.addEvent(t)}catch(t){throw this.logger.error("Failed to queue event:",t),t}}async getUnsentEvents(t=100){return await this.indexedDB.getUnsentEvents(t)}async markEventsAsSent(t){await this.indexedDB.markEventsAsSent(t)}async getQueueSize(){return await this.indexedDB.getQueueSize()}async cleanupOldEvents(){await this.indexedDB.cleanupOldEvents()}async clearQueue(){await this.indexedDB.clear()}cleanupExpiredData(){this.getUTMData()}setUserTraits(t){try{let e={...this.getUserTraits()||{},...t};"u">typeof localStorage&&(localStorage.setItem(this.USER_TRAITS_KEY,JSON.stringify(e)),this.logger.debug("User traits stored:",e))}catch(t){this.logger.error("Failed to store user traits:",t)}}getUserTraits(){try{if("u">typeof localStorage){let t=localStorage.getItem(this.USER_TRAITS_KEY);return t?JSON.parse(t):null}return null}catch(t){return this.logger.error("Failed to get user traits:",t),null}}clearUserTraits(){try{"u">typeof localStorage&&(localStorage.removeItem(this.USER_TRAITS_KEY),this.logger.debug("User traits cleared"))}catch(t){this.logger.error("Failed to clear user traits:",t)}}}let x="0.5.2";class N{constructor(t,e,i,r=100,n=2e3,a=3,o=1e3,s){this.queue=[],this.processing=!1,this.batchTimer=null,this.retryCounts=new Map,this.logger=t,this.apiKey=e,this.apiEndpoint=i,this.batchSize=r,this.batchInterval=n,this.maxRetries=a,this.retryDelay=o,this.sendEvents=s,this.debouncedProcess=function(t){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>t(...i),100)}}(this.process.bind(this))}add(t){if(a.includes(t.event_type)){this.logger.debug(`Immediate event detected: ${t.event_type}, sending immediately`),this.processImmediate(t);return}this.queue.push(t),this.logger.debug(`Event added to queue: ${t.event_type}`),this.scheduleBatchProcessing()}async process(){if(this.processing||0===this.queue.length)return;this.processing=!0;let t=this.queue.splice(0,this.batchSize);try{this.logger.debug(`Processing ${t.length} events from queue`),await this.sendEvents(t),this.resetRetryCounts(t),this.logger.info(`Successfully processed ${t.length} events`)}catch(e){this.logger.error("Failed to process events:",e),this.enqueueBatchForRetry(t),setTimeout(()=>{this.processing=!1,this.debouncedProcess()},this.retryDelay);return}this.processing=!1,this.queue.length>0&&this.debouncedProcess()}async processImmediate(t){try{this.logger.debug(`Processing immediate event: ${t.event_type}`),await this.sendEvents([t]),this.resetRetryCounts([t]),this.logger.info(`Immediate event processed successfully: ${t.event_type}`)}catch(e){this.logger.error(`Failed to process immediate event: ${t.event_type}`,e),this.enqueueBatchForRetry([t])}}scheduleBatchProcessing(){this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(()=>{this.debouncedProcess()},this.batchInterval)}clear(){this.queue=[],this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.processing=!1,this.logger.info("Event queue cleared")}size(){return this.queue.length}getStats(){return{size:this.queue.length,processing:this.processing}}async flush(){for(this.logger.info("Flushing event queue");this.queue.length>0;)await this.process()}drainAll(){let t=this.queue.splice(0,this.queue.length);return this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.processing=!1,t}enqueueBatchForRetry(t){let e=[];for(let i of t){let t=(this.retryCounts.get(i.event_id)||0)+1;if(this.retryCounts.set(i.event_id,t),t>this.maxRetries){this.logger.warn(`Dropping event after max retries (${this.maxRetries}): ${i.event_type} (${i.event_id})`),this.retryCounts.delete(i.event_id);continue}e.push(i)}e.length>0&&this.queue.unshift(...e)}resetRetryCounts(t){for(let e of t)this.retryCounts.delete(e.event_id)}}class F{constructor(t,e,i,r=3,n=1e3){this.logger=t,this.apiKey=e,this.apiEndpoint=i,this.maxRetries=r,this.retryDelay=n}async sendEvents(t){if(0===t.length)return;let e={events:t.map(t=>({event_id:t.event_id,event_type:t.event_type,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||s(),device:t.device||null,adgroup_id:t.adgroup_id||null,ad_id:t.ad_id||null,adgroup_id_source:t.adgroup_id_source||null,ad_id_source:t.ad_id_source||null,click_id:t.click_id||null,click_id_source:t.click_id_source||null,custom_event_name:t.custom_event_name||void 0})),sdk_version:x};await _(async()=>{let i=await fetch(`${this.apiEndpoint}/attribution/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(e)});if(!i.ok){let t=await i.text();throw Error(`HTTP ${i.status}: ${t}`)}let r=await i.json();return this.logger.debug("Events sent successfully:",r),{result:r,sentEvents:t}},this.maxRetries,this.retryDelay)}async sendEventsKeepalive(t){if(0===t.length)return;let e=t.map(t=>({event_id:t.event_id,event_type:t.event_type,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||s(),device:t.device||null,adgroup_id:t.adgroup_id||null,ad_id:t.ad_id||null,adgroup_id_source:t.adgroup_id_source||null,ad_id_source:t.ad_id_source||null,click_id:t.click_id||null,click_id_source:t.click_id_source||null,custom_event_name:t.custom_event_name||void 0})),i=await fetch(`${this.apiEndpoint}/attribution/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({events:e,sdk_version:x}),keepalive:!0});if(!i.ok)throw Error(`HTTP ${i.status}`)}sendEventsBeacon(t){if(0===t.length)return!0;
2if("u"<typeof navigator||"function"!=typeof navigator.sendBeacon)return!1;let e=t.map(t=>({event_id:t.event_id,event_type:t.event_type,anonymous_id:t.anonymous_id,tracking_user_id:t.tracking_user_id,utm_source:t.utm_source||null,utm_medium:t.utm_medium||null,utm_campaign:t.utm_campaign||null,utm_term:t.utm_term||null,utm_content:t.utm_content||null,revenue:t.revenue||null,currency:t.currency||null,event_data:t.event_data||null,context:t.context||null,timestamp:t.timestamp||s(),device:t.device||null,adgroup_id:t.adgroup_id||null,ad_id:t.ad_id||null,adgroup_id_source:t.adgroup_id_source||null,ad_id_source:t.ad_id_source||null,click_id:t.click_id||null,click_id_source:t.click_id_source||null,custom_event_name:t.custom_event_name||void 0})),i=`${this.apiEndpoint}/attribution/events_beacon?api_key=${encodeURIComponent(this.apiKey)}`,r=new Blob([JSON.stringify({events:e,sdk_version:x})],{type:"text/plain"});return navigator.sendBeacon(i,r)}async sendSingleEvent(t){await this.sendEvents([t])}async testConnection(){try{return(await fetch(`${this.apiEndpoint}/health`,{method:"GET",headers:{Authorization:`Bearer ${this.apiKey}`}})).ok}catch(t){return this.logger.error("Connection test failed:",t),!1}}}let M="__getuai_probe";class L{constructor(t){this.session=null,this.initialized=!1,this.autoTrackEnabled=!1,this.pageViewTrackTimes=new Map,this.cachedPublicIP=null,this.publicIPFetchPromise=null,this.initialPageViewTriggered=!1,this.spaTrackingEnabled=!1,this.lastTrackedPath="",this.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=null,this.config={apiEndpoint:n,batchSize:100,batchInterval:2e3,maxRetries:3,retryDelay:1e3,enableDebug:!1,autoTrack:!1,autoTrackPageView:!1,sessionTimeout:18e5,enableCrossDomainUTM:!0,crossDomainUTMParams:["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],excludeDomains:[],autoCleanUTM:!0,pageViewDebounceInterval:5e3,...t},this.logger=new p(this.config.enableDebug),this.storage=new R(this.logger),this.httpClient=new F(this.logger,this.config.apiKey,this.config.apiEndpoint||n,this.config.maxRetries,this.config.retryDelay),this.queue=new N(this.logger,this.config.apiKey,this.config.apiEndpoint||n,this.config.batchSize,this.config.batchInterval,this.config.maxRetries,this.config.retryDelay,t=>this.httpClient.sendEvents(t))}
2async init(){if(this.initialized)return void this.logger.warn("SDK already initialized");try{this.logger.info("Initializing GetuAI Attribution SDK");let t=function(t){if(!t)return null;let e=t.trim();return e?e.startsWith(".")?e:"."+e:null}(this.config.domain)??function(){if(!function(){try{return"u">typeof document&&"string"==typeof document.cookie}catch{return!1}}())return null;let t="u">typeof location&&location.hostname||"";if(!t||"localhost"===t||/^\d+\.\d+\.\d+\.\d+$/.test(t)||t.includes(":"))return null;let e=t.split(".").filter(Boolean);if(e.length<2)return null;for(let t=e.length-2;t>=0;t--){let i="."+e.slice(t).join(".");if(function(t){try{document.cookie=`${M}=1;domain=${t};path=/;SameSite=Lax`;let e=document.cookie.split(";").some(t=>t.trim().startsWith(`${M}=`));return e&&(document.cookie=`${M}=;domain=${t};path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT`),e}catch{return!1}}(i))return i}return null}();this.storage.setCookieDomain(t),this.storage.init().catch(t=>{this.logger.warn("Storage initialization failed (IndexedDB may be unavailable), continuing with basic features:",t)});try{this.storage.migrateLegacyStorage()}catch(t){this.logger.debug("Legacy storage migration skipped:",t)}this.initializeUserId(),this.initializeSession(),this.extractAndStoreUTMData(),this.config.autoTrack&&this.setupAutoTracking(),this.setupNetworkHandlers(),this.setupVisibilityHandlers(),this.setupBeforeUnloadHandler(),this.initialized=!0,this.logger.info("ð GetuAI Attribution SDK initialized successfully"),this.logger.info("ð Auto track page view = "+this.config.autoTrackPageView),this.retryPendingEvents().catch(t=>{this.logger.warn("â ï¸ Pending events retry failed",t)}),this.config.autoTrackPageView&&(this.logger.info("ð Auto track page view enabled (including SPA route tracking)"),this.lastTrackedPath=this.getCurrentPath(),this.setupSPATracking(),this.initialPageViewTriggered||(this.initialPageViewTriggered=!0,Promise.resolve().then(()=>this.trackPageView()).then(()=>this.queue.process()).then(()=>{this.logger.info("â
Auto track page view completed")}).catch(t=>this.logger.error("â Auto track page view failed:",t))))}catch(t){throw this.logger.error("Failed to initialize SDK:",t),t}}async trackEvent(t,r,n,a,o=i.USD,l){if(!this.initialized)return void this.logger.warn("SDK not initialized, event not tracked");try{let i,u=w(),c=this.cachedPublicIP;this.ensurePublicIPFetched();let d={domain:"u">typeof window?window.location.hostname:null,path:"u">typeof window?window.location.pathname:null,title:I(),referrer:y(),url:u.split("?")[0],querystring:function(t){try{let e=t||window.location.href;return new URL(e).search}catch(t){return""}}(u),query_params:function(t){try{let e=t||window.location.href,i=new URL(e),r={};return i.searchParams.forEach((t,e)=>{r[e]=t}),r}catch(t){return{}}}(u),ip_address:c,user_agent:f()},g={session_id:this.session?.sessionId,start_time:this.session?.startTime,last_activity:this.session?.lastActivity,page_views:this.session?.pageViews},h=this.storage.getAnonymousId(),m=n||this.getUserId(),_={event_id:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){let e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}),event_type:t,anonymous_id:h,tracking_user_id:m||void 0,timestamp:s(),event_data:r,context:{page:d,session:g},revenue:a,currency:o,...t===e.CUSTOM&&l?{custom_event_name:l}:{},...this.getUTMParams(),device:(i="u">typeof navigator&&navigator.userAgent||"",/iPad|Tablet|PlayBook|Silk/i.test(i)?"tablet":/Mobi|Android|iPhone|iPod/i.test(i)?"mobile":"desktop"),...this.getAdParams()};this.logger.debug(`Tracking event: ${t}`,_),this.queue.add(_)}catch(e){this.logger.error(`Failed to track event ${t}:`,e)}}async trackCustomEvent(t,r,n,a,o=i.USD){t&&""!==t.trim()?await this.trackEvent(e.CUSTOM,r,n,a,o,t.trim()):this.logger.error("trackCustomEvent requires a non-empty customEventName")}async trackPageView(t,i){let r=w(),n=r.split("?")[0],a=Date.now(),o=this.config.pageViewDebounceInterval||5e3,s=this.pageViewTrackTimes.get(n);if(s&&a-s<o)return void this.logger.debug(`Page view debounced: ${n} (last tracked ${a-s}ms ago)`);let l={url:r,title:I(),referrer:y(),user_agent:f(),...t};
2await this.trackEvent(e.PAGE_VIEW,l,i),this.pageViewTrackTimes.set(n,a),this.cleanupPageViewTrackTimes()}cleanupPageViewTrackTimes(){let t=Date.now()-36e5;for(let[e,i]of this.pageViewTrackTimes.entries())i<t&&this.pageViewTrackTimes.delete(e)}ensurePublicIPFetched(){this.cachedPublicIP||this.publicIPFetchPromise||(this.publicIPFetchPromise=this.fetchPublicIP().then(t=>(t&&(this.cachedPublicIP=t),t)).catch(()=>null).finally(()=>{this.publicIPFetchPromise=null}))}async fetchPublicIP(){try{let t=new AbortController,e=setTimeout(()=>t.abort(),2e3),i=await fetch("https://api.ipify.org?format=json",{signal:t.signal,headers:{Accept:"application/json"}});if(clearTimeout(e),!i.ok)return null;let r=await i.json();return"string"==typeof r?.ip?r.ip:null}catch(t){return this.logger.debug("Public IP fetch failed",t),null}}async trackPurchase(t,r,n=i.USD,a){await this.trackEvent(e.PURCHASE,a,t,r,n)}async trackLogin(t,i){await this.trackEvent(e.LOGIN,i,t)}async trackSignup(t,i){await this.trackEvent(e.SIGNUP,i,t)}async trackFormSubmit(t,i){await this.trackEvent(e.FORM_SUBMIT,i,t)}async trackVideoPlay(t,i){await this.trackEvent(e.VIDEO_PLAY,i,t)}async trackEmailVerification(t,i){await this.trackEvent(e.EMAIL_VERIFICATION,i,t)}async trackAuditApproved(t,i){await this.trackEvent(e.AUDIT_APPROVED,i,t)}async trackPurchaseAuto(t){let r=t.tracking_user_id||this.getUserId();r?await this.trackEvent(e.PURCHASE,t.purchaseData,r,t.revenue,t.currency||i.USD):this.logger.error("â trackPurchaseAuto requires tracking_user_id. Please set user ID using setUserId() or pass it in options.tracking_user_id.")}async trackLoginAuto(t){let i=t.tracking_user_id||this.getUserId();i?await this.trackEvent(e.LOGIN,t.loginData,i):this.logger.error("â trackLoginAuto requires tracking_user_id. Please set user ID using setUserId() or pass it in options.tracking_user_id.")}async trackSignupAuto(t){let i=t.tracking_user_id||this.getUserId();i?await this.trackEvent(e.SIGNUP,t.signupData,i):this.logger.error("â trackSignupAuto requires tracking_user_id. Please set user ID using setUserId() or pass it in options.tracking_user_id.")}async trackEmailVerificationAuto(t){let i=t.tracking_user_id||this.getUserId();i?await this.trackEvent(e.EMAIL_VERIFICATION,t.verificationData,i):this.logger.error("â trackEmailVerificationAuto requires tracking_user_id. Please set user ID using setUserId() or pass it in options.tracking_user_id.")}async trackProductView(t,i){await this.trackEvent(e.PRODUCT_VIEW,i,t)}async trackAddToCart(t,i){await this.trackEvent(e.ADD_TO_CART,i,t)}async trackPageClick(t,i){await this.trackEvent(e.PAGE_CLICK,i,t)}async trackButtonClick(t,i,r){await this.trackEvent(e.BUTTON_CLICK,{button_name:t,...r},i)}getAttributionData(){return this.storage.getUTMData()}addUTMToURL(t){if(!this.config.enableCrossDomainUTM)return t;let e=this.getAttributionData();return e?T(t,D(e.lastTouch,this.config.crossDomainUTMParams)):t}getCurrentUTMParams(){let t=this.getAttributionData();return t?D(t.lastTouch,this.config.crossDomainUTMParams):{}}getUTMParams(){let t=this.getAttributionData();if(!t)return this.logger.debug("No attribution data available for UTM params"),{};let e={utm_source:t.lastTouch.utm_source||null,utm_medium:t.lastTouch.utm_medium||null,utm_campaign:t.lastTouch.utm_campaign||null,utm_term:t.lastTouch.utm_term||null,utm_content:t.lastTouch.utm_content||null},i={};return e.utm_source&&""!==e.utm_source.trim()?i.utm_source=e.utm_source:i.utm_source=null,e.utm_medium&&""!==e.utm_medium.trim()?i.utm_medium=e.utm_medium:i.utm_medium=null,e.utm_campaign&&""!==e.utm_campaign.trim()?i.utm_campaign=e.utm_campaign:i.utm_campaign=null,e.utm_term&&""!==e.utm_term.trim()?i.utm_term=e.utm_term:i.utm_term=null,e.utm_content&&""!==e.utm_content.trim()?i.utm_content=e.utm_content:i.utm_content=null,this.logger.debug("UTM params for event:",i),i}getAdParams(){let t=this.getAttributionData();if(!t)return{};let e=t.lastTouch,i=t=>t&&"string"==typeof t&&""!==t.trim()?t:null;return{adgroup_id:i(e.adgroup_id),ad_id:i(e.ad_id),adgroup_id_source:i(e.adgroup_id_source),ad_id_source:i(e.ad_id_source),click_id:i(e.click_id),click_id_source:i(e.click_id_source)}}initializeUserId(){if(this.config.userId)this.setUserId(this.config.userId),this.logger.info(`ð¤ User ID initialized from config: ${this.config.userId}`);else{let t=this.getUserId();t?this.logger.debug(`ð¤ Existing user ID found: ${t}`):this.logger.debug("ð¤ No user ID found, will be set when user identifies")}}setUserId(t){if(!t||""===t.trim())return void this.logger.warn("Cannot set empty user ID");let e=t.trim(),i=this.storage.getUserId();if(i!==e){if(i&&i!==e&&(this.logger.info(`ð¥ User changed (${i} â ${e}) â rotating anonymous_id + session`),this.storage.rotateAnonymousId()),this.storage.setUserId(e),this.session){let t=this.session.userId;t&&t!==e?(this.logger.info(`ð Session previously owned by ${t} â rotating session for ${e}`),this.rotateSession(e)):t!==e&&(this.session={...this.session,userId:e},this.storage.storeSession(this.session))}this.logger.info(`ð¤ User ID set: ${e}`)}}rotateSession(t){let e=Date.now();this.session={sessionId:b(),startTime:e,lastActivity:e,pageViews:0,userId:t},this.storage.storeSession(this.session)}getUserId(){return this.storage.getUserId()}getAnonymousId(){return this.storage.getAnonymousId()}removeUserId(){this.storage.removeUserId(),this.logger.info("ð¤ User ID removed")}async identify(t,i){this.initialized?t&&""!==t.trim()?(this.setUserId(t),i&&(this.storage.setUserTraits(i),this.logger.info(`User identified: ${t}`,i)),await this.trackEvent(e.FORM_SUBMIT,{_identify:!0,_user_traits:i,tracking_user_id:t},t)):this.logger.warn("Cannot identify with empty user ID"):this.logger.warn("SDK not initialized, identify call queued")}getUserTraits(){return this.storage.getUserTraits()}getSessionId(){return this.session?.sessionId||null}initializeSession(){let t=this.storage.getSession(),e=Date.now(),i=this.storage.getUserId()??void 0,r=t&&e-t.lastActivity<this.config.sessionTimeout,n=!!(t?.userId&&i&&t.userId!==i);r&&!n?this.session={...t,lastActivity:e,userId:t.userId??i}:(n&&this.logger.info(`ð Session owner changed (${t?.userId} â ${i}) â starting new session`),this.session={sessionId:b(),startTime:e,lastActivity:e,pageViews:0,userId:i}),this.storage.storeSession(this.session),this.logger.debug("Session initialized:",this.session)}extractAndStoreUTMData(){let t,e,i=function(){let t=S();if(E(t))return t;if(E(k))return k;let e=function(){if("u"<typeof performance)return null;let t=performance.getEntriesByType;if("function"!=typeof t)return null;try{let e=t.call(performance,"navigation");if(e&&e.length>0){let t=e[0].name;if("string"==typeof t&&t.length>0)return t}}catch{}return null}();return E(e)?e:t}(),r=(t=function(t){let e={};
2try{new URL(t).searchParams.forEach((t,i)=>{e[i]=t})}catch(t){}return e}(i),e={},["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(i=>{t[i]&&""!==t[i].trim()&&(e[i]=t[i].trim())}),e),n=h(i);if(this.logger.debug("Extracting UTM params from URL:",i),this.logger.debug("Found UTM params:",r),this.logger.debug("Found ad params:",n),0===Object.keys(r).length&&!n.adgroup_id&&!n.ad_id&&!n.click_id)return void this.logger.debug("No UTM, ad, or click parameters found in URL");let a={utm_source:r.utm_source||"",utm_medium:r.utm_medium||"",utm_campaign:r.utm_campaign||"",utm_term:r.utm_term||"",utm_content:r.utm_content||"",adgroup_id:n.adgroup_id||"",ad_id:n.ad_id||"",adgroup_id_source:n.adgroup_id_source||"",ad_id_source:n.ad_id_source||"",click_id:n.click_id||"",click_id_source:n.click_id_source||"",timestamp:Date.now()},o=this.getAttributionData(),s={firstTouch:o?.firstTouch||a,lastTouch:a,touchpoints:o?.touchpoints||[],expiresAt:Date.now()+2592e6};o&&o.lastTouch.utm_source===a.utm_source&&o.lastTouch.utm_campaign===a.utm_campaign||s.touchpoints.push(a),this.storage.storeUTMData(s),this.logger.info("UTM data extracted and stored successfully:",a),this.config.autoCleanUTM&&function(){try{let t=new URL(window.location.href),e=!1;["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(i=>{t.searchParams.has(i)&&(t.searchParams.delete(i),e=!0)}),e&&window.history.replaceState({},document.title,t.toString())}catch(t){console.warn("Failed to clean URL:",t)}}()}setupAutoTracking(){this.autoTrackEnabled=!0,this.setupFormTracking(),this.setupLinkTracking(),this.logger.info("Auto-tracking enabled")}setupFormTracking(){document.addEventListener("submit",t=>{try{let i=t.target;if(!i)return;let r=this.serializeFormFields(i),n=this.extractLeadFields(r);n.email&&(this.storage.setUserTraits(n),this.logger.debug("Lead fields extracted from form:",n)),this.trackEvent(e.FORM_SUBMIT,{...r,_lead_fields:n,form_id:i.id||i.name,form_action:i.action,form_method:i.method})}catch(t){this.logger.error("Failed to auto-track form submit:",t)}})}serializeFormFields(t){let e={};try{for(let[i,r]of new FormData(t).entries()){let t=this.serializeFormValue(r);if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];Array.isArray(r)?(r.push(t),e[i]=r):e[i]=[r,t]}else e[i]=t}let i=Array.from(t.elements),r=new Map;for(let t=0;t<i.length;t++){let e=i[t];if(e.disabled)continue;let n=e.tagName.toLowerCase(),a=e.type?.toLowerCase();if("button"===n||"submit"===a||"reset"===a)continue;let o=this.getFormFieldKey(e,t);o&&(r.has(o)||r.set(o,[]),r.get(o).push(e))}r.forEach((t,i)=>{let r=t.some(t=>"radio"===t.type),n=t.some(t=>"checkbox"===t.type),a=t.some(t=>"file"===t.type),o=t.some(t=>"SELECT"===t.tagName&&t.multiple),s=t.some(t=>"password"===t.type);if(n){let r=t.filter(t=>"checkbox"===t.type).filter(t=>t.checked).map(t=>t.value||"on");Object.prototype.hasOwnProperty.call(e,i)?Array.isArray(e[i])||(e[i]=[e[i],...r]):e[i]=r;return}if(r){let r=t.filter(t=>"radio"===t.type).find(t=>t.checked);Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r?r.value:null);return}if(o){let r=t.find(t=>"SELECT"===t.tagName&&t.multiple);if(r){let t=Array.from(r.selectedOptions).map(t=>t.value);Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t);return}}if(a){let r=t.find(t=>"file"===t.type);if(r){let t=r.files?Array.from(r.files):[];Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t.map(t=>this.serializeFormValue(t)));return}}if(s)return void(Object.prototype.hasOwnProperty.call(e,i)?e[i]="string"==typeof e[i]?"*****":e[i]:e[i]="*****");if(!Object.prototype.hasOwnProperty.call(e,i)){let r=t[0];"SELECT"===r.tagName?e[i]=r.multiple?Array.from(r.selectedOptions).map(t=>t.value):r.value:(r.type,e[i]=r.value??"")}})}catch(t){this.logger.error("Failed to serialize form fields:",t)}return e}getFormFieldKey(t,e){let i=t.name;if(i)return i;if(t.id)return`id_${t.id}`;let r=t.getAttribute("aria-label");if(r&&r.trim())return`aria_${this.normalizeFormFieldKey(r)}`;let n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.placeholder:"";return n&&n.trim()?`ph_${this.normalizeFormFieldKey(n)}_${e}`:`field_${e}`}normalizeFormFieldKey(t){return t.trim().toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_]/g,"").slice(0,40)}serializeFormValue(t){return t instanceof File?{file_name:t.name,file_size:t.size,file_type:t.type}:t}extractLeadFields(t){let e={};for(let[i,r]of Object.entries(o))if(!e[i])for(let n of r||[]){let r=n.toLowerCase();for(let[n,a]of Object.entries(t))if((n.toLowerCase()===r||n.toLowerCase().includes(r))&&a&&"string"==typeof a&&a.trim()){e[i]=a.trim();break}if(e[i])break}return!e.name&&(e.first_name||e.last_name)&&(e.name=[e.first_name,e.last_name].filter(
2Boolean).join(" ").trim()),e}setupLinkTracking(){document.addEventListener("click",t=>{let e=t.target.closest("a");e&&function(t){try{let e=new URL(t),i=window.location.hostname;return e.hostname!==i}catch(t){return!1}}(e.href)&&this.handleCrossDomainUTM(e,t)})}handleCrossDomainUTM(t,e){if(!this.config.enableCrossDomainUTM)return;let i=t.href;if(function(t,e=[]){try{let i=new URL(t).hostname.toLowerCase();return e.some(t=>{let e=t.toLowerCase();return i===e||i.endsWith(`.${e}`)})}catch(t){return!1}}(i,this.config.excludeDomains))return void this.logger.debug(`Domain excluded from UTM passing: ${i}`);let r=this.getAttributionData();if(!r)return void this.logger.debug("No UTM data available for cross-domain passing");let n=D(r.lastTouch,this.config.crossDomainUTMParams);if(0===Object.keys(n).length)return void this.logger.debug("No UTM parameters to pass");let a=T(i,n);a!==i&&(t.href=a,this.logger.debug("UTM parameters added to external link:",{original:i,enhanced:a,utmParams:n}),this.logger.debug("Cross-domain UTM passed:",{link_url:a,original_url:i,utm_params_passed:n}))}setupNetworkHandlers(){window.addEventListener("online",()=>{this.logger.info("Network connection restored"),this.queue.flush()}),window.addEventListener("offline",()=>{this.logger.warn("Network connection lost")})}setupVisibilityHandlers(){document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this.flushOnUnload("visibilitychange:hidden"):"visible"===document.visibilityState&&this.updateSessionActivity()})}setupBeforeUnloadHandler(){window.addEventListener("beforeunload",()=>{this.flushOnUnload("beforeunload")}),window.addEventListener("pagehide",()=>{this.flushOnUnload("pagehide")})}flushOnUnload(t){try{this.updateSessionActivity();let e=this.queue.drainAll();if(0===e.length)return;if(this.storage.appendPendingEvents(e),this.logger.debug(`ð Unload flush triggered: ${t}`,{count:e.length}),this.httpClient.sendEventsBeacon(e))return void this.storage.removePendingEventsByIds(e.map(t=>t.event_id));for(let t=0;t<e.length;t+=20){let i=e.slice(t,t+20);this.httpClient.sendEventsKeepalive(i).then(()=>{this.storage.removePendingEventsByIds(i.map(t=>t.event_id))}).catch(t=>{this.logger.debug("Unload keepalive send failed",t)})}}catch(t){this.logger.debug("flushOnUnload failed",t)}}async retryPendingEvents(){let t=this.storage.getPendingEvents();if(0!==t.length){this.logger.info(`ð¦ Retrying pending events: ${t.length}`);try{await this.httpClient.sendEvents(t),this.storage.removePendingEventsByIds(t.map(t=>t.event_id)),this.logger.info(`â
Pending events sent: ${t.length}`)}catch(t){this.logger.warn("â ï¸ Pending events retry failed",t)}}}getCurrentPath(){return"u"<typeof window?"":window.location.pathname+window.location.search}setupSPATracking(){if("u"<typeof window||"u"<typeof history)return void this.logger.warn("â ï¸ SPA tracking not available in this environment");if(this.spaTrackingEnabled)return void this.logger.warn("â ï¸ SPA tracking already enabled");this.spaTrackingEnabled=!0,this.lastTrackedPath=this.getCurrentPath(),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history);let t=t=>{let e=this.getCurrentPath();e===this.lastTrackedPath?this.logger.debug(`ð [SPA] Route change detected (${t}) but path unchanged: ${e}`):(this.logger.debug(`ð [SPA] Route change detected (${t}): ${this.lastTrackedPath} -> ${e}`),this.lastTrackedPath=e,setTimeout(()=>{this.trackPageView().then(()=>this.queue.process()).then(()=>{this.logger.debug(`â
[SPA] Page view tracked for: ${e}`)}).catch(t=>{this.logger.error("â [SPA] Failed to track page view:",t)})},100))};history.pushState=(e,i,r)=>{let n=this.originalPushState(e,i,r);return t("pushState"),n},history.replaceState=(e,i,r)=>{let n=this.originalReplaceState(e,i,r);return t("replaceState"),n},this.popstateHandler=()=>{t("popstate")},window.addEventListener("popstate",this.popstateHandler),this.logger.info("ð SPA tracking setup completed")}cleanupSPATracking(){this.spaTrackingEnabled&&(this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popstateHandler&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.spaTrackingEnabled=!1,this.logger.info("ð SPA tracking cleaned up"))}updateSessionActivity(){this.session&&(this.session.lastActivity=Date.now(),this.storage.storeSession(this.session))}async flush(){await this.queue.flush()}getStatus(){return{initialized:this.initialized,session:this.session,queueSize:this.queue.size(),online:navigator.onLine,crossDomainUTM:{enabled:this.config.enableCrossDomainUTM||!0,currentParam
2s:this.getCurrentUTMParams()},spaTracking:{enabled:this.spaTrackingEnabled,currentPath:this.lastTrackedPath}}}destroy(){this.queue.clear(),this.autoTrackEnabled=!1,this.cleanupSPATracking(),this.initialized=!1,this.logger.info("ðï¸ SDK destroyed")}}let z=null;async function $(t){if(z)return console.warn("GetuAI SDK: Already initialized"),z;try{if(z=new L(t),await z.init(),t.enableDebug&&(window.GetuAISDK=z),console.log("GetuAI Attribution SDK initialized successfully"),"u">typeof window){let t=new CustomEvent("getuaiSDKReady",{detail:{sdk:z}});window.dispatchEvent(t)}return z}catch(t){if(console.error("GetuAI SDK: Failed to initialize:",t),"u">typeof window){let e=new CustomEvent("getuaiSDKError",{detail:{error:t}});window.dispatchEvent(e)}throw t}}function V(){return new Promise((t,e)=>{if(z)return void t(z);let i=e=>{window.removeEventListener("getuaiSDKReady",i),window.removeEventListener("getuaiSDKError",r),t(e.detail.sdk)},r=t=>{window.removeEventListener("getuaiSDKReady",i),window.removeEventListener("getuaiSDKError",r),e(t.detail.error)};window.addEventListener("getuaiSDKReady",i),window.addEventListener("getuaiSDKError",r),setTimeout(()=>{window.removeEventListener("getuaiSDKReady",i),window.removeEventListener("getuaiSDKError",r),e(Error("SDK initialization timeout"))},1e4)})}async function G(t,e,r,n,a=i.USD){let o=z;o?await o.trackEvent(t,e,r,n,a):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function B(t,e){let i=z;i?await i.trackPageView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function q(t,e,r=i.USD,n){let a=z;a?await a.trackPurchase(t,e,r,n):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function Y(t,e){let i=z;i?await i.trackLogin(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function j(t,e){let i=z;i?await i.trackSignup(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function H(t,e){let i=z;i?await i.trackFormSubmit(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function J(t,e){let i=z;i?await i.trackVideoPlay(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function W(t,e){let i=z;i?await i.trackEmailVerification(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function X(t,e){let i=z;i?await i.trackAuditApproved(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function Q(t){let e=z;e?await e.trackPurchaseAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function Z(t){let e=z;e?await e.trackLoginAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function tt(t){let e=z;e?await e.trackSignupAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function te(t){let e=z;e?await e.trackEmailVerificationAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function ti(t,e,r,n,a=i.USD){let o=z;o?await o.trackCustomEvent(t,e,r,n,a):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function tr(t,e){let i=z;i?await i.trackProductView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function tn(t,e){let i=z;i?await i.trackAddToCart(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function ta(t,e){let i=z;i?await i.trackPageClick(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function to(t,e,i){let r=z;r?await r.trackButtonClick(t,e,i):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function ts(){let t=z;return t?t.getAttributionData():null}async function tl(){let t=z;t?await t.flush():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function tu(){let t=z;return t?t.getStatus():null}function tc(t){let e=z;return e?e.addUTMToURL(t):(console.warn("GetuAI SDK: Not initialized. Call init() first."),t)}function td(){let t=z;return t?t.getCurrentUTMParams():{}}function tg(t){let e=z;e?e.setUserId(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function th(){let t=z;return t?t.getUserId():(console.warn("GetuAI SDK: Not initialized. Call init() first."),null)}function tm(){let t=z;t?t.removeUserId():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function t_(){z&&(z.destroy(),z=null,console.log("GetuAI SDK destroyed"))}class tp extends L{static async init(t){return await $(t)}static async trackEvent(t,e,r,n,a=i.USD){return await G(t,e,r,n,a)}static async trackPageView(t,e){return await B(t,e)}static async trackPurchase(t,e,r=i.USD,n){return await q(t,e,r,n)}static async trackLogin(t,e){return await Y(t,e)}static async trackSignup(t,e){return await j(t,e)}static async trackFormSubmit(t,e){return await H(t,e)}static async trackVideoPlay(t,e){return await J(t,e)}static async trackEmailVerification(t,e){return await W(t,e)}static async trackPurchaseAuto(t){return await Q(t)}static async trackLoginAuto(t){return await Z(t)}static async trackSignupAuto(t){return await tt(t)}static async trackEmailVerificationAuto(t){return await te(t)}static async trackCustomEvent(t,e,r,n,a=i.USD){return await ti(t,e,r,n,a)}static async trackProductView(t,e){return await tr(t,e)}static async trackAddToCart(t,e){return await tn(t,e)}static async trackPageClick(t,e){return await ta(t,e)}
2static async trackButtonClick(t,e,i){return await to(t,e,i)}static getAttributionData(){return ts()}static async flush(){return await tl()}static getStatus(){return tu()}static addUTMToURL(t){return tc(t)}static getCurrentUTMParams(){return td()}static setUserId(t){tg(t)}static getUserId(){return th()}static removeUserId(){tm()}static destroy(){t_()}static getSDK(){return z}static waitForSDK(){return V()}}"u">typeof document&&function(){if(z)return;let t=document.currentScript;if(!t)return console.warn("GetuAI SDK: Could not find script tag for auto-initialization");let e=t.getAttribute("data-api-key");e?$({apiKey:e,apiEndpoint:t.getAttribute("data-api-endpoint")||n,enableDebug:"true"===t.getAttribute("data-debug"),autoTrack:"true"===t.getAttribute("data-auto-track"),autoTrackPageView:"true"===t.getAttribute("data-auto-track-page-view"),autoCleanUTM:"false"!==t.getAttribute("data-auto-clean-utm"),batchSize:parseInt(t.getAttribute("data-batch-size")||"100"),batchInterval:parseInt(t.getAttribute("data-batch-interval")||"2000"),userId:t.getAttribute("data-user-id")||void 0,domain:t.getAttribute("data-domain")||void 0}):console.warn("GetuAI SDK: No API key provided. Please add data-api-key attribute to script tag.")}(),"u">typeof window&&(window.getuaiSDK={init:$,getSDK:function(){return z},waitForSDK:V,trackEvent:G,trackPageView:B,trackPageClick:ta,trackButtonClick:to,trackPurchase:q,trackLogin:Y,trackSignup:j,trackFormSubmit:H,trackVideoPlay:J,trackEmailVerification:W,trackAuditApproved:X,trackCustomEvent:ti,trackProductView:tr,trackAddToCart:tn,trackPurchaseAuto:Q,trackLoginAuto:Z,trackSignupAuto:tt,trackEmailVerificationAuto:te,getAttributionData:ts,flush:tl,getStatus:tu,addUTMToURL:tc,getCurrentUTMParams:td,setUserId:tg,getUserId:th,removeUserId:tm,destroy:t_,EventType:e,Currency:i,AttributionSDK:tp},window.init=$,window.waitForSDK=V,window.trackEvent=G,window.trackPageView=B,window.trackPageClick=ta,window.trackButtonClick=to,window.trackPurchase=q,window.trackLogin=Y,window.trackSignup=j,window.trackFormSubmit=H,window.trackVideoPlay=J,window.trackEmailVerification=W,window.trackProductView=tr,window.trackAddToCart=tn,window.trackPurchaseAuto=Q,window.trackLoginAuto=Z,window.trackSignupAuto=tt,window.trackEmailVerificationAuto=te,window.getAttributionData=ts,window.flush=tl,window.getStatus=tu,window.addUTMToURL=tc,window.getCurrentUTMParams=td,window.setUserId=tg,window.getUserId=th,window.removeUserId=tm,window.destroy=t_,window.AttributionSDK=tp),t.s(["init",0,$,"trackFormSubmit",0,H])}]); 3 4//# debugId=a0ae97ed-020f-6bf2-f060-a469efcee1d1
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.