getu-attribution-v2-sdk 0.3.2 → 0.3.3
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.
- package/README.md +45 -10
- package/dist/core/AttributionSDK.d.ts +2 -1
- package/dist/core/AttributionSDK.d.ts.map +1 -1
- package/dist/core/AttributionSDK.js +13 -2
- package/dist/getuai-attribution.min.js +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +33 -3
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +33 -3
- package/dist/queue/index.d.ts.map +1 -1
- package/dist/queue/index.js +3 -0
- package/dist/types/index.d.ts +3 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +2 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -273,6 +273,9 @@ enum EventType {
|
|
|
273
273
|
|
|
274
274
|
// Post-conversion / back-office conversion
|
|
275
275
|
AUDIT_APPROVED = "audit_approved",
|
|
276
|
+
|
|
277
|
+
// User-defined custom events
|
|
278
|
+
CUSTOM = "custom",
|
|
276
279
|
}
|
|
277
280
|
```
|
|
278
281
|
|
|
@@ -564,21 +567,32 @@ await trackAddToCart("user_123", {
|
|
|
564
567
|
|
|
565
568
|
### Track Custom Event
|
|
566
569
|
|
|
570
|
+
Use `trackCustomEvent` to track any user-defined event with a custom name. The event name is required and must be non-empty.
|
|
571
|
+
|
|
567
572
|
```javascript
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
573
|
+
// Basic - event name only
|
|
574
|
+
await trackCustomEvent("webinar_registered");
|
|
575
|
+
|
|
576
|
+
// With custom data
|
|
577
|
+
await trackCustomEvent("webinar_registered", {
|
|
578
|
+
webinar_id: "webinar_123",
|
|
579
|
+
webinar_title: "Advanced Analytics",
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
// With user ID and revenue
|
|
583
|
+
await trackCustomEvent(
|
|
584
|
+
"subscription_upgraded",
|
|
585
|
+
{ plan: "pro", billing_cycle: "annual" },
|
|
576
586
|
"user_123", // tracking_user_id (optional)
|
|
577
|
-
|
|
578
|
-
Currency.USD // currency (optional)
|
|
587
|
+
299.00, // revenue (optional)
|
|
588
|
+
Currency.USD // currency (optional, default: USD)
|
|
579
589
|
);
|
|
580
590
|
```
|
|
581
591
|
|
|
592
|
+
Custom events are **batched** (not sent immediately). Use `flush()` to force-send pending events.
|
|
593
|
+
|
|
594
|
+
**Validation**: An empty or whitespace-only event name will be rejected client-side with a console error.
|
|
595
|
+
|
|
582
596
|
---
|
|
583
597
|
|
|
584
598
|
## Auto-Tracking
|
|
@@ -910,6 +924,27 @@ await trackAddToCart("user_123", {
|
|
|
910
924
|
});
|
|
911
925
|
```
|
|
912
926
|
|
|
927
|
+
#### `trackCustomEvent(customEventName, eventData?, tracking_user_id?, revenue?, currency?): Promise<void>`
|
|
928
|
+
|
|
929
|
+
Track a user-defined custom event. The `customEventName` is required and must be a non-empty string.
|
|
930
|
+
|
|
931
|
+
| Parameter | Type | Required | Description |
|
|
932
|
+
|-----------|------|----------|-------------|
|
|
933
|
+
| `customEventName` | string | **Yes** | Event name (e.g. `"webinar_registered"`) |
|
|
934
|
+
| `eventData` | object | No | Arbitrary key-value payload |
|
|
935
|
+
| `tracking_user_id` | string | No | User identifier; falls back to stored user ID |
|
|
936
|
+
| `revenue` | number | No | Revenue amount |
|
|
937
|
+
| `currency` | Currency | No | Currency code (default: `Currency.USD`) |
|
|
938
|
+
|
|
939
|
+
```javascript
|
|
940
|
+
await trackCustomEvent("feature_used", {
|
|
941
|
+
feature: "export_csv",
|
|
942
|
+
records_count: 500,
|
|
943
|
+
});
|
|
944
|
+
```
|
|
945
|
+
|
|
946
|
+
Custom events are **batched**. Call `flush()` to force immediate delivery.
|
|
947
|
+
|
|
913
948
|
### Attribution Functions
|
|
914
949
|
|
|
915
950
|
#### `getAttributionData(): AttributionData | null`
|
|
@@ -19,7 +19,8 @@ export declare class AttributionSDK {
|
|
|
19
19
|
private popstateHandler;
|
|
20
20
|
constructor(config: SDKConfig);
|
|
21
21
|
init(): Promise<void>;
|
|
22
|
-
trackEvent(eventType: EventType, eventData?: Record<string, any>, tracking_user_id?: string, revenue?: number, currency?: Currency): Promise<void>;
|
|
22
|
+
trackEvent(eventType: EventType, eventData?: Record<string, any>, tracking_user_id?: string, revenue?: number, currency?: Currency, custom_event_name?: string): Promise<void>;
|
|
23
|
+
trackCustomEvent(customEventName: string, eventData?: Record<string, any>, tracking_user_id?: string, revenue?: number, currency?: Currency): Promise<void>;
|
|
23
24
|
trackPageView(pageData?: Record<string, any>, tracking_user_id?: string): Promise<void>;
|
|
24
25
|
private cleanupPageViewTrackTimes;
|
|
25
26
|
private ensurePublicIPFetched;
|
|
@@ -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,EAGX,UAAU,EAEX,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,KAAK,CAAoB;IACjC,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,WAAW,CAAkB;IACrC,OAAO,CAAC,gBAAgB,CAAkB;IAC1C,OAAO,CAAC,kBAAkB,CAAkC;IAC5D,OAAO,CAAC,cAAc,CAAuB;IAC7C,OAAO,CAAC,oBAAoB,CAAuC;IACnE,OAAO,CAAC,wBAAwB,CAAkB;IAElD,OAAO,CAAC,kBAAkB,CAAkB;IAC5C,OAAO,CAAC,eAAe,CAAc;IACrC,OAAO,CAA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OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,kBAAkB;IAW1B;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAwCzB,OAAO,CAAC,iBAAiB;IAkBzB,OAAO,CAAC,oBAAoB;IAqD5B,OAAO,CAAC,oBAAoB;IAY5B,OAAO,CAAC,uBAAuB;IAa/B,OAAO,CAAC,wBAAwB;IAWhC,OAAO,CAAC,aAAa;YAwCP,kBAAkB;IAiBhC,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,gBAAgB;IAmFxB,OAAO,CAAC,kBAAkB;IAwB1B,OAAO,CAAC,qBAAqB;IAQvB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5B,SAAS,IAAI;QACX,WAAW,EAAE,OAAO,CAAC;QACrB,OAAO,EAAE,WAAW,GAAG,IAAI,CAAC;QAC5B,SAAS,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,OAAO,CAAC;QAChB,cAAc,EAAE;YACd,OAAO,EAAE,OAAO,CAAC;YACjB,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;SACvC,CAAC;QACF,WAAW,EAAE;YACX,OAAO,EAAE,OAAO,CAAC;YACjB,WAAW,EAAE,MAAM,CAAC;SACrB,CAAC;KACH;IAkBD,OAAO,IAAI,IAAI;CAOhB"}
|
|
@@ -106,8 +106,8 @@ export class AttributionSDK {
|
|
|
106
106
|
throw error;
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
|
-
// Track
|
|
110
|
-
async trackEvent(eventType, eventData, tracking_user_id, revenue, currency = Currency.USD) {
|
|
109
|
+
// Track event (internal: custom_event_name is the 6th param, only used for CUSTOM type)
|
|
110
|
+
async trackEvent(eventType, eventData, tracking_user_id, revenue, currency = Currency.USD, custom_event_name) {
|
|
111
111
|
if (!this.initialized) {
|
|
112
112
|
this.logger.warn("SDK not initialized, event not tracked");
|
|
113
113
|
return;
|
|
@@ -144,6 +144,9 @@ export class AttributionSDK {
|
|
|
144
144
|
context: { page: pageContext, session: sessionContext },
|
|
145
145
|
revenue: revenue,
|
|
146
146
|
currency: currency,
|
|
147
|
+
...(eventType === EventType.CUSTOM && custom_event_name
|
|
148
|
+
? { custom_event_name }
|
|
149
|
+
: {}),
|
|
147
150
|
...this.getUTMParams(),
|
|
148
151
|
};
|
|
149
152
|
this.logger.debug(`Tracking event: ${eventType}`, event);
|
|
@@ -154,6 +157,14 @@ export class AttributionSDK {
|
|
|
154
157
|
this.logger.error(`Failed to track event ${eventType}:`, error);
|
|
155
158
|
}
|
|
156
159
|
}
|
|
160
|
+
// Track custom event
|
|
161
|
+
async trackCustomEvent(customEventName, eventData, tracking_user_id, revenue, currency = Currency.USD) {
|
|
162
|
+
if (!customEventName || customEventName.trim() === "") {
|
|
163
|
+
this.logger.error("trackCustomEvent requires a non-empty customEventName");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
await this.trackEvent(EventType.CUSTOM, eventData, tracking_user_id, revenue, currency, customEventName.trim());
|
|
167
|
+
}
|
|
157
168
|
// Track page view
|
|
158
169
|
async trackPageView(pageData, tracking_user_id) {
|
|
159
170
|
const currentUrl = getCurrentUrl();
|
|
@@ -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:()=>tt}),function(t){t.PAGE_VIEW="page_view",t.PAGE_CLICK="page_click",t.BUTTON_CLICK="button_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],a={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 o(){return Math.floor(Date.now()/1e3)}function c(){try{const t="__localStorage_test__";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch{return!1}}class u{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 l(){return document.referrer||""}function d(){return window.location.href}function h(){return document.title||""}function g(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 m(t,e=["utm_source","utm_medium","utm_campaign"]){const i={};return e.forEach(e=>{t[e]&&(i[e]=t[e])}),i}function p(t){try{const e=t||window.location.href;return new URL(e).search}catch(t){return""}}function f(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(!c())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(!c())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{c()&&localStorage.removeItem(t)}catch(t){this.logger.error("Error removing from localStorage:",t)}}clear(){try{c()&&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 y{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 _{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_TRAITS_KEY="getuai_user_traits",this.USER_ID_COOKIE_EXPIRES=365,this.logger=t,this.localStorage=new w(t),this.indexedDB=new y(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()}setUserTraits(t){try{const e={...this.getUserTraits()||{},...t};"undefined"!=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("undefined"!=typeof localStorage){const 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{"undefined"!=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)}}}const v="0.3.2";class S{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 k{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||o()})),sdk_version:v};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||o()})),sdk_version:v},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||o()})),sdk_version:v},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 b{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 u(this.config.enableDebug),this.storage=new _(this.logger),this.httpClient=new k(this.logger,this.config.apiKey,this.config.apiEndpoint||n,this.config.maxRetries,this.config.retryDelay),this.queue=new S(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=d(),a=this.cachedPublicIP;this.ensurePublicIPFetched();const c={domain:"undefined"!=typeof window?window.location.hostname:null,path:"undefined"!=typeof window?window.location.pathname:null,title:h(),referrer:l(),url:e.split("?")[0],querystring:p(e),query_params:f(e),ip_address:a},u={session_id:this.session?.sessionId,start_time:this.session?.startTime,last_activity:this.session?.lastActivity,page_views:this.session?.pageViews},g=r||this.getUserId(),m={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:o(),event_data:i,context:{page:c,session:u},revenue:n,currency:s,...this.getUTMParams()};this.logger.debug(`Tracking event: ${t}`,m),this.queue.add(m)}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=d(),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:h(),referrer:l(),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)}async trackButtonClick(e,i,r){await this.trackEvent(t.BUTTON_CLICK,{button_name:e,...r},i)}getAttributionData(){return this.storage.getUTMData()}addUTMToURL(t){if(!this.config.enableCrossDomainUTM)return t;const e=this.getAttributionData();return e?g(t,m(e.lastTouch,this.config.crossDomainUTMParams)):t}getCurrentUTMParams(){const t=this.getAttributionData();return t?m(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")}async identify(e,i){this.initialized?e&&""!==e.trim()?(this.setUserId(e),i&&(this.storage.setUserTraits(i),this.logger.info(`User identified: ${e}`,i)),await this.trackEvent(t.FORM_SUBMIT,{_identify:!0,_user_traits:i,tracking_user_id:e},e)):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(){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=d(),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),n=this.extractLeadFields(r);n.email&&(this.storage.setUserTraits(n),this.logger.debug("Lead fields extracted from form:",n)),this.trackEvent(t.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){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(let t=0;t<r.length;t++){const e=r[t];if(e.disabled)continue;const i=e.tagName.toLowerCase(),s=e.type?.toLowerCase();if("button"===i||"submit"===s||"reset"===s)continue;const a=this.getFormFieldKey(e,t);a&&(n.has(a)||n.set(a,[]),n.get(a).push(e))}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}getFormFieldKey(t,e){const i=t.name;if(i)return i;if(t.id)return`id_${t.id}`;const r=t.getAttribute("aria-label");if(r&&r.trim())return`aria_${this.normalizeFormFieldKey(r)}`;const 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){const e={};for(const[i,r]of Object.entries(a))if(!e[i])for(const n of r||[]){const r=n.toLowerCase();for(const[n,s]of Object.entries(t))if((n.toLowerCase()===r||n.toLowerCase().includes(r))&&s&&"string"==typeof s&&s.trim()){e[i]=s.trim();break}if(e[i])break}return e.name||!e.first_name&&!e.last_name||(e.name=[e.first_name,e.last_name].filter(Boolean).join(" ").trim()),e}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=m(r.lastTouch,this.config.crossDomainUTMParams);if(0===Object.keys(n).length)return void this.logger.debug("No UTM parameters to pass");const s=g(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 I(t){if(E)return console.warn("GetuAI SDK: Already initialized"),E;try{if(E=new b(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 T(){return E}function P(){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 A(t,i,r,n,s=e.USD){const a=T();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=T();i?await i.trackPageView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function U(t,i,r=e.USD,n){const s=T();s?await s.trackPurchase(t,i,r,n):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function C(t,e){const i=T();i?await i.trackLogin(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function x(t,e){const i=T();i?await i.trackSignup(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function K(t,e){const i=T();i?await i.trackFormSubmit(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function N(t,e){const i=T();i?await i.trackVideoPlay(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function R(t,e){const i=T();i?await i.trackEmailVerification(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function F(t){const e=T();e?await e.trackPurchaseAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function O(t){const e=T();e?await e.trackLoginAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function L(t){const e=T();e?await e.trackSignupAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function z(t){const e=T();e?await e.trackEmailVerificationAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function M(t,e){const i=T();i?await i.trackProductView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function V(t,e){const i=T();i?await i.trackAddToCart(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function G(t,e){const i=T();i?await i.trackPageClick(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function $(t,e,i){const r=T();r?await r.trackButtonClick(t,e,i):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function B(){const t=T();return t?t.getAttributionData():null}async function q(){const t=T();t?await t.flush():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function j(){const t=T();return t?t.getStatus():null}function Y(t){const e=T();return e?e.addUTMToURL(t):(console.warn("GetuAI SDK: Not initialized. Call init() first."),t)}function H(){const t=T();return t?t.getCurrentUTMParams():{}}function J(t){const e=T();e?e.setUserId(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function W(){const t=T();return t?t.getUserId():(console.warn("GetuAI SDK: Not initialized. Call init() first."),null)}function Q(){const t=T();t?t.removeUserId():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function X(){E&&(E.destroy(),E=null,console.log("GetuAI SDK destroyed"))}class Z extends b{static async init(t){return await I(t)}static async trackEvent(t,i,r,n,s=e.USD){return await A(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 U(t,i,r,n)}static async trackLogin(t,e){return await C(t,e)}static async trackSignup(t,e){return await x(t,e)}static async trackFormSubmit(t,e){return await K(t,e)}static async trackVideoPlay(t,e){return await N(t,e)}static async trackEmailVerification(t,e){return await R(t,e)}static async trackPurchaseAuto(t){return await F(t)}static async trackLoginAuto(t){return await O(t)}static async trackSignupAuto(t){return await L(t)}static async trackEmailVerificationAuto(t){return await z(t)}static async trackProductView(t,e){return await M(t,e)}static async trackAddToCart(t,e){return await V(t,e)}static async trackPageClick(t,e){return await G(t,e)}static async trackButtonClick(t,e,i){return await $(t,e,i)}static getAttributionData(){return B()}static async flush(){return await q()}static getStatus(){return j()}static addUTMToURL(t){return Y(t)}static getCurrentUTMParams(){return H()}static setUserId(t){J(t)}static getUserId(){return W()}static removeUserId(){Q()}static destroy(){X()}static getSDK(){return T()}static waitForSDK(){return P()}}"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?I({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:I,getSDK:T,waitForSDK:P,trackEvent:A,trackPageView:D,trackPageClick:G,trackButtonClick:$,trackPurchase:U,trackLogin:C,trackSignup:x,trackFormSubmit:K,trackVideoPlay:N,trackEmailVerification:R,trackAuditApproved:async function(t,e){const i=T();i?await i.trackAuditApproved(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")},trackProductView:M,trackAddToCart:V,trackPurchaseAuto:F,trackLoginAuto:O,trackSignupAuto:L,trackEmailVerificationAuto:z,getAttributionData:B,flush:q,getStatus:j,addUTMToURL:Y,getCurrentUTMParams:H,setUserId:J,getUserId:W,removeUserId:Q,destroy:X,EventType:t,Currency:e,AttributionSDK:Z},window.init=I,window.waitForSDK=P,window.trackEvent=A,window.trackPageView=D,window.trackPageClick=G,window.trackButtonClick=$,window.trackPurchase=U,window.trackLogin=C,window.trackSignup=x,window.trackFormSubmit=K,window.trackVideoPlay=N,window.trackEmailVerification=R,window.trackProductView=M,window.trackAddToCart=V,window.trackPurchaseAuto=F,window.trackLoginAuto=O,window.trackSignupAuto=L,window.trackEmailVerificationAuto=z,window.getAttributionData=B,window.flush=q,window.getStatus=j,window.addUTMToURL=Y,window.getCurrentUTMParams=H,window.setUserId=J,window.getUserId=W,window.removeUserId=Q,window.destroy=X,window.AttributionSDK=Z);const tt={init:I,getSDK:T,waitForSDK:P,trackEvent:A,trackPageView:D,trackPageClick:G,trackButtonClick:$,trackPurchase:U,trackLogin:C,trackSignup:x,trackFormSubmit:K,trackVideoPlay:N,trackEmailVerification:R,trackProductView:M,trackAddToCart:V,trackPurchaseAuto:F,trackLoginAuto:O,trackSignupAuto:L,trackEmailVerificationAuto:z,getAttributionData:B,flush:q,getStatus:j,addUTMToURL:Y,getCurrentUTMParams:H,setUserId:J,getUserId:W,removeUserId:Q,destroy:X,EventType:t,Currency:e,AttributionSDK:Z};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:()=>et}),function(t){t.PAGE_VIEW="page_view",t.PAGE_CLICK="page_click",t.BUTTON_CLICK="button_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.CUSTOM="custom"}(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],a={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 o(){return Math.floor(Date.now()/1e3)}function c(){try{const t="__localStorage_test__";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch{return!1}}class u{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 l(){return document.referrer||""}function d(){return window.location.href}function h(){return document.title||""}function g(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 m(t,e=["utm_source","utm_medium","utm_campaign"]){const i={};return e.forEach(e=>{t[e]&&(i[e]=t[e])}),i}function p(t){try{const e=t||window.location.href;return new URL(e).search}catch(t){return""}}function f(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(!c())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(!c())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{c()&&localStorage.removeItem(t)}catch(t){this.logger.error("Error removing from localStorage:",t)}}clear(){try{c()&&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 y{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 _{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_TRAITS_KEY="getuai_user_traits",this.USER_ID_COOKIE_EXPIRES=365,this.logger=t,this.localStorage=new w(t),this.indexedDB=new y(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()}setUserTraits(t){try{const e={...this.getUserTraits()||{},...t};"undefined"!=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("undefined"!=typeof localStorage){const 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{"undefined"!=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)}}}const v="0.3.2";class S{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 k{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||o(),custom_event_name:t.custom_event_name||void 0})),sdk_version:v};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||o(),custom_event_name:t.custom_event_name||void 0})),sdk_version:v},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||o(),custom_event_name:t.custom_event_name||void 0})),sdk_version:v},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 E{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 u(this.config.enableDebug),this.storage=new _(this.logger),this.httpClient=new k(this.logger,this.config.apiKey,this.config.apiEndpoint||n,this.config.maxRetries,this.config.retryDelay),this.queue=new S(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(i,r,n,s,a=e.USD,c){if(this.initialized)try{const e=d(),u=this.cachedPublicIP;this.ensurePublicIPFetched();const g={domain:"undefined"!=typeof window?window.location.hostname:null,path:"undefined"!=typeof window?window.location.pathname:null,title:h(),referrer:l(),url:e.split("?")[0],querystring:p(e),query_params:f(e),ip_address:u},m={session_id:this.session?.sessionId,start_time:this.session?.startTime,last_activity:this.session?.lastActivity,page_views:this.session?.pageViews},w=n||this.getUserId(),y={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:i,tracking_user_id:w||void 0,timestamp:o(),event_data:r,context:{page:g,session:m},revenue:s,currency:a,...i===t.CUSTOM&&c?{custom_event_name:c}:{},...this.getUTMParams()};this.logger.debug(`Tracking event: ${i}`,y),this.queue.add(y)}catch(t){this.logger.error(`Failed to track event ${i}:`,t)}else this.logger.warn("SDK not initialized, event not tracked")}async trackCustomEvent(i,r,n,s,a=e.USD){i&&""!==i.trim()?await this.trackEvent(t.CUSTOM,r,n,s,a,i.trim()):this.logger.error("trackCustomEvent requires a non-empty customEventName")}async trackPageView(e,i){const r=d(),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:h(),referrer:l(),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)}async trackButtonClick(e,i,r){await this.trackEvent(t.BUTTON_CLICK,{button_name:e,...r},i)}getAttributionData(){return this.storage.getUTMData()}addUTMToURL(t){if(!this.config.enableCrossDomainUTM)return t;const e=this.getAttributionData();return e?g(t,m(e.lastTouch,this.config.crossDomainUTMParams)):t}getCurrentUTMParams(){const t=this.getAttributionData();return t?m(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")}async identify(e,i){this.initialized?e&&""!==e.trim()?(this.setUserId(e),i&&(this.storage.setUserTraits(i),this.logger.info(`User identified: ${e}`,i)),await this.trackEvent(t.FORM_SUBMIT,{_identify:!0,_user_traits:i,tracking_user_id:e},e)):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(){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=d(),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),n=this.extractLeadFields(r);n.email&&(this.storage.setUserTraits(n),this.logger.debug("Lead fields extracted from form:",n)),this.trackEvent(t.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){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(let t=0;t<r.length;t++){const e=r[t];if(e.disabled)continue;const i=e.tagName.toLowerCase(),s=e.type?.toLowerCase();if("button"===i||"submit"===s||"reset"===s)continue;const a=this.getFormFieldKey(e,t);a&&(n.has(a)||n.set(a,[]),n.get(a).push(e))}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}getFormFieldKey(t,e){const i=t.name;if(i)return i;if(t.id)return`id_${t.id}`;const r=t.getAttribute("aria-label");if(r&&r.trim())return`aria_${this.normalizeFormFieldKey(r)}`;const 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){const e={};for(const[i,r]of Object.entries(a))if(!e[i])for(const n of r||[]){const r=n.toLowerCase();for(const[n,s]of Object.entries(t))if((n.toLowerCase()===r||n.toLowerCase().includes(r))&&s&&"string"==typeof s&&s.trim()){e[i]=s.trim();break}if(e[i])break}return e.name||!e.first_name&&!e.last_name||(e.name=[e.first_name,e.last_name].filter(Boolean).join(" ").trim()),e}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=m(r.lastTouch,this.config.crossDomainUTMParams);if(0===Object.keys(n).length)return void this.logger.debug("No UTM parameters to pass");const s=g(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 b=null;async function T(t){if(b)return console.warn("GetuAI SDK: Already initialized"),b;try{if(b=new E(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 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 A(t,e){const i=I();i?await i.trackPageView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function U(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 C(t,e){const i=I();i?await i.trackLogin(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function x(t,e){const i=I();i?await i.trackSignup(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function K(t,e){const i=I();i?await i.trackFormSubmit(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function N(t,e){const i=I();i?await i.trackVideoPlay(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function R(t,e){const i=I();i?await i.trackEmailVerification(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function F(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 L(t){const e=I();e?await e.trackSignupAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function z(t){const e=I();e?await e.trackEmailVerificationAuto(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function M(t,i,r,n,s=e.USD){const a=I();a?await a.trackCustomEvent(t,i,r,n,s):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function V(t,e){const i=I();i?await i.trackProductView(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function G(t,e){const i=I();i?await i.trackAddToCart(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function $(t,e){const i=I();i?await i.trackPageClick(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")}async function B(t,e,i){const r=I();r?await r.trackButtonClick(t,e,i):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function q(){const t=I();return t?t.getAttributionData():null}async function j(){const t=I();t?await t.flush():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function Y(){const t=I();return t?t.getStatus():null}function H(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 W(t){const e=I();e?e.setUserId(t):console.warn("GetuAI SDK: Not initialized. Call init() first.")}function Q(){const t=I();return t?t.getUserId():(console.warn("GetuAI SDK: Not initialized. Call init() first."),null)}function X(){const t=I();t?t.removeUserId():console.warn("GetuAI SDK: Not initialized. Call init() first.")}function Z(){b&&(b.destroy(),b=null,console.log("GetuAI SDK destroyed"))}class tt extends E{static async init(t){return await T(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 A(t,e)}static async trackPurchase(t,i,r=e.USD,n){return await U(t,i,r,n)}static async trackLogin(t,e){return await C(t,e)}static async trackSignup(t,e){return await x(t,e)}static async trackFormSubmit(t,e){return await K(t,e)}static async trackVideoPlay(t,e){return await N(t,e)}static async trackEmailVerification(t,e){return await R(t,e)}static async trackPurchaseAuto(t){return await F(t)}static async trackLoginAuto(t){return await O(t)}static async trackSignupAuto(t){return await L(t)}static async trackEmailVerificationAuto(t){return await z(t)}static async trackCustomEvent(t,i,r,n,s=e.USD){return await M(t,i,r,n,s)}static async trackProductView(t,e){return await V(t,e)}static async trackAddToCart(t,e){return await G(t,e)}static async trackPageClick(t,e){return await $(t,e)}static async trackButtonClick(t,e,i){return await B(t,e,i)}static getAttributionData(){return q()}static async flush(){return await j()}static getStatus(){return Y()}static addUTMToURL(t){return H(t)}static getCurrentUTMParams(){return J()}static setUserId(t){W(t)}static getUserId(){return Q()}static removeUserId(){X()}static destroy(){Z()}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?T({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:T,getSDK:I,waitForSDK:D,trackEvent:P,trackPageView:A,trackPageClick:$,trackButtonClick:B,trackPurchase:U,trackLogin:C,trackSignup:x,trackFormSubmit:K,trackVideoPlay:N,trackEmailVerification:R,trackAuditApproved:async function(t,e){const i=I();i?await i.trackAuditApproved(t,e):console.warn("GetuAI SDK: Not initialized. Call init() first.")},trackCustomEvent:M,trackProductView:V,trackAddToCart:G,trackPurchaseAuto:F,trackLoginAuto:O,trackSignupAuto:L,trackEmailVerificationAuto:z,getAttributionData:q,flush:j,getStatus:Y,addUTMToURL:H,getCurrentUTMParams:J,setUserId:W,getUserId:Q,removeUserId:X,destroy:Z,EventType:t,Currency:e,AttributionSDK:tt},window.init=T,window.waitForSDK=D,window.trackEvent=P,window.trackPageView=A,window.trackPageClick=$,window.trackButtonClick=B,window.trackPurchase=U,window.trackLogin=C,window.trackSignup=x,window.trackFormSubmit=K,window.trackVideoPlay=N,window.trackEmailVerification=R,window.trackProductView=V,window.trackAddToCart=G,window.trackPurchaseAuto=F,window.trackLoginAuto=O,window.trackSignupAuto=L,window.trackEmailVerificationAuto=z,window.getAttributionData=q,window.flush=j,window.getStatus=Y,window.addUTMToURL=H,window.getCurrentUTMParams=J,window.setUserId=W,window.getUserId=Q,window.removeUserId=X,window.destroy=Z,window.AttributionSDK=tt);const et={init:T,getSDK:I,waitForSDK:D,trackEvent:P,trackPageView:A,trackPageClick:$,trackButtonClick:B,trackPurchase:U,trackLogin:C,trackSignup:x,trackFormSubmit:K,trackVideoPlay:N,trackEmailVerification:R,trackProductView:V,trackAddToCart:G,trackPurchaseAuto:F,trackLoginAuto:O,trackSignupAuto:L,trackEmailVerificationAuto:z,getAttributionData:q,flush:j,getStatus:Y,addUTMToURL:H,getCurrentUTMParams:J,setUserId:W,getUserId:Q,removeUserId:X,destroy:Z,EventType:t,Currency:e,AttributionSDK:tt};return r.default})());
|
package/dist/index.d.ts
CHANGED
|
@@ -30,6 +30,7 @@ declare function trackEmailVerificationAuto(options: {
|
|
|
30
30
|
verificationData?: Record<string, any>;
|
|
31
31
|
tracking_user_id?: string;
|
|
32
32
|
}): Promise<void>;
|
|
33
|
+
declare function trackCustomEvent(customEventName: string, eventData?: Record<string, any>, tracking_user_id?: string, revenue?: number, currency?: Currency): Promise<void>;
|
|
33
34
|
declare function trackProductView(tracking_user_id?: string, productData?: Record<string, any>): Promise<void>;
|
|
34
35
|
declare function trackAddToCart(tracking_user_id?: string, cartData?: Record<string, any>): Promise<void>;
|
|
35
36
|
declare function trackPageClick(tracking_user_id?: string, clickData?: Record<string, any>): Promise<void>;
|
|
@@ -84,6 +85,7 @@ declare class AttributionSDKStatic extends AttributionSDK {
|
|
|
84
85
|
verificationData?: Record<string, any>;
|
|
85
86
|
tracking_user_id?: string;
|
|
86
87
|
}): Promise<void>;
|
|
88
|
+
static trackCustomEvent(customEventName: string, eventData?: Record<string, any>, tracking_user_id?: string, revenue?: number, currency?: Currency): Promise<void>;
|
|
87
89
|
static trackProductView(tracking_user_id?: string, productData?: Record<string, any>): Promise<void>;
|
|
88
90
|
static trackAddToCart(tracking_user_id?: string, cartData?: Record<string, any>): Promise<void>;
|
|
89
91
|
static trackPageClick(tracking_user_id?: string, clickData?: Record<string, any>): Promise<void>;
|
|
@@ -114,7 +116,7 @@ declare class AttributionSDKStatic extends AttributionSDK {
|
|
|
114
116
|
static waitForSDK(): Promise<AttributionSDK>;
|
|
115
117
|
}
|
|
116
118
|
export { EventType, Currency, type SDKConfig, type EventData, type AttributionData, };
|
|
117
|
-
export { init, getSDK, waitForSDK, trackEvent, trackPageView, trackPageClick, trackButtonClick, trackPurchase, trackLogin, trackSignup, trackFormSubmit, trackVideoPlay, trackEmailVerification, trackAuditApproved, trackProductView, trackAddToCart, trackPurchaseAuto, trackLoginAuto, trackSignupAuto, trackEmailVerificationAuto, getAttributionData, flush, getStatus, addUTMToURL, getCurrentUTMParams, setUserId, getUserId, removeUserId, destroy, };
|
|
119
|
+
export { init, getSDK, waitForSDK, trackEvent, trackPageView, trackPageClick, trackButtonClick, trackPurchase, trackLogin, trackSignup, trackFormSubmit, trackVideoPlay, trackEmailVerification, trackAuditApproved, trackCustomEvent, trackProductView, trackAddToCart, trackPurchaseAuto, trackLoginAuto, trackSignupAuto, trackEmailVerificationAuto, getAttributionData, flush, getStatus, addUTMToURL, getCurrentUTMParams, setUserId, getUserId, removeUserId, destroy, };
|
|
118
120
|
export { AttributionSDKStatic as AttributionSDK };
|
|
119
121
|
declare const _default: {
|
|
120
122
|
init: typeof init;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,SAAS,E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CAAC,cAAc,CAAC;CAG7C;AAGD,OAAO,EACL,SAAS,EACT,QAAQ,EACR,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,eAAe,GACrB,CAAC;AAGF,OAAO,EACL,IAAI,EACJ,MAAM,EACN,UAAU,EACV,UAAU,EACV,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,aAAa,EACb,UAAU,EACV,WAAW,EACX,eAAe,EACf,cAAc,EACd,sBAAsB,EACtB,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,0BAA0B,EAC1B,kBAAkB,EAClB,KAAK,EACL,SAAS,EACT,WAAW,EACX,mBAAmB,EACnB,SAAS,EACT,SAAS,EACT,YAAY,EACZ,OAAO,GACR,CAAC;AAGF,OAAO,EAAE,oBAAoB,IAAI,cAAc,EAAE,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+ElD,wBAgCE"}
|
package/dist/index.esm.js
CHANGED
|
@@ -19,6 +19,8 @@ var EventType;
|
|
|
19
19
|
EventType["PURCHASE"] = "purchase";
|
|
20
20
|
// Post-conversion / back-office conversion
|
|
21
21
|
EventType["AUDIT_APPROVED"] = "audit_approved";
|
|
22
|
+
// Custom event (user-defined name passed via custom_event_name field)
|
|
23
|
+
EventType["CUSTOM"] = "custom";
|
|
22
24
|
})(EventType || (EventType = {}));
|
|
23
25
|
// Currency types
|
|
24
26
|
var Currency;
|
|
@@ -1060,6 +1062,7 @@ class EventHttpClient {
|
|
|
1060
1062
|
event_data: event.event_data || null,
|
|
1061
1063
|
context: event.context || null,
|
|
1062
1064
|
timestamp: event.timestamp || getTimestamp(), // Convert to seconds
|
|
1065
|
+
custom_event_name: event.custom_event_name || undefined,
|
|
1063
1066
|
}));
|
|
1064
1067
|
const batchRequest = {
|
|
1065
1068
|
events: transformedEvents,
|
|
@@ -1108,6 +1111,7 @@ class EventHttpClient {
|
|
|
1108
1111
|
event_data: event.event_data || null,
|
|
1109
1112
|
context: event.context || null,
|
|
1110
1113
|
timestamp: event.timestamp || getTimestamp(),
|
|
1114
|
+
custom_event_name: event.custom_event_name || undefined,
|
|
1111
1115
|
}));
|
|
1112
1116
|
const batchRequest = {
|
|
1113
1117
|
events: transformedEvents,
|
|
@@ -1157,6 +1161,7 @@ class EventHttpClient {
|
|
|
1157
1161
|
event_data: event.event_data || null,
|
|
1158
1162
|
context: event.context || null,
|
|
1159
1163
|
timestamp: event.timestamp || getTimestamp(),
|
|
1164
|
+
custom_event_name: event.custom_event_name || undefined,
|
|
1160
1165
|
}));
|
|
1161
1166
|
const payload = {
|
|
1162
1167
|
events: transformedEvents,
|
|
@@ -1292,8 +1297,8 @@ class AttributionSDK {
|
|
|
1292
1297
|
throw error;
|
|
1293
1298
|
}
|
|
1294
1299
|
}
|
|
1295
|
-
// Track
|
|
1296
|
-
async trackEvent(eventType, eventData, tracking_user_id, revenue, currency = Currency.USD) {
|
|
1300
|
+
// Track event (internal: custom_event_name is the 6th param, only used for CUSTOM type)
|
|
1301
|
+
async trackEvent(eventType, eventData, tracking_user_id, revenue, currency = Currency.USD, custom_event_name) {
|
|
1297
1302
|
if (!this.initialized) {
|
|
1298
1303
|
this.logger.warn("SDK not initialized, event not tracked");
|
|
1299
1304
|
return;
|
|
@@ -1330,6 +1335,9 @@ class AttributionSDK {
|
|
|
1330
1335
|
context: { page: pageContext, session: sessionContext },
|
|
1331
1336
|
revenue: revenue,
|
|
1332
1337
|
currency: currency,
|
|
1338
|
+
...(eventType === EventType.CUSTOM && custom_event_name
|
|
1339
|
+
? { custom_event_name }
|
|
1340
|
+
: {}),
|
|
1333
1341
|
...this.getUTMParams(),
|
|
1334
1342
|
};
|
|
1335
1343
|
this.logger.debug(`Tracking event: ${eventType}`, event);
|
|
@@ -1340,6 +1348,14 @@ class AttributionSDK {
|
|
|
1340
1348
|
this.logger.error(`Failed to track event ${eventType}:`, error);
|
|
1341
1349
|
}
|
|
1342
1350
|
}
|
|
1351
|
+
// Track custom event
|
|
1352
|
+
async trackCustomEvent(customEventName, eventData, tracking_user_id, revenue, currency = Currency.USD) {
|
|
1353
|
+
if (!customEventName || customEventName.trim() === "") {
|
|
1354
|
+
this.logger.error("trackCustomEvent requires a non-empty customEventName");
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
await this.trackEvent(EventType.CUSTOM, eventData, tracking_user_id, revenue, currency, customEventName.trim());
|
|
1358
|
+
}
|
|
1343
1359
|
// Track page view
|
|
1344
1360
|
async trackPageView(pageData, tracking_user_id) {
|
|
1345
1361
|
const currentUrl = getCurrentUrl();
|
|
@@ -2437,6 +2453,15 @@ async function trackEmailVerificationAuto(options) {
|
|
|
2437
2453
|
}
|
|
2438
2454
|
await sdk.trackEmailVerificationAuto(options);
|
|
2439
2455
|
}
|
|
2456
|
+
// Track custom event
|
|
2457
|
+
async function trackCustomEvent(customEventName, eventData, tracking_user_id, revenue, currency = Currency.USD) {
|
|
2458
|
+
const sdk = getSDK();
|
|
2459
|
+
if (!sdk) {
|
|
2460
|
+
console.warn("GetuAI SDK: Not initialized. Call init() first.");
|
|
2461
|
+
return;
|
|
2462
|
+
}
|
|
2463
|
+
await sdk.trackCustomEvent(customEventName, eventData, tracking_user_id, revenue, currency);
|
|
2464
|
+
}
|
|
2440
2465
|
// Track product view
|
|
2441
2466
|
async function trackProductView(tracking_user_id, productData) {
|
|
2442
2467
|
const sdk = getSDK();
|
|
@@ -2604,6 +2629,10 @@ class AttributionSDKStatic extends AttributionSDK {
|
|
|
2604
2629
|
static async trackEmailVerificationAuto(options) {
|
|
2605
2630
|
return await trackEmailVerificationAuto(options);
|
|
2606
2631
|
}
|
|
2632
|
+
// Static method to track custom event
|
|
2633
|
+
static async trackCustomEvent(customEventName, eventData, tracking_user_id, revenue, currency = Currency.USD) {
|
|
2634
|
+
return await trackCustomEvent(customEventName, eventData, tracking_user_id, revenue, currency);
|
|
2635
|
+
}
|
|
2607
2636
|
// Static method to track product view
|
|
2608
2637
|
static async trackProductView(tracking_user_id, productData) {
|
|
2609
2638
|
return await trackProductView(tracking_user_id, productData);
|
|
@@ -2688,6 +2717,7 @@ if (typeof window !== "undefined") {
|
|
|
2688
2717
|
trackVideoPlay,
|
|
2689
2718
|
trackEmailVerification,
|
|
2690
2719
|
trackAuditApproved,
|
|
2720
|
+
trackCustomEvent,
|
|
2691
2721
|
trackProductView,
|
|
2692
2722
|
trackAddToCart,
|
|
2693
2723
|
trackPurchaseAuto,
|
|
@@ -2772,5 +2802,5 @@ var index = {
|
|
|
2772
2802
|
AttributionSDK: AttributionSDKStatic, // 包含带静态方法的AttributionSDK类
|
|
2773
2803
|
};
|
|
2774
2804
|
|
|
2775
|
-
export { AttributionSDKStatic as AttributionSDK, Currency, EventType, addUTMToURL, index as default, destroy, flush, getAttributionData, getCurrentUTMParams, getSDK, getStatus, getUserId, init, removeUserId, setUserId, trackAddToCart, trackAuditApproved, trackButtonClick, trackEmailVerification, trackEmailVerificationAuto, trackEvent, trackFormSubmit, trackLogin, trackLoginAuto, trackPageClick, trackPageView, trackProductView, trackPurchase, trackPurchaseAuto, trackSignup, trackSignupAuto, trackVideoPlay, waitForSDK };
|
|
2805
|
+
export { AttributionSDKStatic as AttributionSDK, Currency, EventType, addUTMToURL, index as default, destroy, flush, getAttributionData, getCurrentUTMParams, getSDK, getStatus, getUserId, init, removeUserId, setUserId, trackAddToCart, trackAuditApproved, trackButtonClick, trackCustomEvent, trackEmailVerification, trackEmailVerificationAuto, trackEvent, trackFormSubmit, trackLogin, trackLoginAuto, trackPageClick, trackPageView, trackProductView, trackPurchase, trackPurchaseAuto, trackSignup, trackSignupAuto, trackVideoPlay, waitForSDK };
|
|
2776
2806
|
//# sourceMappingURL=index.esm.js.map
|