getu-attribution-v2-sdk 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,9 @@ export declare class AttributionSDK {
9
9
  private initialized;
10
10
  private autoTrackEnabled;
11
11
  private pageViewTrackTimes;
12
+ private cachedPublicIP;
13
+ private publicIPFetchPromise;
14
+ private initialPageViewTriggered;
12
15
  private spaTrackingEnabled;
13
16
  private lastTrackedPath;
14
17
  private originalPushState;
@@ -19,6 +22,7 @@ export declare class AttributionSDK {
19
22
  trackEvent(eventType: EventType, eventData?: Record<string, any>, tracking_user_id?: string, revenue?: number, currency?: Currency): Promise<void>;
20
23
  trackPageView(pageData?: Record<string, any>, tracking_user_id?: string): Promise<void>;
21
24
  private cleanupPageViewTrackTimes;
25
+ private ensurePublicIPFetched;
22
26
  private fetchPublicIP;
23
27
  trackPurchase(tracking_user_id: string, revenue: number, currency?: Currency, purchaseData?: Record<string, any>): Promise<void>;
24
28
  trackLogin(tracking_user_id: string, loginData?: Record<string, any>): Promise<void>;
@@ -67,6 +71,8 @@ export declare class AttributionSDK {
67
71
  private setupNetworkHandlers;
68
72
  private setupVisibilityHandlers;
69
73
  private setupBeforeUnloadHandler;
74
+ private flushOnUnload;
75
+ private retryPendingEvents;
70
76
  private getCurrentPath;
71
77
  private setupSPATracking;
72
78
  private cleanupSPATracking;
@@ -1 +1 @@
1
- {"version":3,"file":"AttributionSDK.d.ts","sourceRoot":"","sources":["../../src/core/AttributionSDK.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EAET,SAAS,EACT,eAAe,EAEf,QAAQ,EACR,WAAW,EAGZ,MAAM,UAAU,CAAC;AAuBlB,qBAAa,cAAc;IACzB,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,UAAU,CAAkB;IACpC,OAAO,CAAC,K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;YACX,OAAO,EAAE,OAAO,CAAC;YACjB,WAAW,EAAE,MAAM,CAAC;SACrB,CAAC;KACH;IAkBD,OAAO,IAAI,IAAI;CAOhB"}
@@ -8,6 +8,9 @@ export class AttributionSDK {
8
8
  this.initialized = false;
9
9
  this.autoTrackEnabled = false;
10
10
  this.pageViewTrackTimes = new Map();
11
+ this.cachedPublicIP = null;
12
+ this.publicIPFetchPromise = null;
13
+ this.initialPageViewTriggered = false;
11
14
  // SPA tracking internals
12
15
  this.spaTrackingEnabled = false;
13
16
  this.lastTrackedPath = "";
@@ -49,15 +52,10 @@ export class AttributionSDK {
49
52
  }
50
53
  try {
51
54
  this.logger.info("Initializing GetuAI Attribution SDK");
52
- // Initialize storage (IndexedDB failure should not block SDK initialization)
53
- try {
54
- await this.storage.init();
55
- }
56
- catch (storageError) {
55
+ // Initialize storage in background (IndexedDB failure should not block SDK initialization)
56
+ void this.storage.init().catch((storageError) => {
57
57
  this.logger.warn("Storage initialization failed (IndexedDB may be unavailable), continuing with basic features:", storageError);
58
- // Continue initialization even if IndexedDB fails
59
- // User ID and other features using cookie/localStorage will still work
60
- }
58
+ });
61
59
  // Initialize user ID (from config or existing storage)
62
60
  this.initializeUserId();
63
61
  // Initialize session
@@ -74,9 +72,14 @@ export class AttributionSDK {
74
72
  this.setupVisibilityHandlers();
75
73
  // Setup beforeunload handler
76
74
  this.setupBeforeUnloadHandler();
75
+ // Mark initialized as early as possible so auto page view can be queued
77
76
  this.initialized = true;
78
77
  this.logger.info("🚀 GetuAI Attribution SDK initialized successfully");
79
78
  this.logger.info("📄 Auto track page view = " + this.config.autoTrackPageView);
79
+ // Best-effort: retry pending events from last unload/redirect (do not block init)
80
+ void this.retryPendingEvents().catch((error) => {
81
+ this.logger.warn("⚠️ Pending events retry failed", error);
82
+ });
80
83
  // Auto track page view if enabled (independent from autoTrack)
81
84
  // Also enables SPA route tracking automatically
82
85
  if (this.config.autoTrackPageView) {
@@ -85,14 +88,17 @@ export class AttributionSDK {
85
88
  this.lastTrackedPath = this.getCurrentPath();
86
89
  // Setup SPA tracking for route changes
87
90
  this.setupSPATracking();
88
- setTimeout(() => {
89
- // Fire asynchronously; do not block initialization
90
- this.trackPageView()
91
+ // Fire ASAP (microtask) to survive short redirects (e.g. 50ms)
92
+ if (!this.initialPageViewTriggered) {
93
+ this.initialPageViewTriggered = true;
94
+ Promise.resolve()
95
+ .then(() => this.trackPageView())
96
+ .then(() => this.queue.process())
91
97
  .then(() => {
92
98
  this.logger.info("✅ Auto track page view completed");
93
99
  })
94
100
  .catch((error) => this.logger.error("❌ Auto track page view failed:", error));
95
- }, 100);
101
+ }
96
102
  }
97
103
  }
98
104
  catch (error) {
@@ -108,14 +114,9 @@ export class AttributionSDK {
108
114
  }
109
115
  try {
110
116
  const currentUrl = getCurrentUrl();
111
- // Try to fetch public IP (best-effort)
112
- let ip_address = null;
113
- try {
114
- ip_address = await this.fetchPublicIP();
115
- }
116
- catch (e) {
117
- // ignore
118
- }
117
+ // Use cached public IP (best-effort). Do not block tracking on network.
118
+ const ip_address = this.cachedPublicIP;
119
+ this.ensurePublicIPFetched();
119
120
  const pageContext = {
120
121
  domain: typeof window !== "undefined" ? window.location.hostname : null,
121
122
  path: typeof window !== "undefined" ? window.location.pathname : null,
@@ -188,6 +189,22 @@ export class AttributionSDK {
188
189
  }
189
190
  }
190
191
  }
192
+ ensurePublicIPFetched() {
193
+ if (this.cachedPublicIP || this.publicIPFetchPromise) {
194
+ return;
195
+ }
196
+ this.publicIPFetchPromise = this.fetchPublicIP()
197
+ .then((ip) => {
198
+ if (ip) {
199
+ this.cachedPublicIP = ip;
200
+ }
201
+ return ip;
202
+ })
203
+ .catch(() => null)
204
+ .finally(() => {
205
+ this.publicIPFetchPromise = null;
206
+ });
207
+ }
191
208
  // Best-effort fetch of public IP address
192
209
  async fetchPublicIP() {
193
210
  try {
@@ -683,6 +700,10 @@ export class AttributionSDK {
683
700
  // Setup visibility handlers
684
701
  setupVisibilityHandlers() {
685
702
  document.addEventListener("visibilitychange", () => {
703
+ if (document.visibilityState === "hidden") {
704
+ this.flushOnUnload("visibilitychange:hidden");
705
+ return;
706
+ }
686
707
  if (document.visibilityState === "visible") {
687
708
  this.updateSessionActivity();
688
709
  }
@@ -691,10 +712,64 @@ export class AttributionSDK {
691
712
  // Setup beforeunload handler
692
713
  setupBeforeUnloadHandler() {
693
714
  window.addEventListener("beforeunload", () => {
694
- this.updateSessionActivity();
695
- this.queue.flush();
715
+ this.flushOnUnload("beforeunload");
716
+ });
717
+ // More reliable than beforeunload for modern browsers (incl. mobile)
718
+ window.addEventListener("pagehide", () => {
719
+ this.flushOnUnload("pagehide");
696
720
  });
697
721
  }
722
+ flushOnUnload(reason) {
723
+ try {
724
+ this.updateSessionActivity();
725
+ const pending = this.queue.drainAll();
726
+ if (pending.length === 0) {
727
+ return;
728
+ }
729
+ // Backup first (best-effort). If keepalive succeeds, we'll remove by id.
730
+ this.storage.appendPendingEvents(pending);
731
+ this.logger.debug(`🚚 Unload flush triggered: ${reason}`, {
732
+ count: pending.length,
733
+ });
734
+ // Prefer beacon (avoid preflight) for redirect/unload scenarios.
735
+ const beaconOk = this.httpClient.sendEventsBeacon(pending);
736
+ if (beaconOk) {
737
+ // Best-effort: remove to avoid duplicates (beacon is queued by browser).
738
+ this.storage.removePendingEventsByIds(pending.map((e) => e.event_id));
739
+ return;
740
+ }
741
+ const chunkSize = 20;
742
+ for (let i = 0; i < pending.length; i += chunkSize) {
743
+ const chunk = pending.slice(i, i + chunkSize);
744
+ void this.httpClient
745
+ .sendEventsKeepalive(chunk)
746
+ .then(() => {
747
+ this.storage.removePendingEventsByIds(chunk.map((e) => e.event_id));
748
+ })
749
+ .catch((error) => {
750
+ this.logger.debug("Unload keepalive send failed", error);
751
+ });
752
+ }
753
+ }
754
+ catch (error) {
755
+ this.logger.debug("flushOnUnload failed", error);
756
+ }
757
+ }
758
+ async retryPendingEvents() {
759
+ const pending = this.storage.getPendingEvents();
760
+ if (pending.length === 0) {
761
+ return;
762
+ }
763
+ this.logger.info(`📦 Retrying pending events: ${pending.length}`);
764
+ try {
765
+ await this.httpClient.sendEvents(pending);
766
+ this.storage.removePendingEventsByIds(pending.map((e) => e.event_id));
767
+ this.logger.info(`✅ Pending events sent: ${pending.length}`);
768
+ }
769
+ catch (error) {
770
+ this.logger.warn("⚠️ Pending events retry failed", error);
771
+ }
772
+ }
698
773
  // Get current path (pathname + search) for comparison
699
774
  getCurrentPath() {
700
775
  if (typeof window === "undefined")
@@ -729,6 +804,10 @@ export class AttributionSDK {
729
804
  // Delay tracking to allow page title and content to update (100ms is sufficient for most frameworks)
730
805
  setTimeout(() => {
731
806
  this.trackPageView()
807
+ .then(() => {
808
+ // If auto page view is enabled, send ASAP to survive short redirects
809
+ return this.queue.process();
810
+ })
732
811
  .then(() => {
733
812
  this.logger.debug(`✅ [SPA] Page view tracked for: ${newPath}`);
734
813
  })
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.GetuAIAttribution=e():t.GetuAIAttribution=e()}(this,()=>(()=>{"use strict";var t,e,i={d:(t,e)=>{for(var r in e)i.o(e,r)&&!i.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},r={};i.d(r,{default:()=>J}),function(t){t.PAGE_VIEW="page_view",t.PAGE_CLICK="page_click",t.VIDEO_PLAY="video_play",t.FORM_SUBMIT="form_submit",t.EMAIL_VERIFICATION="email_verification",t.LOGIN="login",t.SIGNUP="signup",t.PRODUCT_VIEW="product_view",t.ADD_TO_CART="add_to_cart",t.PURCHASE="purchase",t.AUDIT_APPROVED="audit_approved"}(t||(t={})),function(t){t.USD="USD"}(e||(e={}));const a="https://attribution.getu.ai/attribution/api",n=[t.PURCHASE,t.LOGIN,t.SIGNUP,t.FORM_SUBMIT,t.EMAIL_VERIFICATION,t.AUDIT_APPROVED];function s(){return Math.floor(Date.now()/1e3)}function o(){try{const t="__localStorage_test__";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch{return!1}}class c{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 u(){return document.referrer||""}function l(){return window.location.href}function d(){return document.title||""}function h(t,e){try{const 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 g(t,e=["utm_source","utm_medium","utm_campaign"]){const i={};return e.forEach(e=>{t[e]&&(i[e]=t[e])}),i}function m(t){try{const e=t||window.location.href;return new URL(e).search}catch(t){return""}}function p(t){try{const e=t||window.location.href,i=new URL(e),r={};return i.searchParams.forEach((t,e)=>{r[e]=t}),r}catch(t){return{}}}class w{constructor(t){this.logger=t}get(t){try{if(!o())return this.logger.warn("LocalStorage not supported"),null;const e=localStorage.getItem(t);return null===e?null:JSON.parse(e)}catch(t){return this.logger.error("Error reading from localStorage:",t),null}}set(t,e){try{if(!o())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{o()&&localStorage.removeItem(t)}catch(t){this.logger.error("Error removing from localStorage:",t)}}clear(){try{o()&&localStorage.clear()}catch(t){this.logger.error("Error clearing localStorage:",t)}}handleQuotaExceeded(){try{const t=Object.keys(localStorage).filter(t=>t.startsWith("attribution_"));if(t.length>0){t.sort((t,e)=>{const i=this.get(t),r=this.get(e);return(i?.expiresAt||0)-(r?.expiresAt||0)});const 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 f{constructor(t){this.dbName="attribution_events",this.dbVersion=1,this.storeName="events",this.db=null,this.logger=t}async init(){if("indexedDB"in window)return new Promise((t,e)=>{const 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=>{const e=t.target.result;if(!e.objectStoreNames.contains(this.storeName)){const 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})}}});this.logger.warn("IndexedDB not supported")}async addEvent(t){if(!this.db)throw new Error("IndexedDB not initialized");return new Promise((e,i)=>{const r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName),a={...t,queued_at:Date.now(),sent:!1},n=r.add(a);n.onsuccess=()=>{this.logger.debug("Event added to IndexedDB queue"),e()},n.onerror=()=>{this.logger.error("Failed to add event to IndexedDB:",n.error),i(n.error)}})}async getUnsentEvents(t=100){return this.db?new Promise((e,i)=>{const r=this.db.transaction([this.storeName],"readonly").objectStore(this.storeName).index("sent").getAll(IDBKeyRange.only(!1),t);r.onsuccess=()=>{const t=r.result.map(t=>{const{queued_at:e,sent:i,...r}=t;return r});e(t)},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)=>{const r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName);let a=0,n=!1;t.forEach(s=>{const o=r.get(s);o.onsuccess=()=>{if(o.result){const s={...o.result,sent:!0},c=r.put(s);c.onsuccess=()=>{a++,a!==t.length||n||e()},c.onerror=()=>{n=!0,this.logger.error("Failed to mark event as sent:",c.error),i(c.error)}}else a++,a!==t.length||n||e()},o.onerror=()=>{n=!0,this.logger.error("Failed to get event for marking as sent:",o.error),i(o.error)}})})}async cleanupOldEvents(t=6048e5){if(!this.db)return;const e=Date.now()-t;return new Promise((t,i)=>{const r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).index("queued_at").openCursor(IDBKeyRange.upperBound(e));r.onsuccess=()=>{const 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)=>{const 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)=>{const 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 y{constructor(t){this.UTM_STORAGE_KEY="attribution_utm_data",this.SESSION_STORAGE_KEY="attribution_session",this.USER_ID_KEY="getuai_user_id",this.USER_ID_COOKIE_EXPIRES=365,this.logger=t,this.localStorage=new w(t),this.indexedDB=new f(t)}setUserId(t){if(!t||""===t.trim())return void this.logger.warn("Cannot set empty user ID");const e=t.trim();try{this.setCookie(this.USER_ID_KEY,e,this.USER_ID_COOKIE_EXPIRES),this.logger.debug(`👤 User ID stored in cookie: ${e}`)}catch(t){this.logger.error("Failed to store user ID in cookie:",t)}try{"undefined"!=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(){try{if("undefined"!=typeof localStorage){const t=localStorage.getItem(this.USER_ID_KEY);if(t)return t}}catch(t){this.logger.debug("Failed to get user ID from localStorage:",t)}try{const t=this.getCookie(this.USER_ID_KEY);if(t){try{"undefined"!=typeof localStorage&&localStorage.setItem(this.USER_ID_KEY,t)}catch(t){}return t}}catch(t){this.logger.debug("Failed to get user ID from cookie:",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{"undefined"!=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)}}setCookie(t,e,i){try{const r=new Date;r.setTime(r.getTime()+24*i*60*60*1e3);const a=`${t}=${encodeURIComponent(e)};expires=${r.toUTCString()};path=/;SameSite=Lax`;document.cookie=a}catch(t){this.logger.error("Failed to set cookie:",t)}}getCookie(t){try{const 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=/;`}catch(t){this.logger.error("Failed to delete cookie:",t)}}async init(){await this.indexedDB.init()}storeUTMData(t){try{const 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.localStorage.set(this.UTM_STORAGE_KEY,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(){const t=this.localStorage.get(this.UTM_STORAGE_KEY);return t&&t.expiresAt&&t.expiresAt>Date.now()?t:(t&&this.localStorage.remove(this.UTM_STORAGE_KEY),null)}storeSession(t){this.localStorage.set(this.SESSION_STORAGE_KEY,t)}getSession(){return this.localStorage.get(this.SESSION_STORAGE_KEY)}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()}}class S{constructor(t,e,i,r=100,a=2e3,n=3,s=1e3,o){this.queue=[],this.processing=!1,this.batchTimer=null,this.logger=t,this.apiKey=e,this.apiEndpoint=i,this.batchSize=r,this.batchInterval=a,this.maxRetries=n,this.retryDelay=s,this.sendEvents=o,this.debouncedProcess=function(t){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>t(...i),100)}}(this.process.bind(this))}add(t){this.queue.push(t),this.logger.debug(`Event added to queue: ${t.event_type}`),n.includes(t.event_type)?(this.logger.debug(`Immediate event detected: ${t.event_type}, processing immediately`),this.processImmediate(t)):this.scheduleBatchProcessing()}async process(){if(!this.processing&&0!==this.queue.length){this.processing=!0;try{const t=this.queue.splice(0,this.batchSize);this.logger.debug(`Processing ${t.length} events from queue`),await this.sendEvents(t),this.logger.info(`Successfully processed ${t.length} events`)}catch(t){this.logger.error("Failed to process events:",t);const e=this.queue.splice(0,this.batchSize);return this.queue.unshift(...e),void setTimeout(()=>{this.processing=!1,this.debouncedProcess()},this.retryDelay)}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.logger.info(`Immediate event processed successfully: ${t.event_type}`)}catch(e){this.logger.error(`Failed to process immediate event: ${t.event_type}`,e),this.queue.unshift(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()}}class k{constructor(t,e,i,r=3,a=1e3){this.logger=t,this.apiKey=e,this.apiEndpoint=i,this.maxRetries=r,this.retryDelay=a}async sendEvents(t){if(0===t.length)return;const e={events:t.map(t=>({event_id:t.event_id,event_type:t.event_type,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()})),sdk_version:"0.2.4"};await async function(t,e=3,i=1e3){let r;for(let a=0;a<=e;a++)try{return await t()}catch(t){if(r=t,a===e)throw r;const n=i*Math.pow(2,a);await new Promise(t=>setTimeout(t,n))}throw r}(async()=>{const 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){const t=await i.text();throw new Error(`HTTP ${i.status}: ${t}`)}const r=await i.json();return this.logger.debug("Events sent successfully:",r),{result:r,sentEvents:t}},this.maxRetries,this.retryDelay)}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}}}class _{constructor(t){this.session=null,this.initialized=!1,this.autoTrackEnabled=!1,this.pageViewTrackTimes=new Map,this.spaTrackingEnabled=!1,this.lastTrackedPath="",this.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=null,this.config={apiEndpoint:a,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 c(this.config.enableDebug),this.storage=new y(this.logger),this.httpClient=new k(this.logger,this.config.apiKey,this.config.apiEndpoint||a,this.config.maxRetries,this.config.retryDelay),this.queue=new S(this.logger,this.config.apiKey,this.config.apiEndpoint||a,this.config.batchSize,this.config.batchInterval,this.config.maxRetries,this.config.retryDelay,t=>this.httpClient.sendEvents(t))}async init(){if(this.initialized)this.logger.warn("SDK already initialized");else try{this.logger.info("Initializing GetuAI Attribution SDK");try{await this.storage.init()}catch(t){this.logger.warn("Storage initialization failed (IndexedDB may be unavailable), continuing with basic features:",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.config.autoTrackPageView&&(this.logger.info("📄 Auto track page view enabled (including SPA route tracking)"),this.lastTrackedPath=this.getCurrentPath(),this.setupSPATracking(),setTimeout(()=>{this.trackPageView().then(()=>{this.logger.info("✅ Auto track page view completed")}).catch(t=>this.logger.error("❌ Auto track page view failed:",t))},100))}catch(t){throw this.logger.error("Failed to initialize SDK:",t),t}}async trackEvent(t,i,r,a,n=e.USD){if(this.initialized)try{const e=l();let o=null;try{o=await this.fetchPublicIP()}catch(t){}const c={domain:"undefined"!=typeof window?window.location.hostname:null,path:"undefined"!=typeof window?window.location.pathname:null,title:d(),referrer:u(),url:e.split("?")[0],querystring:m(e),query_params:p(e),ip_address:o},h={session_id:this.session?.sessionId,start_time:this.session?.startTime,last_activity:this.session?.lastActivity,page_views:this.session?.pageViews},g=r||this.getUserId(),w={event_id:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}),event_type:t,tracking_user_id:g||void 0,timestamp:s(),event_data:i,context:{page:c,session:h},revenue:a,currency:n,...this.getUTMParams()};this.logger.debug(`Tracking event: ${t}`,w),this.queue.add(w)}catch(e){this.logger.error(`Failed to track event ${t}:`,e)}else this.logger.warn("SDK not initialized, event not tracked")}async trackPageView(e,i){const r=l(),a=r.split("?")[0],n=Date.now(),s=this.config.pageViewDebounceInterval||5e3,o=this.pageViewTrackTimes.get(a);if(o&&n-o<s)return void this.logger.debug(`Page view debounced: ${a} (last tracked ${n-o}ms ago)`);const c={url:r,title:d(),referrer:u(),user_agent:navigator.userAgent||"",...e};await this.trackEvent(t.PAGE_VIEW,c,i),this.pageViewTrackTimes.set(a,n),this.cleanupPageViewTrackTimes()}cleanupPageViewTrackTimes(){const t=Date.now()-36e5;for(const[e,i]of this.pageViewTrackTimes.entries())i<t&&this.pageViewTrackTimes.delete(e)}async fetchPublicIP(){try{const 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;const 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(i,r,a=e.USD,n){await this.trackEvent(t.PURCHASE,n,i,r,a)}async trackLogin(e,i){await this.trackEvent(t.LOGIN,i,e)}async trackSignup(e,i){await this.trackEvent(t.SIGNUP,i,e)}async trackFormSubmit(e,i){await this.trackEvent(t.FORM_SUBMIT,i,e)}async trackVideoPlay(e,i){await this.trackEvent(t.VIDEO_PLAY,i,e)}async trackEmailVerification(e,i){await this.trackEvent(t.EMAIL_VERIFICATION,i,e)}async trackAuditApproved(e,i){await this.trackEvent(t.AUDIT_APPROVED,i,e)}async trackPurchaseAuto(i){const r=i.tracking_user_id||this.getUserId();r?await this.trackEvent(t.PURCHASE,i.purchaseData,r,i.revenue,i.currency||e.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(e){const i=e.tracking_user_id||this.getUserId();i?await this.trackEvent(t.LOGIN,e.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(e){const i=e.tracking_user_id||this.getUserId();i?await this.trackEvent(t.SIGNUP,e.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(e){const i=e.tracking_user_id||this.getUserId();i?await this.trackEvent(t.EMAIL_VERIFICATION,e.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(e,i){await this.trackEvent(t.PRODUCT_VIEW,i,e)}async trackAddToCart(e,i){await this.trackEvent(t.ADD_TO_CART,i,e)}async trackPageClick(e,i){await this.trackEvent(t.PAGE_CLICK,i,e)}getAttributionData(){return this.storage.getUTMData()}addUTMToURL(t){if(!this.config.enableCrossDomainUTM)return t;const e=this.getAttributionData();return e?h(t,g(e.lastTouch,this.config.crossDomainUTMParams)):t}getCurrentUTMParams(){const t=this.getAttributionData();return t?g(t.lastTouch,this.config.crossDomainUTMParams):{}}getUTMParams(){const t=this.getAttributionData();if(!t)return this.logger.debug("No attribution data available for UTM params"),{};const 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}initializeUserId(){if(this.config.userId)this.setUserId(this.config.userId),this.logger.info(`👤 User ID initialized from config: ${this.config.userId}`);else{const 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){t&&""!==t.trim()?(this.storage.setUserId(t),this.logger.info(`👤 User ID set: ${t}`)):this.logger.warn("Cannot set empty user ID")}getUserId(){return this.storage.getUserId()}removeUserId(){this.storage.removeUserId(),this.logger.info("👤 User ID removed")}initializeSession(){const t=this.storage.getSession(),e=Date.now();t&&e-t.lastActivity<this.config.sessionTimeout?this.session={...t,lastActivity:e}:this.session={sessionId:`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,startTime:e,lastActivity:e,pageViews:0},this.storage.storeSession(this.session),this.logger.debug("Session initialized:",this.session)}extractAndStoreUTMData(){const t=l(),e=function(t){const e=function(t){const e={};try{new URL(t).searchParams.forEach((t,i)=>{e[i]=t})}catch(t){}return e}(t),i={};return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(t=>{e[t]&&""!==e[t].trim()&&(i[t]=e[t].trim())}),i}(t);if(this.logger.debug("Extracting UTM params from URL:",t),this.logger.debug("Found UTM params:",e),0===Object.keys(e).length)return void this.logger.debug("No UTM parameters found in URL");const i={utm_source:e.utm_source||"",utm_medium:e.utm_medium||"",utm_campaign:e.utm_campaign||"",utm_term:e.utm_term||"",utm_content:e.utm_content||"",timestamp:Date.now()},r=this.getAttributionData(),a={firstTouch:r?.firstTouch||i,lastTouch:i,touchpoints:r?.touchpoints||[],expiresAt:Date.now()+2592e6};r&&r.lastTouch.utm_source===i.utm_source&&r.lastTouch.utm_campaign===i.utm_campaign||a.touchpoints.push(i),this.storage.storeUTMData(a),this.logger.info("UTM data extracted and stored successfully:",i),this.config.autoCleanUTM&&function(){try{const t=new URL(window.location.href);let 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",e=>{try{const i=e.target;if(!i)return;const r=this.serializeFormFields(i);this.trackEvent(t.FORM_SUBMIT,{...r,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){const e={};try{const i=new FormData(t);for(const[t,r]of i.entries()){const i=this.serializeFormValue(r);if(Object.prototype.hasOwnProperty.call(e,t)){const r=e[t];Array.isArray(r)?(r.push(i),e[t]=r):e[t]=[r,i]}else e[t]=i}const r=Array.from(t.elements),a=new Map;for(const t of r){const e=t.name;e&&!t.disabled&&(a.has(e)||a.set(e,[]),a.get(e).push(t))}a.forEach((t,i)=>{const r=t.some(t=>"radio"===t.type),a=t.some(t=>"checkbox"===t.type),n=t.some(t=>"file"===t.type),s=t.some(t=>"SELECT"===t.tagName&&t.multiple),o=t.some(t=>"password"===t.type);if(a){const r=t.filter(t=>"checkbox"===t.type).filter(t=>t.checked).map(t=>t.value||"on");return void(Object.prototype.hasOwnProperty.call(e,i)?Array.isArray(e[i])||(e[i]=[e[i],...r]):e[i]=r)}if(r){const r=t.filter(t=>"radio"===t.type).find(t=>t.checked);return void(Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r?r.value:null))}if(s){const r=t.find(t=>"SELECT"===t.tagName&&t.multiple);if(r){const t=Array.from(r.selectedOptions).map(t=>t.value);return void(Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t))}}if(n){const r=t.find(t=>"file"===t.type);if(r){const t=r.files?Array.from(r.files):[];return void(Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t.map(t=>this.serializeFormValue(t))))}}if(o)Object.prototype.hasOwnProperty.call(e,i)?e[i]="string"==typeof e[i]?"*****":e[i]:e[i]="*****";else if(!Object.prototype.hasOwnProperty.call(e,i)){const r=t[0];if("SELECT"===r.tagName){const t=r;e[i]=t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}else r.type,e[i]=r.value??""}})}catch(t){this.logger.error("Failed to serialize form fields:",t)}return e}serializeFormValue(t){return t instanceof File?{file_name:t.name,file_size:t.size,file_type:t.type}:t}setupLinkTracking(){document.addEventListener("click",t=>{const e=t.target.closest("a");e&&function(t){try{const 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;const i=t.href;if(function(t,e=[]){try{const i=new URL(t).hostname.toLowerCase();return e.some(t=>{const 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}`);const r=this.getAttributionData();if(!r)return void this.logger.debug("No UTM data available for cross-domain passing");const a=g(r.lastTouch,this.config.crossDomainUTMParams);if(0===Object.keys(a).length)return void this.logger.debug("No UTM parameters to pass");const n=h(i,a);n!==i&&(t.href=n,this.logger.debug("UTM parameters added to external link:",{original:i,enhanced:n,utmParams:a}),this.logger.debug("Cross-domain UTM passed:",{link_url:n,original_url:i,utm_params_passed:a}))}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",()=>{"visible"===document.visibilityState&&this.updateSessionActivity()})}setupBeforeUnloadHandler(){window.addEventListener("beforeunload",()=>{this.updateSessionActivity(),this.queue.flush()})}getCurrentPath(){return"undefined"==typeof window?"":window.location.pathname+window.location.search}setupSPATracking(){if("undefined"==typeof window||"undefined"==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);const t=t=>{const e=this.getCurrentPath();e!==this.lastTrackedPath?(this.logger.debug(`🔄 [SPA] Route change detected (${t}): ${this.lastTrackedPath} -> ${e}`),this.lastTrackedPath=e,setTimeout(()=>{this.trackPageView().then(()=>{this.logger.debug(`✅ [SPA] Page view tracked for: ${e}`)}).catch(t=>{this.logger.error("❌ [SPA] Failed to track page view:",t)})},100)):this.logger.debug(`🔄 [SPA] Route change detected (${t}) but path unchanged: ${e}`)};history.pushState=(e,i,r)=>{const a=this.originalPushState(e,i,r);return t("pushState"),a},history.replaceState=(e,i,r)=>{const a=this.originalReplaceState(e,i,r);return t("replaceState"),a},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,currentParams: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 b=null;async function v(t){if(b)return console.warn("GetuAI SDK: Already initialized"),b;try{if(b=new _(t),await b.init(),t.enableDebug&&(window.GetuAISDK=b),console.log("GetuAI Attribution SDK initialized successfully"),"undefined"!=typeof window){const t=new CustomEvent("getuaiSDKReady",{detail:{sdk:b}});window.dispatchEvent(t)}return b}catch(t){if(console.error("GetuAI SDK: Failed to initialize:",t),"undefined"!=typeof window){const e=new CustomEvent("getuaiSDKError",{detail:{error:t}});window.dispatchEvent(e)}throw t}}function I(){return b}function D(){return new Promise((t,e)=>{if(b)return void t(b);const 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(new Error("SDK initialization timeout"))},1e4)})}async function E(t,i,r,a,n=e.USD){const s=I();s?await s.trackEvent(t,i,r,a,n):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function T(t,e){const i=I();i?await i.trackPageView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function A(t,i,r=e.USD,a){const n=I();n?await n.trackPurchase(t,i,r,a):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function P(t,e){const i=I();i?await i.trackLogin(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function U(t,e){const i=I();i?await i.trackSignup(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function C(t,e){const i=I();i?await i.trackFormSubmit(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function x(t,e){const i=I();i?await i.trackVideoPlay(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function K(t,e){const i=I();i?await i.trackEmailVerification(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function R(t){const e=I();e?await e.trackPurchaseAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function M(t){const e=I();e?await e.trackLoginAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function z(t){const e=I();e?await e.trackSignupAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function N(t){const e=I();e?await e.trackEmailVerificationAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function O(t,e){const i=I();i?await i.trackProductView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function L(t,e){const i=I();i?await i.trackAddToCart(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function V(t,e){const i=I();i?await i.trackPageClick(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function F(){const t=I();return t?t.getAttributionData():null}async function G(){const t=I();t?await t.flush():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function q(){const t=I();return t?t.getStatus():null}function $(t){const e=I();return e?e.addUTMToURL(t):(console.warn("GetuAI SDK: Not initialized. Call init() first."),t)}function B(){const t=I();return t?t.getCurrentUTMParams():{}}function j(t){const e=I();e?e.setUserId(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function H(){const t=I();return t?t.getUserId():(console.warn("GetuAI SDK: Not initialized. Call init() first."),null)}function Y(){const t=I();t?t.removeUserId():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function W(){b&&(b.destroy(),b=null,console.log("GetuAI SDK destroyed"))}class Q extends _{static async init(t){return await v(t)}static async trackEvent(t,i,r,a,n=e.USD){return await E(t,i,r,a,n)}static async trackPageView(t,e){return await T(t,e)}static async trackPurchase(t,i,r=e.USD,a){return await A(t,i,r,a)}static async trackLogin(t,e){return await P(t,e)}static async trackSignup(t,e){return await U(t,e)}static async trackFormSubmit(t,e){return await C(t,e)}static async trackVideoPlay(t,e){return await x(t,e)}static async trackEmailVerification(t,e){return await K(t,e)}static async trackPurchaseAuto(t){return await R(t)}static async trackLoginAuto(t){return await M(t)}static async trackSignupAuto(t){return await z(t)}static async trackEmailVerificationAuto(t){return await N(t)}static async trackProductView(t,e){return await O(t,e)}static async trackAddToCart(t,e){return await L(t,e)}static async trackPageClick(t,e){return await V(t,e)}static getAttributionData(){return F()}static async flush(){return await G()}static getStatus(){return q()}static addUTMToURL(t){return $(t)}static getCurrentUTMParams(){return B()}static setUserId(t){j(t)}static getUserId(){return H()}static removeUserId(){Y()}static destroy(){W()}static getSDK(){return I()}static waitForSDK(){return D()}}"undefined"!=typeof document&&function(){if(b)return;const t=document.currentScript;if(!t)return void console.warn("GetuAI SDK: Could not find script tag for auto-initialization");const e=t.getAttribute("data-api-key");e?v({apiKey:e,apiEndpoint:t.getAttribute("data-api-endpoint")||a,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}):console.warn("GetuAI SDK: No API key provided. Please add data-api-key attribute to script tag.")}(),"undefined"!=typeof window&&(window.getuaiSDK={init:v,getSDK:I,waitForSDK:D,trackEvent:E,trackPageView:T,trackPageClick:V,trackPurchase:A,trackLogin:P,trackSignup:U,trackFormSubmit:C,trackVideoPlay:x,trackEmailVerification:K,trackAuditApproved:async function(t,e){const i=I();i?await i.trackAuditApproved(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")},trackProductView:O,trackAddToCart:L,trackPurchaseAuto:R,trackLoginAuto:M,trackSignupAuto:z,trackEmailVerificationAuto:N,getAttributionData:F,flush:G,getStatus:q,addUTMToURL:$,getCurrentUTMParams:B,setUserId:j,getUserId:H,removeUserId:Y,destroy:W,EventType:t,Currency:e,AttributionSDK:Q},window.init=v,window.waitForSDK=D,window.trackEvent=E,window.trackPageView=T,window.trackPageClick=V,window.trackPurchase=A,window.trackLogin=P,window.trackSignup=U,window.trackFormSubmit=C,window.trackVideoPlay=x,window.trackEmailVerification=K,window.trackProductView=O,window.trackAddToCart=L,window.trackPurchaseAuto=R,window.trackLoginAuto=M,window.trackSignupAuto=z,window.trackEmailVerificationAuto=N,window.getAttributionData=F,window.flush=G,window.getStatus=q,window.addUTMToURL=$,window.getCurrentUTMParams=B,window.setUserId=j,window.getUserId=H,window.removeUserId=Y,window.destroy=W,window.AttributionSDK=Q);const J={init:v,getSDK:I,waitForSDK:D,trackEvent:E,trackPageView:T,trackPageClick:V,trackPurchase:A,trackLogin:P,trackSignup:U,trackFormSubmit:C,trackVideoPlay:x,trackEmailVerification:K,trackProductView:O,trackAddToCart:L,trackPurchaseAuto:R,trackLoginAuto:M,trackSignupAuto:z,trackEmailVerificationAuto:N,getAttributionData:F,flush:G,getStatus:q,addUTMToURL:$,getCurrentUTMParams:B,setUserId:j,getUserId:H,removeUserId:Y,destroy:W,EventType:t,Currency:e,AttributionSDK:Q};return r.default})());
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.GetuAIAttribution=e():t.GetuAIAttribution=e()}(this,()=>(()=>{"use strict";var t,e,i={d:(t,e)=>{for(var r in e)i.o(e,r)&&!i.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},r={};i.d(r,{default:()=>X}),function(t){t.PAGE_VIEW="page_view",t.PAGE_CLICK="page_click",t.VIDEO_PLAY="video_play",t.FORM_SUBMIT="form_submit",t.EMAIL_VERIFICATION="email_verification",t.LOGIN="login",t.SIGNUP="signup",t.PRODUCT_VIEW="product_view",t.ADD_TO_CART="add_to_cart",t.PURCHASE="purchase",t.AUDIT_APPROVED="audit_approved"}(t||(t={})),function(t){t.USD="USD"}(e||(e={}));const n="https://attribution.getu.ai/attribution/api",s=[t.PURCHASE,t.LOGIN,t.SIGNUP,t.FORM_SUBMIT,t.EMAIL_VERIFICATION,t.AUDIT_APPROVED];function a(){return Math.floor(Date.now()/1e3)}function o(){try{const t="__localStorage_test__";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch{return!1}}class c{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 u(){return document.referrer||""}function l(){return window.location.href}function d(){return document.title||""}function h(t,e){try{const 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 g(t,e=["utm_source","utm_medium","utm_campaign"]){const i={};return e.forEach(e=>{t[e]&&(i[e]=t[e])}),i}function m(t){try{const e=t||window.location.href;return new URL(e).search}catch(t){return""}}function p(t){try{const e=t||window.location.href,i=new URL(e),r={};return i.searchParams.forEach((t,e)=>{r[e]=t}),r}catch(t){return{}}}class f{constructor(t){this.logger=t}get(t){try{if(!o())return this.logger.warn("LocalStorage not supported"),null;const e=localStorage.getItem(t);return null===e?null:JSON.parse(e)}catch(t){return this.logger.error("Error reading from localStorage:",t),null}}set(t,e){try{if(!o())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{o()&&localStorage.removeItem(t)}catch(t){this.logger.error("Error removing from localStorage:",t)}}clear(){try{o()&&localStorage.clear()}catch(t){this.logger.error("Error clearing localStorage:",t)}}handleQuotaExceeded(){try{const t=Object.keys(localStorage).filter(t=>t.startsWith("attribution_"));if(t.length>0){t.sort((t,e)=>{const i=this.get(t),r=this.get(e);return(i?.expiresAt||0)-(r?.expiresAt||0)});const 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 w{constructor(t){this.dbName="attribution_events",this.dbVersion=1,this.storeName="events",this.db=null,this.logger=t}async init(){if("indexedDB"in window)return new Promise((t,e)=>{const 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=>{const e=t.target.result;if(!e.objectStoreNames.contains(this.storeName)){const 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})}}});this.logger.warn("IndexedDB not supported")}async addEvent(t){if(!this.db)throw new Error("IndexedDB not initialized");return new Promise((e,i)=>{const r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName),n={...t,queued_at:Date.now(),sent:!1},s=r.add(n);s.onsuccess=()=>{this.logger.debug("Event added to IndexedDB queue"),e()},s.onerror=()=>{this.logger.error("Failed to add event to IndexedDB:",s.error),i(s.error)}})}async getUnsentEvents(t=100){return this.db?new Promise((e,i)=>{const r=this.db.transaction([this.storeName],"readonly").objectStore(this.storeName).index("sent").getAll(IDBKeyRange.only(!1),t);r.onsuccess=()=>{const t=r.result.map(t=>{const{queued_at:e,sent:i,...r}=t;return r});e(t)},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)=>{const r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName);let n=0,s=!1;t.forEach(a=>{const o=r.get(a);o.onsuccess=()=>{if(o.result){const a={...o.result,sent:!0},c=r.put(a);c.onsuccess=()=>{n++,n!==t.length||s||e()},c.onerror=()=>{s=!0,this.logger.error("Failed to mark event as sent:",c.error),i(c.error)}}else n++,n!==t.length||s||e()},o.onerror=()=>{s=!0,this.logger.error("Failed to get event for marking as sent:",o.error),i(o.error)}})})}async cleanupOldEvents(t=6048e5){if(!this.db)return;const e=Date.now()-t;return new Promise((t,i)=>{const r=this.db.transaction([this.storeName],"readwrite").objectStore(this.storeName).index("queued_at").openCursor(IDBKeyRange.upperBound(e));r.onsuccess=()=>{const 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)=>{const 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)=>{const 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 y{constructor(t){this.UTM_STORAGE_KEY="attribution_utm_data",this.SESSION_STORAGE_KEY="attribution_session",this.USER_ID_KEY="getuai_user_id",this.PENDING_EVENTS_KEY="getuai_pending_events_v1",this.USER_ID_COOKIE_EXPIRES=365,this.logger=t,this.localStorage=new f(t),this.indexedDB=new w(t)}setUserId(t){if(!t||""===t.trim())return void this.logger.warn("Cannot set empty user ID");const e=t.trim();try{this.setCookie(this.USER_ID_KEY,e,this.USER_ID_COOKIE_EXPIRES),this.logger.debug(`👤 User ID stored in cookie: ${e}`)}catch(t){this.logger.error("Failed to store user ID in cookie:",t)}try{"undefined"!=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(){try{if("undefined"!=typeof localStorage){const t=localStorage.getItem(this.USER_ID_KEY);if(t)return t}}catch(t){this.logger.debug("Failed to get user ID from localStorage:",t)}try{const t=this.getCookie(this.USER_ID_KEY);if(t){try{"undefined"!=typeof localStorage&&localStorage.setItem(this.USER_ID_KEY,t)}catch(t){}return t}}catch(t){this.logger.debug("Failed to get user ID from cookie:",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{"undefined"!=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)}}setCookie(t,e,i){try{const r=new Date;r.setTime(r.getTime()+24*i*60*60*1e3);const n=`${t}=${encodeURIComponent(e)};expires=${r.toUTCString()};path=/;SameSite=Lax`;document.cookie=n}catch(t){this.logger.error("Failed to set cookie:",t)}}getCookie(t){try{const 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=/;`}catch(t){this.logger.error("Failed to delete cookie:",t)}}async init(){await this.indexedDB.init()}getPendingEvents(){try{const t=this.localStorage.get(this.PENDING_EVENTS_KEY);return Array.isArray(t)?t:[]}catch(t){return this.logger.debug("Failed to read pending events:",t),[]}}appendPendingEvents(t){if(t&&0!==t.length)try{const 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{const e=this.getPendingEvents();if(0===e.length)return;const 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{const 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.localStorage.set(this.UTM_STORAGE_KEY,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(){const t=this.localStorage.get(this.UTM_STORAGE_KEY);return t&&t.expiresAt&&t.expiresAt>Date.now()?t:(t&&this.localStorage.remove(this.UTM_STORAGE_KEY),null)}storeSession(t){this.localStorage.set(this.SESSION_STORAGE_KEY,t)}getSession(){return this.localStorage.get(this.SESSION_STORAGE_KEY)}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()}}const _="0.2.5";class v{constructor(t,e,i,r=100,n=2e3,s=3,a=1e3,o){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=s,this.retryDelay=a,this.sendEvents=o,this.debouncedProcess=function(t){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>t(...i),100)}}(this.process.bind(this))}add(t){if(s.includes(t.event_type))return this.logger.debug(`Immediate event detected: ${t.event_type}, sending immediately`),void this.processImmediate(t);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;const 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){return this.logger.error("Failed to process events:",e),this.enqueueBatchForRetry(t),void setTimeout(()=>{this.processing=!1,this.debouncedProcess()},this.retryDelay)}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(){const t=this.queue.splice(0,this.queue.length);return this.batchTimer&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.processing=!1,t}enqueueBatchForRetry(t){const e=[];for(const i of t){const t=(this.retryCounts.get(i.event_id)||0)+1;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)):e.push(i)}e.length>0&&this.queue.unshift(...e)}resetRetryCounts(t){for(const e of t)this.retryCounts.delete(e.event_id)}}class S{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;const e={events:t.map(t=>({event_id:t.event_id,event_type:t.event_type,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||a()})),sdk_version:_};await async function(t,e=3,i=1e3){let r;for(let n=0;n<=e;n++)try{return await t()}catch(t){if(r=t,n===e)throw r;const s=i*Math.pow(2,n);await new Promise(t=>setTimeout(t,s))}throw r}(async()=>{const 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){const t=await i.text();throw new Error(`HTTP ${i.status}: ${t}`)}const 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;const e={events:t.map(t=>({event_id:t.event_id,event_type:t.event_type,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||a()})),sdk_version:_},i=await fetch(`${this.apiEndpoint}/attribution/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(e),keepalive:!0});if(!i.ok)throw new Error(`HTTP ${i.status}`)}sendEventsBeacon(t){if(0===t.length)return!0;if("undefined"==typeof navigator||"function"!=typeof navigator.sendBeacon)return!1;const e={events:t.map(t=>({event_id:t.event_id,event_type:t.event_type,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||a()})),sdk_version:_},i=`${this.apiEndpoint}/attribution/events_beacon?api_key=${encodeURIComponent(this.apiKey)}`,r=new Blob([JSON.stringify(e)],{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}}}class k{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 c(this.config.enableDebug),this.storage=new y(this.logger),this.httpClient=new S(this.logger,this.config.apiKey,this.config.apiEndpoint||n,this.config.maxRetries,this.config.retryDelay),this.queue=new v(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))}async init(){if(this.initialized)this.logger.warn("SDK already initialized");else try{this.logger.info("Initializing GetuAI Attribution SDK"),this.storage.init().catch(t=>{this.logger.warn("Storage initialization failed (IndexedDB may be unavailable), continuing with basic features:",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,i,r,n,s=e.USD){if(this.initialized)try{const e=l(),o=this.cachedPublicIP;this.ensurePublicIPFetched();const c={domain:"undefined"!=typeof window?window.location.hostname:null,path:"undefined"!=typeof window?window.location.pathname:null,title:d(),referrer:u(),url:e.split("?")[0],querystring:m(e),query_params:p(e),ip_address:o},h={session_id:this.session?.sessionId,start_time:this.session?.startTime,last_activity:this.session?.lastActivity,page_views:this.session?.pageViews},g=r||this.getUserId(),f={event_id:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}),event_type:t,tracking_user_id:g||void 0,timestamp:a(),event_data:i,context:{page:c,session:h},revenue:n,currency:s,...this.getUTMParams()};this.logger.debug(`Tracking event: ${t}`,f),this.queue.add(f)}catch(e){this.logger.error(`Failed to track event ${t}:`,e)}else this.logger.warn("SDK not initialized, event not tracked")}async trackPageView(e,i){const r=l(),n=r.split("?")[0],s=Date.now(),a=this.config.pageViewDebounceInterval||5e3,o=this.pageViewTrackTimes.get(n);if(o&&s-o<a)return void this.logger.debug(`Page view debounced: ${n} (last tracked ${s-o}ms ago)`);const c={url:r,title:d(),referrer:u(),user_agent:navigator.userAgent||"",...e};await this.trackEvent(t.PAGE_VIEW,c,i),this.pageViewTrackTimes.set(n,s),this.cleanupPageViewTrackTimes()}cleanupPageViewTrackTimes(){const t=Date.now()-36e5;for(const[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{const 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;const 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(i,r,n=e.USD,s){await this.trackEvent(t.PURCHASE,s,i,r,n)}async trackLogin(e,i){await this.trackEvent(t.LOGIN,i,e)}async trackSignup(e,i){await this.trackEvent(t.SIGNUP,i,e)}async trackFormSubmit(e,i){await this.trackEvent(t.FORM_SUBMIT,i,e)}async trackVideoPlay(e,i){await this.trackEvent(t.VIDEO_PLAY,i,e)}async trackEmailVerification(e,i){await this.trackEvent(t.EMAIL_VERIFICATION,i,e)}async trackAuditApproved(e,i){await this.trackEvent(t.AUDIT_APPROVED,i,e)}async trackPurchaseAuto(i){const r=i.tracking_user_id||this.getUserId();r?await this.trackEvent(t.PURCHASE,i.purchaseData,r,i.revenue,i.currency||e.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(e){const i=e.tracking_user_id||this.getUserId();i?await this.trackEvent(t.LOGIN,e.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(e){const i=e.tracking_user_id||this.getUserId();i?await this.trackEvent(t.SIGNUP,e.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(e){const i=e.tracking_user_id||this.getUserId();i?await this.trackEvent(t.EMAIL_VERIFICATION,e.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(e,i){await this.trackEvent(t.PRODUCT_VIEW,i,e)}async trackAddToCart(e,i){await this.trackEvent(t.ADD_TO_CART,i,e)}async trackPageClick(e,i){await this.trackEvent(t.PAGE_CLICK,i,e)}getAttributionData(){return this.storage.getUTMData()}addUTMToURL(t){if(!this.config.enableCrossDomainUTM)return t;const e=this.getAttributionData();return e?h(t,g(e.lastTouch,this.config.crossDomainUTMParams)):t}getCurrentUTMParams(){const t=this.getAttributionData();return t?g(t.lastTouch,this.config.crossDomainUTMParams):{}}getUTMParams(){const t=this.getAttributionData();if(!t)return this.logger.debug("No attribution data available for UTM params"),{};const 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}initializeUserId(){if(this.config.userId)this.setUserId(this.config.userId),this.logger.info(`👤 User ID initialized from config: ${this.config.userId}`);else{const 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){t&&""!==t.trim()?(this.storage.setUserId(t),this.logger.info(`👤 User ID set: ${t}`)):this.logger.warn("Cannot set empty user ID")}getUserId(){return this.storage.getUserId()}removeUserId(){this.storage.removeUserId(),this.logger.info("👤 User ID removed")}initializeSession(){const t=this.storage.getSession(),e=Date.now();t&&e-t.lastActivity<this.config.sessionTimeout?this.session={...t,lastActivity:e}:this.session={sessionId:`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,startTime:e,lastActivity:e,pageViews:0},this.storage.storeSession(this.session),this.logger.debug("Session initialized:",this.session)}extractAndStoreUTMData(){const t=l(),e=function(t){const e=function(t){const e={};try{new URL(t).searchParams.forEach((t,i)=>{e[i]=t})}catch(t){}return e}(t),i={};return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(t=>{e[t]&&""!==e[t].trim()&&(i[t]=e[t].trim())}),i}(t);if(this.logger.debug("Extracting UTM params from URL:",t),this.logger.debug("Found UTM params:",e),0===Object.keys(e).length)return void this.logger.debug("No UTM parameters found in URL");const i={utm_source:e.utm_source||"",utm_medium:e.utm_medium||"",utm_campaign:e.utm_campaign||"",utm_term:e.utm_term||"",utm_content:e.utm_content||"",timestamp:Date.now()},r=this.getAttributionData(),n={firstTouch:r?.firstTouch||i,lastTouch:i,touchpoints:r?.touchpoints||[],expiresAt:Date.now()+2592e6};r&&r.lastTouch.utm_source===i.utm_source&&r.lastTouch.utm_campaign===i.utm_campaign||n.touchpoints.push(i),this.storage.storeUTMData(n),this.logger.info("UTM data extracted and stored successfully:",i),this.config.autoCleanUTM&&function(){try{const t=new URL(window.location.href);let 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",e=>{try{const i=e.target;if(!i)return;const r=this.serializeFormFields(i);this.trackEvent(t.FORM_SUBMIT,{...r,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){const e={};try{const i=new FormData(t);for(const[t,r]of i.entries()){const i=this.serializeFormValue(r);if(Object.prototype.hasOwnProperty.call(e,t)){const r=e[t];Array.isArray(r)?(r.push(i),e[t]=r):e[t]=[r,i]}else e[t]=i}const r=Array.from(t.elements),n=new Map;for(const t of r){const e=t.name;e&&!t.disabled&&(n.has(e)||n.set(e,[]),n.get(e).push(t))}n.forEach((t,i)=>{const r=t.some(t=>"radio"===t.type),n=t.some(t=>"checkbox"===t.type),s=t.some(t=>"file"===t.type),a=t.some(t=>"SELECT"===t.tagName&&t.multiple),o=t.some(t=>"password"===t.type);if(n){const r=t.filter(t=>"checkbox"===t.type).filter(t=>t.checked).map(t=>t.value||"on");return void(Object.prototype.hasOwnProperty.call(e,i)?Array.isArray(e[i])||(e[i]=[e[i],...r]):e[i]=r)}if(r){const r=t.filter(t=>"radio"===t.type).find(t=>t.checked);return void(Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r?r.value:null))}if(a){const r=t.find(t=>"SELECT"===t.tagName&&t.multiple);if(r){const t=Array.from(r.selectedOptions).map(t=>t.value);return void(Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t))}}if(s){const r=t.find(t=>"file"===t.type);if(r){const t=r.files?Array.from(r.files):[];return void(Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t.map(t=>this.serializeFormValue(t))))}}if(o)Object.prototype.hasOwnProperty.call(e,i)?e[i]="string"==typeof e[i]?"*****":e[i]:e[i]="*****";else if(!Object.prototype.hasOwnProperty.call(e,i)){const r=t[0];if("SELECT"===r.tagName){const t=r;e[i]=t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}else r.type,e[i]=r.value??""}})}catch(t){this.logger.error("Failed to serialize form fields:",t)}return e}serializeFormValue(t){return t instanceof File?{file_name:t.name,file_size:t.size,file_type:t.type}:t}setupLinkTracking(){document.addEventListener("click",t=>{const e=t.target.closest("a");e&&function(t){try{const 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;const i=t.href;if(function(t,e=[]){try{const i=new URL(t).hostname.toLowerCase();return e.some(t=>{const 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}`);const r=this.getAttributionData();if(!r)return void this.logger.debug("No UTM data available for cross-domain passing");const n=g(r.lastTouch,this.config.crossDomainUTMParams);if(0===Object.keys(n).length)return void this.logger.debug("No UTM parameters to pass");const s=h(i,n);s!==i&&(t.href=s,this.logger.debug("UTM parameters added to external link:",{original:i,enhanced:s,utmParams:n}),this.logger.debug("Cross-domain UTM passed:",{link_url:s,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?"visible"===document.visibilityState&&this.updateSessionActivity():this.flushOnUnload("visibilitychange:hidden")})}setupBeforeUnloadHandler(){window.addEventListener("beforeunload",()=>{this.flushOnUnload("beforeunload")}),window.addEventListener("pagehide",()=>{this.flushOnUnload("pagehide")})}flushOnUnload(t){try{this.updateSessionActivity();const 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));const i=20;for(let t=0;t<e.length;t+=i){const r=e.slice(t,t+i);this.httpClient.sendEventsKeepalive(r).then(()=>{this.storage.removePendingEventsByIds(r.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(){const 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"undefined"==typeof window?"":window.location.pathname+window.location.search}setupSPATracking(){if("undefined"==typeof window||"undefined"==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);const t=t=>{const e=this.getCurrentPath();e!==this.lastTrackedPath?(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)):this.logger.debug(`🔄 [SPA] Route change detected (${t}) but path unchanged: ${e}`)};history.pushState=(e,i,r)=>{const n=this.originalPushState(e,i,r);return t("pushState"),n},history.replaceState=(e,i,r)=>{const 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,currentParams: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 E=null;async function b(t){if(E)return console.warn("GetuAI SDK: Already initialized"),E;try{if(E=new k(t),await E.init(),t.enableDebug&&(window.GetuAISDK=E),console.log("GetuAI Attribution SDK initialized successfully"),"undefined"!=typeof window){const t=new CustomEvent("getuaiSDKReady",{detail:{sdk:E}});window.dispatchEvent(t)}return E}catch(t){if(console.error("GetuAI SDK: Failed to initialize:",t),"undefined"!=typeof window){const e=new CustomEvent("getuaiSDKError",{detail:{error:t}});window.dispatchEvent(e)}throw t}}function I(){return E}function T(){return new Promise((t,e)=>{if(E)return void t(E);const 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(new Error("SDK initialization timeout"))},1e4)})}async function P(t,i,r,n,s=e.USD){const a=I();a?await a.trackEvent(t,i,r,n,s):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function D(t,e){const i=I();i?await i.trackPageView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function A(t,i,r=e.USD,n){const s=I();s?await s.trackPurchase(t,i,r,n):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function U(t,e){const i=I();i?await i.trackLogin(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function C(t,e){const i=I();i?await i.trackSignup(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function x(t,e){const i=I();i?await i.trackFormSubmit(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function K(t,e){const i=I();i?await i.trackVideoPlay(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function N(t,e){const i=I();i?await i.trackEmailVerification(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function R(t){const e=I();e?await e.trackPurchaseAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function O(t){const e=I();e?await e.trackLoginAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function V(t){const e=I();e?await e.trackSignupAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function M(t){const e=I();e?await e.trackEmailVerificationAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function z(t,e){const i=I();i?await i.trackProductView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function F(t,e){const i=I();i?await i.trackAddToCart(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function L(t,e){const i=I();i?await i.trackPageClick(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function G(){const t=I();return t?t.getAttributionData():null}async function $(){const t=I();t?await t.flush():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function q(){const t=I();return t?t.getStatus():null}function B(t){const e=I();return e?e.addUTMToURL(t):(console.warn("GetuAI SDK: Not initialized. Call init() first."),t)}function j(){const t=I();return t?t.getCurrentUTMParams():{}}function Y(t){const e=I();e?e.setUserId(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function H(){const t=I();return t?t.getUserId():(console.warn("GetuAI SDK: Not initialized. Call init() first."),null)}function W(){const t=I();t?t.removeUserId():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function J(){E&&(E.destroy(),E=null,console.log("GetuAI SDK destroyed"))}class Q extends k{static async init(t){return await b(t)}static async trackEvent(t,i,r,n,s=e.USD){return await P(t,i,r,n,s)}static async trackPageView(t,e){return await D(t,e)}static async trackPurchase(t,i,r=e.USD,n){return await A(t,i,r,n)}static async trackLogin(t,e){return await U(t,e)}static async trackSignup(t,e){return await C(t,e)}static async trackFormSubmit(t,e){return await x(t,e)}static async trackVideoPlay(t,e){return await K(t,e)}static async trackEmailVerification(t,e){return await N(t,e)}static async trackPurchaseAuto(t){return await R(t)}static async trackLoginAuto(t){return await O(t)}static async trackSignupAuto(t){return await V(t)}static async trackEmailVerificationAuto(t){return await M(t)}static async trackProductView(t,e){return await z(t,e)}static async trackAddToCart(t,e){return await F(t,e)}static async trackPageClick(t,e){return await L(t,e)}static getAttributionData(){return G()}static async flush(){return await $()}static getStatus(){return q()}static addUTMToURL(t){return B(t)}static getCurrentUTMParams(){return j()}static setUserId(t){Y(t)}static getUserId(){return H()}static removeUserId(){W()}static destroy(){J()}static getSDK(){return I()}static waitForSDK(){return T()}}"undefined"!=typeof document&&function(){if(E)return;const t=document.currentScript;if(!t)return void console.warn("GetuAI SDK: Could not find script tag for auto-initialization");const e=t.getAttribute("data-api-key");e?b({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}):console.warn("GetuAI SDK: No API key provided. Please add data-api-key attribute to script tag.")}(),"undefined"!=typeof window&&(window.getuaiSDK={init:b,getSDK:I,waitForSDK:T,trackEvent:P,trackPageView:D,trackPageClick:L,trackPurchase:A,trackLogin:U,trackSignup:C,trackFormSubmit:x,trackVideoPlay:K,trackEmailVerification:N,trackAuditApproved:async function(t,e){const i=I();i?await i.trackAuditApproved(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")},trackProductView:z,trackAddToCart:F,trackPurchaseAuto:R,trackLoginAuto:O,trackSignupAuto:V,trackEmailVerificationAuto:M,getAttributionData:G,flush:$,getStatus:q,addUTMToURL:B,getCurrentUTMParams:j,setUserId:Y,getUserId:H,removeUserId:W,destroy:J,EventType:t,Currency:e,AttributionSDK:Q},window.init=b,window.waitForSDK=T,window.trackEvent=P,window.trackPageView=D,window.trackPageClick=L,window.trackPurchase=A,window.trackLogin=U,window.trackSignup=C,window.trackFormSubmit=x,window.trackVideoPlay=K,window.trackEmailVerification=N,window.trackProductView=z,window.trackAddToCart=F,window.trackPurchaseAuto=R,window.trackLoginAuto=O,window.trackSignupAuto=V,window.trackEmailVerificationAuto=M,window.getAttributionData=G,window.flush=$,window.getStatus=q,window.addUTMToURL=B,window.getCurrentUTMParams=j,window.setUserId=Y,window.getUserId=H,window.removeUserId=W,window.destroy=J,window.AttributionSDK=Q);const X={init:b,getSDK:I,waitForSDK:T,trackEvent:P,trackPageView:D,trackPageClick:L,trackPurchase:A,trackLogin:U,trackSignup:C,trackFormSubmit:x,trackVideoPlay:K,trackEmailVerification:N,trackProductView:z,trackAddToCart:F,trackPurchaseAuto:R,trackLoginAuto:O,trackSignupAuto:V,trackEmailVerificationAuto:M,getAttributionData:G,flush:$,getStatus:q,addUTMToURL:B,getCurrentUTMParams:j,setUserId:Y,getUserId:H,removeUserId:W,destroy:J,EventType:t,Currency:e,AttributionSDK:Q};return r.default})());